org.bukkit.util.BlockIterator Java Examples

The following examples show how to use org.bukkit.util.BlockIterator. 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: CraftLivingEntity.java    From Thermos with GNU General Public License v3.0 6 votes vote down vote up
private List<Block> getLineOfSight(HashSet<Byte> transparent, int maxDistance, int maxLength) {
    if (maxDistance > 120) {
        maxDistance = 120;
    }
    ArrayList<Block> blocks = new ArrayList<Block>();
    Iterator<Block> itr = new BlockIterator(this, maxDistance);
    while (itr.hasNext()) {
        Block block = itr.next();
        blocks.add(block);
        if (maxLength != 0 && blocks.size() > maxLength) {
            blocks.remove(0);
        }
        int id = block.getTypeId();
        if (transparent == null) {
            if (id != 0) {
                break;
            }
        } else {
            if (!transparent.contains((byte) id)) {
                break;
            }
        }
    }
    return blocks;
}
 
Example #2
Source File: ArrowTurret.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
private boolean hasCleanShot(Location shootHere, Location targetHere) {
        double x = shootHere.getX();
        double y = shootHere.getY();
        double z = shootHere.getZ();

        double x1 = targetHere.getX();
        double y1 = targetHere.getY();
        double z1 = targetHere.getZ();

        Vector start = new Vector(x, y, z);
        Vector end = new Vector (x1, y1, z1);

        BlockIterator bi = new BlockIterator(shootHere.getWorld(), start, end, 0, (int) shootHere.distance(targetHere));
        while (bi.hasNext()) {
            Block block = bi.next();
//            System.out.println(Civs.getPrefix() + ((int) block.getLocation().getX()) +
//                    ":" + ((int) block.getLocation().getY()) + ":" +
//                    ((int) block.getLocation().getZ()) + " " + !Util.isSolidBlock(block.getType()));
            if (!Util.isSolidBlock(block.getType())) {
                return false;
            }
        }

        return true;
    }
 
Example #3
Source File: CraftLivingEntity.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
private List<Block> getLineOfSight(Set<Material> transparent, int maxDistance, int maxLength) {
    if (maxDistance > 120) {
        maxDistance = 120;
    }
    ArrayList<Block> blocks = new ArrayList<Block>();
    Iterator<Block> itr = new BlockIterator(this, maxDistance);
    while (itr.hasNext()) {
        Block block = itr.next();
        blocks.add(block);
        if (maxLength != 0 && blocks.size() > maxLength) {
            blocks.remove(0);
        }
        Material material = block.getType();
        if (transparent == null) {
            if (!material.equals(Material.AIR)) {
                break;
            }
        } else {
            if (!transparent.contains(material)) {
                break;
            }
        }
    }
    return blocks;
}
 
Example #4
Source File: SubCommand_Buy.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCommand(
        @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {
    if (!(sender instanceof Player)) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("Can't run command by Console", sender));
        return;
    }

    final BlockIterator bIt = new BlockIterator((LivingEntity) sender, 10);

    if (!bIt.hasNext()) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
        return;
    }

    while (bIt.hasNext()) {
        final Block b = bIt.next();
        final Shop shop = plugin.getShopManager().getShop(b.getLocation());

        if (shop != null) {
            if (shop.getModerator().isModerator(((Player) sender).getUniqueId()) || QuickShop.getPermissionManager().hasPermission(sender, "quickshop.other.control")) {
                shop.setShopType(ShopType.BUYING);
                // shop.setSignText();
                shop.update();
                MsgUtil.sendMessage(sender, MsgUtil.getMessage("command.now-buying", sender, Util.getItemStackName(shop.getItem())));
            } else {
                MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-managed-shop", sender));
            }
            return;
        }
    }

    MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
}
 
Example #5
Source File: DelsignCommand.java    From AreaShop with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(CommandSender sender, String[] args) {
	if(!sender.hasPermission("areashop.delsign")) {
		plugin.message(sender, "delsign-noPermission");
		return;
	}
	if(!(sender instanceof Player)) {
		plugin.message(sender, "cmd-onlyByPlayer");
		return;
	}
	Player player = (Player)sender;

	// Get the sign
	Block block = null;
	BlockIterator blockIterator = new BlockIterator(player, 100);
	while(blockIterator.hasNext() && block == null) {
		Block next = blockIterator.next();
		if(next.getType() != Material.AIR) {
			block = next;
		}
	}
	if(block == null || !Materials.isSign(block.getType())) {
		plugin.message(sender, "delsign-noSign");
		return;
	}
	RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
	if(regionSign == null) {
		plugin.message(sender, "delsign-noRegion");
		return;
	}
	plugin.message(sender, "delsign-success", regionSign.getRegion());
	regionSign.remove();
}
 
Example #6
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getHitBlock(ProjectileHitEvent event) {
	BlockIterator iterator = new BlockIterator(event.getEntity().getWorld(), event.getEntity().getLocation().toVector(), event.getEntity().getVelocity().normalize(), 0.0D, 4);
	Block hitBlock = null;
	while (iterator.hasNext()) {
		hitBlock = iterator.next();
		if (hitBlock.getType() != Material.AIR) {
			break;
		}
	}
	return hitBlock;
}
 
Example #7
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getHitBlock(ProjectileHitEvent event) {
	BlockIterator iterator = new BlockIterator(event.getEntity().getWorld(), event.getEntity().getLocation().toVector(), event.getEntity().getVelocity().normalize(), 0.0D, 4);
	Block hitBlock = null;
	while (iterator.hasNext()) {
		hitBlock = iterator.next();
		if (hitBlock.getType() != Material.AIR) {
			break;
		}
	}
	return hitBlock;
}
 
Example #8
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getHitBlock(ProjectileHitEvent event) {
	BlockIterator iterator = new BlockIterator(event.getEntity().getWorld(), event.getEntity().getLocation().toVector(), event.getEntity().getVelocity().normalize(), 0.0D, 4);
	Block hitBlock = null;
	while (iterator.hasNext()) {
		hitBlock = iterator.next();
		if (hitBlock.getType() != Material.AIR) {
			break;
		}
	}
	return hitBlock;
}
 
Example #9
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getHitBlock(ProjectileHitEvent event) {
	BlockIterator iterator = new BlockIterator(event.getEntity().getWorld(), event.getEntity().getLocation().toVector(), event.getEntity().getVelocity().normalize(), 0.0D, 4);
	Block hitBlock = null;
	while (iterator.hasNext()) {
		hitBlock = iterator.next();
		if (hitBlock.getType() != Material.AIR) {
			break;
		}
	}
	return hitBlock;
}
 
Example #10
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getHitBlock(ProjectileHitEvent event) {
	BlockIterator iterator = new BlockIterator(event.getEntity().getWorld(), event.getEntity().getLocation().toVector(), event.getEntity().getVelocity().normalize(), 0.0D, 4);
	Block hitBlock = null;
	while (iterator.hasNext()) {
		hitBlock = iterator.next();
		if (hitBlock.getType() != Material.AIR) {
			break;
		}
	}
	return hitBlock;
}
 
Example #11
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getHitBlock(ProjectileHitEvent event) {
	BlockIterator iterator = new BlockIterator(event.getEntity().getWorld(), event.getEntity().getLocation().toVector(), event.getEntity().getVelocity().normalize(), 0.0D, 4);
	Block hitBlock = null;
	while (iterator.hasNext()) {
		hitBlock = iterator.next();
		if (hitBlock.getType() != Material.AIR) {
			break;
		}
	}
	return hitBlock;
}
 
Example #12
Source File: VectorUtils.java    From AACAdditionPro with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get to know where the {@link Vector} intersects with a {@link org.bukkit.block.Block}.
 * Non-Occluding {@link Block}s as defined in {@link BlockUtils#isReallyOccluding(Material)} are ignored.
 *
 * @param start     the starting {@link Location}
 * @param direction the {@link Vector} which should be checked
 *
 * @return The length when the {@link Vector} intersects or 0 if no intersection was found
 */
public static double getDistanceToFirstIntersectionWithBlock(final Location start, final Vector direction)
{
    final int length = (int) Math.floor(direction.length());
    Preconditions.checkNotNull(start.getWorld(), "RayTrace: Unknown start world.");

    if (length >= 1) {
        if (RAY_TRACING) {
            RayTraceResult result = start.getWorld().rayTraceBlocks(start, direction, length, FluidCollisionMode.NEVER, true);
            // Hit nothing or the other player
            if (result == null || result.getHitBlock() == null) {
                return 0;
            }

            return start.toVector().distance(result.getHitPosition());
        } else {
            try {
                final BlockIterator blockIterator = new BlockIterator(start.getWorld(), start.toVector(), direction, 0, length);
                Block block;
                while (blockIterator.hasNext()) {
                    block = blockIterator.next();
                    // Account for a Spigot bug: BARRIER and MOB_SPAWNER are not occluding blocks
                    if (BlockUtils.isReallyOccluding(block.getType())) {
                        // Use the middle location of the Block instead of the simple location.
                        return block.getLocation().clone().add(0.5, 0.5, 0.5).distance(start);
                    }
                }
            } catch (IllegalStateException exception) {
                // Just in case the start block could not be found for some reason or a chunk is loaded async.
                return 0;
            }
        }
    }
    return 0;
}
 
Example #13
Source File: BlockLineIterator.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param start
 * @param dir
 * @param dist
 * @throws IllegalStateException randomly (Bukkit bug)
 */
public BlockLineIterator(final Location start, final Vector dir, final double dist) throws IllegalStateException {
	super(new BlockIterator(start.getWorld(), fitInWorld(start, dir), dir, 0, 0), new NullableChecker<Block>() {
		private final double distSq = dist * dist;
		
		@Override
		public boolean check(final @Nullable Block b) {
			return b != null && b.getLocation().add(0.5, 0.5, 0.5).distanceSquared(start) >= distSq;
		}
	}, false);
}
 
Example #14
Source File: ProjectileMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onProjectileHitEvent(ProjectileHitEvent event) {
    final Projectile projectile = event.getEntity();
    final ProjectileDefinition projectileDefinition = Projectiles.getProjectileDefinition(projectile);
    if(projectileDefinition == null) return;

    final Filter filter = projectileDefinition.destroyFilter();
    if(filter == null) return;

    final BlockIterator blockIterator = new BlockIterator(projectile.getWorld(), projectile.getLocation().toVector(), projectile.getVelocity().normalize(), 0d, 2);
    Block hitBlock = null;
    while(blockIterator.hasNext()) {
        hitBlock = blockIterator.next();
        if(hitBlock.getType() != Material.AIR) break;
    }

    if(hitBlock != null) {
        final MatchPlayer shooter = projectile.getShooter() instanceof Player ? getMatch().getPlayer((Player) projectile.getShooter()) : null;
        final IQuery query = shooter != null ? new PlayerBlockEventQuery(shooter, event, hitBlock.getState())
                                             : new BlockEventQuery(event, hitBlock);

        if(filter.query(query).isAllowed()) {
            final BlockTransformEvent bte = new BlockTransformEvent(event, hitBlock, Material.AIR);
            match.callEvent(bte);

            if(!bte.isCancelled()) {
                hitBlock.setType(Material.AIR);
                projectile.remove();
            }
        }
    }
}
 
Example #15
Source File: TargetHelper.java    From ActionHealth with MIT License 5 votes vote down vote up
public Block getTarget(Location from, int distance, Set<Byte> transparentTypeIds) {
    BlockIterator itr = new BlockIterator(from, 0, distance);
    while (itr.hasNext()) {
        Block block = itr.next();
        int id = block.getType().getId();
        if (transparentTypeIds == null) {
            if (id == 0) continue;
        } else if (transparentTypeIds.contains((byte) id)) {
            continue;
        }
        return block;
    }
    return null;
}
 
Example #16
Source File: BlockInteractOcclusion.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void check(InteractWorldEvent e) {
    HawkPlayer pp = e.getHawkPlayer();
    Vector eyePos = pp.getPosition().clone().add(new Vector(0, pp.isSneaking() ? 1.54 : 1.62, 0));
    Vector direction = MathPlus.getDirection(pp.getYaw(), pp.getPitch());

    Location bLoc = e.getTargetedBlockLocation();
    Block b = bLoc.getBlock();
    WrappedBlock bNMS = WrappedBlock.getWrappedBlock(b, pp.getClientVersion());
    AABB targetAABB = new AABB(bNMS.getHitBox().getMin(), bNMS.getHitBox().getMax());

    double distance = targetAABB.distanceToPosition(eyePos);
    BlockIterator iter = new BlockIterator(pp.getWorld(), eyePos, direction, 0, (int) distance + 2);
    while (iter.hasNext()) {
        Block bukkitBlock = iter.next();

        if (bukkitBlock.getType() == Material.AIR || bukkitBlock.isLiquid())
            continue;
        if (bukkitBlock.getLocation().equals(bLoc))
            break;

        WrappedBlock iterBNMS = WrappedBlock.getWrappedBlock(bukkitBlock, pp.getClientVersion());
        AABB checkIntersection = new AABB(iterBNMS.getHitBox().getMin(), iterBNMS.getHitBox().getMax());
        Vector occludeIntersection = checkIntersection.intersectsRay(new Ray(eyePos, direction), 0, Float.MAX_VALUE);
        if (occludeIntersection != null) {
            if (occludeIntersection.distance(eyePos) < distance) {
                Placeholder ph = new Placeholder("type", iterBNMS.getBukkitBlock().getType());
                punishAndTryCancelAndBlockRespawn(pp, 1, e, ph);
                return;
            }
        }
    }
}
 
Example #17
Source File: SubCommand_Sell.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCommand(
        @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {
    if (!(sender instanceof Player)) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("Can't run command by Console", sender));
        return;
    }

    final BlockIterator bIt = new BlockIterator((LivingEntity) sender, 10);

    if (!bIt.hasNext()) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
        return;
    }

    while (bIt.hasNext()) {
        final Block b = bIt.next();
        final Shop shop = plugin.getShopManager().getShop(b.getLocation());

        if (shop != null) {
            if (shop.getModerator().isModerator(((Player) sender).getUniqueId()) || QuickShop.getPermissionManager().hasPermission(sender, "quickshop.other.control")) {
                shop.setShopType(ShopType.SELLING);
                // shop.setSignText();
                shop.update();
                MsgUtil.sendMessage(sender,
                        MsgUtil.getMessage("command.now-selling", sender, Util.getItemStackName(shop.getItem())));
                return;
            } else {
                MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-managed-shop", sender));
                return;
            }
        }
    }
    MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
}
 
Example #18
Source File: SubCommand_Remove.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCommand(
        @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {
    if (!(sender instanceof Player)) {
        MsgUtil.sendMessage(sender, ChatColor.RED + "Only players may use that command.");
        return;
    }

    final Player p = (Player) sender;
    final BlockIterator bIt = new BlockIterator(p, 10);

    if (!bIt.hasNext()) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
        return;
    }

    while (bIt.hasNext()) {
        final Block b = bIt.next();
        final Shop shop = plugin.getShopManager().getShop(b.getLocation());

        if (shop == null) {
            continue;
        }

        if (shop.getModerator().isModerator(((Player) sender).getUniqueId())
                || QuickShop.getPermissionManager().hasPermission(p, "quickshop.other.destroy")) {
            //shop.onUnload();
            shop.delete();
            plugin.log("Deleting shop "+shop+" request by /qs remove command.");
        } else {
            MsgUtil.sendMessage(sender, ChatColor.RED + MsgUtil.getMessage("no-permission", sender));
        }

        return;
    }

    MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
}
 
Example #19
Source File: SubCommand_Unlimited.java    From QuickShop-Reremake with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCommand(
        @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {
    if (!(sender instanceof Player)) {
        MsgUtil.sendMessage(sender, "Only player can run this command.");
        return;
    }

    final BlockIterator bIt = new BlockIterator((Player) sender, 10);

    if (!bIt.hasNext()) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
        return;
    }

    while (bIt.hasNext()) {
        final Block b = bIt.next();
        final Shop shop = plugin.getShopManager().getShop(b.getLocation());

        if (shop == null) {
            continue;
        }

        shop.setUnlimited(!shop.isUnlimited());
        // shop.setSignText();
        shop.update();

        if (shop.isUnlimited()) {
            MsgUtil.sendMessage(sender, MsgUtil.getMessage("command.toggle-unlimited.unlimited", sender));
            return;
        }

        MsgUtil.sendMessage(sender, MsgUtil.getMessage("command.toggle-unlimited.limited", sender));

        return;
    }

    MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
}
 
Example #20
Source File: FlagSnowballs.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
	Projectile projectile = event.getEntity();
	if (!(projectile instanceof Snowball)) {
		return;
	}
	
	ProjectileSource shooter = projectile.getShooter();
	if (!(shooter instanceof Player)) {
		return;
	}
	
	SpleefPlayer player = getHeavySpleef().getSpleefPlayer(shooter);
	GameManager manager = getHeavySpleef().getGameManager();
	Game game;
	
	if ((game = manager.getGame(player)) == null) {
		return;
	}

	Location location = projectile.getLocation();
	Vector start = location.toVector();
	Vector dir = projectile.getVelocity().normalize();
	
	BlockIterator iterator = new BlockIterator(projectile.getWorld(), start, dir, 0, 4);
	
	Block blockHit = null;
	
	while (iterator.hasNext()) {
		blockHit = iterator.next();
		
		if (blockHit.getType() != Material.AIR) {
			break;
		}
	}
	
	if (!game.canSpleef(blockHit)) {
		//Cannot remove this block
		return;
	}
	
	projectile.remove();
	game.addBlockBroken(player, blockHit);
	
	blockHit.setType(Material.AIR);
	if (game.getPropertyValue(GameProperty.PLAY_BLOCK_BREAK)) {
		blockHit.getWorld().playEffect(blockHit.getLocation(), Effect.STEP_SOUND, blockHit.getTypeId());
	}
}
 
Example #21
Source File: FlagSplegg.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
	Projectile projectile = event.getEntity();
	if (!(projectile instanceof Egg)) {
		return;
	}
	
	ProjectileSource source = projectile.getShooter();
	
	if (!(source instanceof Player)) {
		return;
	}
	
	SpleefPlayer shooter = getHeavySpleef().getSpleefPlayer(source);
	Game game = getHeavySpleef().getGameManager().getGame(shooter);
	if (game != this.game) {
		return;
	}
	
	projectile.remove();
	
	if (game == null || game.getGameState() != GameState.INGAME) {
		return;
	}
	
	// Use a BlockIterator to determine where the arrow has hit the ground
	BlockIterator blockIter = new BlockIterator(projectile.getWorld(), 
			projectile.getLocation().toVector(), 
			projectile.getVelocity().normalize(), 
			0, 4);
	
	Block blockHit = null;
	
	while (blockIter.hasNext()) {
		blockHit = blockIter.next();
		
		if (blockHit.getType() != Material.AIR) {
			break;
		}
	}
	
	if (!game.canSpleef(blockHit)) {
		//Cannot remove this block
		return;
	}
	
	game.addBlockBroken(shooter, blockHit);
	Material type = blockHit.getType();
	blockHit.setType(Material.AIR);
	
	World world = blockHit.getWorld();
	
	if (type == Material.TNT) {
		Location spawnLocation = blockHit.getLocation().add(0.5, 0, 0.5);
		TNTPrimed tnt = (TNTPrimed) world.spawnEntity(spawnLocation, EntityType.PRIMED_TNT);
		tnt.setMetadata(TNT_METADATA_KEY, new FixedMetadataValue(getHeavySpleef().getPlugin(), game));
		tnt.setYield(3);
		tnt.setFuseTicks(0);
	} else {
           Sound chickenEggPopSound = Game.getSoundEnumType("CHICKEN_EGG_POP", "CHICKEN_EGG");
           if (chickenEggPopSound != null) {
               projectile.getWorld().playSound(blockHit.getLocation(), chickenEggPopSound, 1.0f, 0.7f);
           }
	}
}
 
Example #22
Source File: ExtensionLobbyWall.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
public void loopSigns(SignLooper looper) {
	Vector startVec = new Vector(start.getBlockX(), start.getBlockY(), start.getBlockZ());
	Vector endVec = new Vector(end.getBlockX(), end.getBlockY(), end.getBlockZ());
	
	Vector directionVec = direction.mod();
	
	int maxDistance = Math.abs(direction == BlockFace2D.NORTH || direction == BlockFace2D.SOUTH ? endVec.getBlockZ() - startVec.getBlockZ()
			: endVec.getBlockX() - startVec.getBlockX());
          if (maxDistance == 0) {
              maxDistance = 1;
          }

	BlockIterator iterator = new BlockIterator(world, startVec, directionVec, 0, maxDistance);
	
	for (int i = 0; iterator.hasNext(); i++) {
		Block block = iterator.next();
		
		if (block.getType() != Material.WALL_SIGN) {
			continue;
		}

              Vector blockVec = block.getLocation().toVector();
              Map<String, Object> preMeta = metadata == null ? null : metadata.get(blockVec);

		Sign sign = (Sign) block.getState();
		WrappedMetadataSign wrappedMetadataSign = new WrappedMetadataSign(sign, preMeta);

		SignLooper.LoopReturn loopReturn = looper.loop(i, wrappedMetadataSign);
              if (preMeta == null && wrappedMetadataSign.metadataValues != null) {
                  if (metadata == null) {
                      enableSignMetadata();
                  }

                  metadata.put(blockVec, wrappedMetadataSign.metadataValues);
              }

		if (loopReturn == SignLooper.LoopReturn.CONTINUE) {
			continue;
		} else if (loopReturn == SignLooper.LoopReturn.BREAK) {
			break;
		} else if (loopReturn == SignLooper.LoopReturn.RETURN) {
			return;
		}
	}
}
 
Example #23
Source File: LoseCheckerTask.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
	for (Game game : gameManager.getGames()) {
		if (game.getGameState() != GameState.INGAME) {
			continue;
		}
		
		Set<SpleefPlayer> deathCandidates = null;
		final boolean isLiquidDeathzone = game.getPropertyValue(GameProperty.USE_LIQUID_DEATHZONE);
		
		for (SpleefPlayer player : game.getPlayers()) {
			Location playerLoc = player.getBukkitPlayer().getLocation();
			
			boolean isDeathCandidate = isInsideDeathzone(playerLoc, game, isLiquidDeathzone);
			if (!isDeathCandidate && recentLocations.containsKey(player)) {
				//Try to check every block the player has passed between the recent location and his location now
				Location recent = recentLocations.get(player);
				org.bukkit.util.Vector direction = playerLoc.clone().subtract(recent).toVector();
				int directionLength = (int) direction.length();
				
				if (directionLength > 0) {
					BlockIterator iterator = new BlockIterator(game.getWorld(), recent.toVector(), direction, 0D, directionLength);
					while (iterator.hasNext()) {
						Block passedBlock = iterator.next();
						
						if (isInsideDeathzone(passedBlock.getLocation(), game, isLiquidDeathzone)) {
							isDeathCandidate = true;
							break;
						}
					}
				}
			}
			
			if (isDeathCandidate) {
				//Lazy initialization for performance optimization
				if (deathCandidates == null) {
					deathCandidates = Sets.newHashSet();
				}
				
				deathCandidates.add(player);
			}
			
			recentLocations.put(player, playerLoc);
		}
		
		if (deathCandidates != null) {
			for (SpleefPlayer deathCandidate : deathCandidates) {
				game.requestLose(deathCandidate, QuitCause.LOSE);
			}
		}
	}
}
 
Example #24
Source File: Util.java    From ObsidianDestroyer with GNU General Public License v3.0 4 votes vote down vote up
public static List<Location> getTargetsPathBlocked(Location tLoc, Location dLoc, boolean useOnlyMaterialListing, boolean ignoreFirstZone) {
    final ArrayList<Location> targetsInPath = new ArrayList<Location>();

    // check world
    if (!dLoc.getWorld().getName().equalsIgnoreCase(tLoc.getWorld().getName())) {
        return targetsInPath;
    }

    // if the distance is too close... the path is not blocked ;)
    if (dLoc.distance(tLoc) <= 0.9) {
        return targetsInPath;
    }

    // try to iterate through blocks between dLoc and tLoc
    try {
        // Create a vector block trace from the detonator location to damaged block's location
        final Location tarLoc = tLoc.clone().add(0, 0.25, 0);
        final BlockIterator blocksInPath = new BlockIterator(tarLoc.getWorld(), dLoc.toVector(), tarLoc.toVector().subtract(dLoc.toVector()).normalize(), 0.5, (int) dLoc.distance(tarLoc));

        // iterate through the blocks in the path
        int i = ConfigManager.getInstance().getRadius() + 1;
        int over = 0; // prevents rare case of infinite loop and server crash
        while (blocksInPath.hasNext() && over < 128) {
            if (i > 0) {
                i--;
            } else {
                break;
            }
            over++;

            // the next block
            final Block block = blocksInPath.next();
            if (block == null) {
                continue;
            }
            // check if next block is the target block
            if (tarLoc.getWorld().getName().equals(block.getWorld().getName()) &&
                    tarLoc.getBlockX() == block.getX() &&
                    tarLoc.getBlockY() == block.getY() &&
                    tarLoc.getBlockZ() == block.getZ()) {
                // ignore target block
                continue;
            }
            // Ignore first blocks next to explosion
            if (ignoreFirstZone && ((i >= ConfigManager.getInstance().getRadius() - 1) || (dLoc.distance(tarLoc) <= 1.5))) {
                if (i >= ConfigManager.getInstance().getRadius() - 1 && MaterialManager.getInstance().contains(block.getType().name(), block.getData())) {
                    targetsInPath.add(block.getLocation());
                }
                continue;
            }

            // check if the block material is being handled
            if (useOnlyMaterialListing) {
                // only handle for certain case as to not interfere with all explosions
                if (MaterialManager.getInstance().contains(block.getType().name(), block.getData())) {
                    targetsInPath.add(block.getLocation());
                    continue;
                } else {
                    continue;
                }
            }
            // check if the block material is a solid
            if (!isNonSolid(block.getType())) {
                targetsInPath.add(block.getLocation());
                if (targetsInPath.size() > 3) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        // ignore the error and return no targets in path
    }
    return targetsInPath;
}
 
Example #25
Source File: Util.java    From ObsidianDestroyer with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isTargetsPathBlocked(Location tLoc, Location dLoc, boolean useOnlyMaterialListing) {

        // check world
        if (!dLoc.getWorld().getName().equalsIgnoreCase(tLoc.getWorld().getName())) {
            return false;
        }

        // if the distance is too close... the path is not blocked ;)
        if (dLoc.distance(tLoc) <= 0.9) {
            return false;
        }

        // try to iterate through blocks between dLoc and tLoc
        try {
            // Create a vector block trace from the detonator location to damaged block's location
            final BlockIterator blocksInPath = new BlockIterator(tLoc.getWorld(), dLoc.toVector(), tLoc.toVector().subtract(dLoc.toVector()).normalize(), 0.5, (int) dLoc.distance(tLoc));

            // iterate through the blocks in the path
            int over = 0; // prevents rare case of infinite loop and server crash
            while (blocksInPath.hasNext() && over < 128) {
                over++;
                // the next block
                final Block block = blocksInPath.next();
                if (block == null) {
                    continue;
                }
                // check if next block is the target block
                if (tLoc.getWorld().getName().equals(block.getWorld().getName()) &&
                        tLoc.getBlockX() == block.getX() &&
                        tLoc.getBlockY() == block.getY() &&
                        tLoc.getBlockZ() == block.getZ()) {
                    // ignore target block
                    continue;
                }

                // check if the block material is being handled
                if (useOnlyMaterialListing) {
                    // only handle for certain case as to not interfere with all explosions
                    if (MaterialManager.getInstance().contains(block.getType().name(), block.getData())) {
                        return true;
                    } else {
                        continue;
                    }
                }
                // check if the block material is a solid
                if (!isNonSolid(block.getType())) {
                    return true;
                }
            }
        } catch (Exception e) {
            // ignore the error and return no targets in path
        }
        return false;
    }
 
Example #26
Source File: AcidInventory.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Event that covers filling a bottle
 */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onWaterBottleFill(final PlayerInteractEvent e) {
    if (DEBUG)
        plugin.getLogger().info("DEBUG: " + e.getEventName());

    Player player = e.getPlayer();
    if (!player.getWorld().getName().equalsIgnoreCase(Settings.worldName))
        return;
    if (Settings.acidDamage == 0D || !Settings.acidBottle)
        return;
    if (!player.getItemInHand().getType().equals(Material.GLASS_BOTTLE)) {
        return;
    }
    // plugin.getLogger().info(e.getEventName() + " called");
    // Look at what the player was looking at
    BlockIterator iter = new BlockIterator(player, 10);
    Block lastBlock = iter.next();
    while (iter.hasNext()) {
        lastBlock = iter.next();
        if (lastBlock.getType() == Material.AIR)
            continue;
        break;
    }
    // plugin.getLogger().info(lastBlock.getType().toString());
    if (lastBlock.getType().equals(Material.WATER) || lastBlock.getType().equals(Material.STATIONARY_WATER)
            || lastBlock.getType().equals(Material.CAULDRON)) {
        // They *may* have filled a bottle with water
        // Check inventory for POTIONS in a tick
        plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
            @Override
            public void run() {
                // plugin.getLogger().info("Checking inventory");
                PlayerInventory inv = e.getPlayer().getInventory();
                if (inv.contains(Material.POTION)) {
                    // plugin.getLogger().info("POTION in inventory");
                    // They have a POTION of some kind in inventory
                    int i = 0;
                    for (ItemStack item : inv.getContents()) {
                        if (item != null) {
                            // plugin.getLogger().info(i + ":" +
                            // item.getType().toString());
                            if (item.getType().equals(Material.POTION)) {
                                NMSAbstraction nms = null;
                                try {
                                    nms = Util.checkVersion();
                                } catch (Exception ex) {
                                    return;
                                }
                                if (!nms.isPotion(item)) {
                                    // plugin.getLogger().info("Water bottle found!");
                                    ItemMeta meta = item.getItemMeta();
                                    meta.setDisplayName(plugin.myLocale(e.getPlayer().getUniqueId()).acidBottle);
                                    // ArrayList<String> lore = new
                                    // ArrayList<String>(Arrays.asList("Poison",
                                    // "Beware!", "Do not drink!"));
                                    meta.setLore(lore);
                                    item.setItemMeta(meta);
                                    inv.setItem(i, item);
                                }
                            }
                        }
                        i++;
                    }
                }
            }
        });
    }

}
 
Example #27
Source File: AddsignCommand.java    From AreaShop with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(CommandSender sender, String[] args) {
	if(!sender.hasPermission("areashop.addsign")) {
		plugin.message(sender, "addsign-noPermission");
		return;
	}
	if(!(sender instanceof Player)) {
		plugin.message(sender, "cmd-onlyByPlayer");
		return;
	}
	Player player = (Player)sender;

	// Get the sign
	Block block = null;
	BlockIterator blockIterator = new BlockIterator(player, 100);
	while(blockIterator.hasNext() && block == null) {
		Block next = blockIterator.next();
		if(next.getType() != Material.AIR) {
			block = next;
		}
	}
	if(block == null || !Materials.isSign(block.getType())) {
		plugin.message(sender, "addsign-noSign");
		return;
	}

	GeneralRegion region;
	if(args.length > 1) {
		// Get region by argument
		region = plugin.getFileManager().getRegion(args[1]);
		if(region == null) {
			plugin.message(sender, "cmd-notRegistered", args[1]);
			return;
		}
	} else {
		// Get region by sign position
		List<GeneralRegion> regions = Utils.getImportantRegions(block.getLocation());
		if(regions.isEmpty()) {
			plugin.message(sender, "addsign-noRegions");
			return;
		} else if(regions.size() > 1) {
			plugin.message(sender, "addsign-couldNotDetect", regions.get(0).getName(), regions.get(1).getName());
			return;
		}
		region = regions.get(0);
	}
	String profile = null;
	if(args.length > 2) {
		profile = args[2];
		Set<String> profiles = plugin.getConfig().getConfigurationSection("signProfiles").getKeys(false);
		if(!profiles.contains(profile)) {
			plugin.message(sender, "addsign-wrongProfile", Utils.createCommaSeparatedList(profiles), region);
			return;
		}
	}
	RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
	if(regionSign != null) {
		plugin.message(sender, "addsign-alreadyRegistered", regionSign.getRegion());
		return;
	}

	region.getSignsFeature().addSign(block.getLocation(), block.getType(), plugin.getBukkitHandler().getSignFacing(block), profile);
	if(profile == null) {
		plugin.message(sender, "addsign-success", region);
	} else {
		plugin.message(sender, "addsign-successProfile", profile, region);
	}
	region.update();
}
 
Example #28
Source File: ProjectileMatchModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onProjectileHitEvent(ProjectileHitEvent event) {
  Projectile projectile = event.getEntity();
  ProjectileDefinition projectileDefinition = getProjectileDefinition(projectile);
  if (projectileDefinition == null) return;
  Filter filter = projectileDefinition.destroyFilter;
  if (filter == null) return;

  BlockIterator it =
      new BlockIterator(
          projectile.getWorld(),
          projectile.getLocation().toVector(),
          projectile.getVelocity().normalize(),
          0d,
          2);

  Block hitBlock = null;
  while (it.hasNext()) {
    hitBlock = it.next();

    if (hitBlock.getType() != Material.AIR) {
      break;
    }
  }

  if (hitBlock != null) {
    MatchPlayer player =
        projectile.getShooter() instanceof Player
            ? match.getPlayer((Player) projectile.getShooter())
            : null;
    Query query =
        player != null
            ? new PlayerBlockQuery(event, player, hitBlock.getState())
            : new BlockQuery(event, hitBlock);

    if (filter.query(query).isAllowed()) {
      BlockTransformEvent bte = new BlockTransformEvent(event, hitBlock, Material.AIR);
      match.callEvent(bte);
      if (!bte.isCancelled()) {
        hitBlock.setType(Material.AIR);
        projectile.remove();
      }
    }
  }
}
 
Example #29
Source File: SubCommand_Refill.java    From QuickShop-Reremake with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCommand(
        @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {
    if (!(sender instanceof Player)) {
        MsgUtil.sendMessage(sender, "Can't run by Console");
        return;
    }

    if (cmdArg.length < 1) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("command.no-amount-given", sender));
        return;
    }

    final int add;

    try {
        add = Integer.parseInt(cmdArg[0]);
    } catch (NumberFormatException e) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("thats-not-a-number", sender));
        return;
    }

    final BlockIterator bIt = new BlockIterator((LivingEntity) sender, 10);

    if (!bIt.hasNext()) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
        return;
    }

    while (bIt.hasNext()) {
        final Block b = bIt.next();
        final Shop shop = plugin.getShopManager().getShop(b.getLocation());

        if (shop == null) {
            continue;
        }

        shop.add(shop.getItem(), add);
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("refill-success", sender));
        return;
    }

    MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
}
 
Example #30
Source File: SubCommand_SetOwner.java    From QuickShop-Reremake with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCommand(
        @NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {
    if (!(sender instanceof Player)) {
        MsgUtil.sendMessage(sender, "Only player can run this command");
        return;
    }

    if (cmdArg.length < 1) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("command.no-owner-given", sender));
        return;
    }

    final BlockIterator bIt = new BlockIterator((Player) sender, 10);

    if (!bIt.hasNext()) {
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
        return;
    }

    while (bIt.hasNext()) {
        final Block b = bIt.next();
        final Shop shop = plugin.getShopManager().getShop(b.getLocation());

        if (shop == null) {
            continue;
        }

        @SuppressWarnings("deprecation") final OfflinePlayer newShopOwner = plugin.getServer().getOfflinePlayer(cmdArg[0]);
        if (newShopOwner.getName() == null) {
            MsgUtil.sendMessage(sender, MsgUtil.getMessage("unknown-player", null));
            return;
        }
        shop.setOwner(newShopOwner.getUniqueId());
        //shop.setSignText();
        //shop.update();
        MsgUtil.sendMessage(sender, MsgUtil.getMessage("command.new-owner", sender, newShopOwner.getName()));
        return;
    }

    MsgUtil.sendMessage(sender, MsgUtil.getMessage("not-looking-at-shop", sender));
}