Java Code Examples for org.bukkit.Chunk#getEntities()

The following examples show how to use org.bukkit.Chunk#getEntities() . 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: SimpleChunkManager.java    From EntityAPI with GNU Lesser General Public License v3.0 7 votes vote down vote up
@EventHandler
public void onUnload(ChunkUnloadEvent event) {
    Chunk unloadedChunk = event.getChunk();
    for (Entity entity : unloadedChunk.getEntities()) {
        if (entity instanceof LivingEntity) {
            Object handle = BukkitUnwrapper.getInstance().unwrap(entity);
            if (handle instanceof ControllableEntityHandle) {
                ControllableEntity controllableEntity = ((ControllableEntityHandle) handle).getControllableEntity();
                if (controllableEntity != null && controllableEntity.isSpawned()) {
                    this.SPAWN_QUEUE.add(new EntityChunkData(controllableEntity, entity.getLocation()));
                    controllableEntity.despawn(DespawnReason.CHUNK_UNLOAD);
                }
            }
        }
    }
}
 
Example 2
Source File: HologramListener.java    From Holograms with MIT License 6 votes vote down vote up
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
    Chunk chunk = event.getChunk();
    for (Entity entity : chunk.getEntities()) {
        HologramEntity hologramEntity = plugin.getEntityController().getHologramEntity(entity);
        if (hologramEntity != null) {
            hologramEntity.remove();
        }
    }
    Collection<Hologram> holograms = plugin.getHologramManager().getActiveHolograms().values();
    for (Hologram holo : holograms) {
        Location loc = holo.getLocation();
        int chunkX = (int) Math.floor(loc.getBlockX() / 16.0D);
        int chunkZ = (int) Math.floor(loc.getBlockZ() / 16.0D);
        if (chunkX == chunk.getX() && chunkZ == chunk.getZ()) {
            holo.despawn();
        }
    }
}
 
Example 3
Source File: EventListener.java    From iDisguise with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onChunkUnload(ChunkUnloadEvent event) {
	final Chunk chunk = event.getChunk();
	final List<Integer> entityIds = new ArrayList<Integer>();
	for(Entity entity : chunk.getEntities()) {
		if(entity instanceof LivingEntity) {
			entityIds.add(entity.getEntityId());
		}
	}
	Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
		
		public void run() {
			if(!chunk.isLoaded()) {
				for(int entityId : entityIds) {
					EntityIdList.removeEntity(entityId);
				}
			}
		}
		
	}, 40L); // TODO: increase delay?
}
 
Example 4
Source File: DebugCommand.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
public void moveframes_cmd() throws CivException {
	Player player = getPlayer();
	Chunk chunk = player.getLocation().getChunk();
	
//	int x = this.getNamedInteger(1);
//	int y = this.getNamedInteger(2);
//	int z = this.getNamedInteger(3);
	
//	Location loc = new Location(player.getWorld(), x, y, z);
	
	for (Entity entity : chunk.getEntities()) {
		if (entity instanceof ItemFrame) {
			CivMessage.send(sender, "Teleported...");
			entity.teleport(entity.getLocation());
		}
	}
	
}
 
Example 5
Source File: GDClaim.java    From GriefDefender with MIT License 5 votes vote down vote up
public int countEntities(Entity spawnedEntity) {
    int count = 0;
    for (Chunk chunk : this.getChunks()) {
        for (Entity entity : chunk.getEntities()) {
            if (spawnedEntity.getType() == entity.getType()) {
                count++;
            }
        }
    }

    return count;
}
 
Example 6
Source File: ChunkListener.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public void cleanup(Chunk chunk) {
    for (Entity entity : chunk.getEntities()) {
        if (entity.getType() == EntityType.DROPPED_ITEM) {
            entity.remove();
        }
    }

}
 
Example 7
Source File: ChunkListener.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Prevent FireWorks from loading chunks
 * @param event
 */
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
    if (!Settings.IMP.TICK_LIMITER.FIREWORKS_LOAD_CHUNKS) {
        Chunk chunk = event.getChunk();
        Entity[] entities = chunk.getEntities();
        World world = chunk.getWorld();

        Exception e = new Exception();
        int start = 14;
        int end = 22;
        int depth = Math.min(end, getDepth(e));

        for (int frame = start; frame < depth; frame++) {
            StackTraceElement elem = getElement(e, frame);
            if (elem == null) return;
            String className = elem.getClassName();
            int len = className.length();
            if (className != null) {
                if (len > 15 && className.charAt(len - 15) == 'E' && className.endsWith("EntityFireworks")) {
                    for (Entity ent : world.getEntities()) {
                        if (ent.getType() == EntityType.FIREWORK) {
                            Vector velocity = ent.getVelocity();
                            double vertical = Math.abs(velocity.getY());
                            if (Math.abs(velocity.getX()) > vertical || Math.abs(velocity.getZ()) > vertical) {
                                Fawe.debug("[FAWE `tick-limiter`] Detected and cancelled rogue FireWork at " + ent.getLocation());
                                ent.remove();
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 8
Source File: ChunkRegenerator.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Teleport all the {@link Player}s within the given {@link Chunk} to spawn.
 * @param chunk Chunk to spawnteleport players in.
 */
private void spawnTeleportPlayers(@NotNull Chunk chunk) {
    for (Entity entity : chunk.getEntities()) {
        if (entity instanceof Player) {
            uSkyBlock.getInstance().getTeleportLogic().spawnTeleport((Player) entity, true);
        }
    }
}
 
Example 9
Source File: CivGlobal.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public static Entity getEntityAtLocation(Location loc) {
	
	Chunk chunk = loc.getChunk();
	for (Entity entity : chunk.getEntities()) {
		if (entity.getLocation().getBlock().equals(loc.getBlock())) {
			return entity;
		}
		
	}
	return null;
}
 
Example 10
Source File: DebugCommand.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public void show_cmd() throws CivException {
	Player player = getPlayer();
	Chunk chunk = player.getLocation().getChunk();
	
	for (Entity entity : chunk.getEntities()) {
		CivMessage.send(player, "E:"+entity.getType().name()+" UUID:"+entity.getUniqueId().toString());
		CivLog.info("E:"+entity.getType().name()+" UUID:"+entity.getUniqueId().toString());
	}
}
 
Example 11
Source File: GridManager.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes monsters around location l
 *
 * @param l location
 */
public void removeMobs(final Location l) {
    if (!inWorld(l)) {
        return;
    }
    //plugin.getLogger().info("DEBUG: removing mobs");
    // Don't remove mobs if at spawn
    if (this.isAtSpawn(l)) {
        //plugin.getLogger().info("DEBUG: at spawn!");
        return;
    }

    final int px = l.getBlockX();
    final int py = l.getBlockY();
    final int pz = l.getBlockZ();
    for (int x = -1; x <= 1; x++) {
        for (int z = -1; z <= 1; z++) {
            final Chunk c = l.getWorld().getChunkAt(new Location(l.getWorld(), px + x * 16, py, pz + z * 16));
            if (c.isLoaded()) {
                for (final Entity e : c.getEntities()) {
                    //plugin.getLogger().info("DEBUG: " + e.getType());
                    // Don't remove if the entity is an NPC or has a name tag
                    if (e.getCustomName() != null || e.hasMetadata("NPC"))
                        continue;
                    if (e instanceof Monster && !Settings.mobWhiteList.contains(e.getType())) {
                        e.remove();
                    }
                }
            }
        }
    }
}
 
Example 12
Source File: CommandClaimClear.java    From GriefDefender with MIT License 4 votes vote down vote up
@CommandCompletion("@gdentityids @gddummy")
@CommandAlias("claimclear")
@Description("Allows clearing of entities within one or more claims.")
@Syntax("<entity_id> [claim_uuid]")
@Subcommand("claim clear")
public void execute(Player player, String target, @Optional String claimId) {
    World world = player.getWorld();
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUID())) {
        GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_DISABLED_WORLD);
        return;
    }

    UUID claimUniqueId = null;
    GDClaim targetClaim = null;
    if (claimId == null) {
        targetClaim = GriefDefenderPlugin.getInstance().dataStore.getClaimAt(player.getLocation());
        final Component result = targetClaim.allowEdit(player);
        if (result != null) {
            GriefDefenderPlugin.sendMessage(player, result);
            return;
        }
        claimUniqueId = targetClaim.getUniqueId();
    } else {
        if (!player.hasPermission(GDPermissions.COMMAND_DELETE_CLAIMS)) {
            GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().COMMAND_CLAIMCLEAR_UUID_DENY);
            return;
        }
        try {
            claimUniqueId = UUID.fromString(claimId);
        } catch (IllegalArgumentException e) {
            return;
        }
    }

    if (targetClaim.isWilderness()) {
        GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_ACTION_NOT_AVAILABLE, 
                ImmutableMap.of("type", TextComponent.of("the wilderness"))));
        return;
    }

    int count = 0;
    String[] parts = target.split(":");
    if (parts.length > 1) {
        target = parts[1];
    }

    for (Chunk chunk : targetClaim.getChunks()) {
        for (Entity entity : chunk.getEntities()) {
            if (entity instanceof Player) {
                continue;
            }
            if (entity instanceof Villager || !(entity instanceof LivingEntity)) {
                continue;
            }
            if (entity instanceof Tameable) {
                final UUID ownerUniqueId = NMSUtil.getInstance().getTameableOwnerUUID(entity);
                if (ownerUniqueId != null && !ownerUniqueId.equals(player.getUniqueId())) {
                    continue;
                }
            }
            LivingEntity livingEntity = (LivingEntity) entity;

            String entityName = entity.getType().getName().toLowerCase();
            if (target.equalsIgnoreCase("any") || target.equalsIgnoreCase("all") || target.equalsIgnoreCase("minecraft") || target.equalsIgnoreCase(entityName)) {
                livingEntity.setHealth(0);
                count++;
            }
        }
    }

    if (count == 0) {
        GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.COMMAND_CLAIMCLEAR_NO_ENTITIES,
                ImmutableMap.of("type", TextComponent.of(target, TextColor.GREEN))));
    } else {
        GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.COMMAND_CLAIMCLEAR_NO_ENTITIES,
                ImmutableMap.of(
                    "amount", count,
                    "type", TextComponent.of(target, TextColor.GREEN))));
    }
}
 
Example 13
Source File: EntityTracker.java    From EliteMobs with GNU General Public License v3.0 4 votes vote down vote up
public static void chunkWiper(WorldUnloadEvent event) {
    for (Chunk chunk : event.getWorld().getLoadedChunks())
        for (Entity entity : chunk.getEntities())
            wipeEntity(entity);
}
 
Example 14
Source File: CivGlobal.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
public static void checkForEmptyDuplicateFrames(ItemFrameStorage frame) {
	
	if (frame.noFrame()) {
		return;
	}
	
	Chunk chunk = frame.getLocation().getChunk();
	ArrayList<Entity> removed = new ArrayList<Entity>();
	HashMap<Integer, Boolean> droppedItems = new HashMap<Integer, Boolean>();
	
	try {
		if (!frame.isEmpty()) {
			droppedItems.put(ItemManager.getId(frame.getItem()), true);
		}
	} catch (CivException e1) {
		e1.printStackTrace();
	}
	
	for (Entity entity : chunk.getEntities()) {
		if (entity instanceof ItemFrame) {
			if (frame.isOurEntity(entity)) {
				continue;
			}
			
			int x = frame.getLocation().getBlockX();
			int y = frame.getLocation().getBlockY();
			int z = frame.getLocation().getBlockZ();
			
			
			if (x == entity.getLocation().getBlockX() &&
				y == entity.getLocation().getBlockY() &&
				z == entity.getLocation().getBlockZ()) {
				// We have found a duplicate item frame here.

				ItemFrame eFrame = (ItemFrame)entity;
				boolean eFrameEmpty = (eFrame.getItem() == null || eFrame.getItem().getType().equals(Material.AIR));
			
				if (!eFrameEmpty) {
					Boolean droppedAlready = droppedItems.get(ItemManager.getId(eFrame.getItem()));
					if (droppedAlready == null || droppedAlready == false) {
						droppedItems.put(ItemManager.getId(eFrame.getItem()), true);
						eFrame.getLocation().getWorld().dropItemNaturally(eFrame.getLocation(), eFrame.getItem());
					}
				}
				
				removed.add(eFrame);
				
			}			
		}
	}
	
	for (Entity e : removed) {
		e.remove();
	}
	
	return;
}
 
Example 15
Source File: DebugCommand.java    From HolographicDisplays with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(CommandSender sender, String label, String[] args) throws CommandException {
	boolean foundAnyHologram = false;
	
	for (World world : Bukkit.getWorlds()) {
		Map<Hologram, HologramDebugInfo> hologramsDebugInfo = new HashMap<>();
		
		for (Chunk chunk : world.getLoadedChunks()) {
			for (Entity entity : chunk.getEntities()) {
				NMSEntityBase nmsEntity = HolographicDisplays.getNMSManager().getNMSEntityBase(entity);
				
				if (nmsEntity == null) {
					continue;
				}
				
				Hologram ownerHologram = nmsEntity.getHologramLine().getParent();
				HologramDebugInfo hologramDebugInfo = hologramsDebugInfo.computeIfAbsent(ownerHologram, mapKey -> new HologramDebugInfo());
				
				if (nmsEntity.isDeadNMS()) {
					hologramDebugInfo.deadEntities++;
				} else {
					hologramDebugInfo.aliveEntities++;
				}
			}
		}
		
		if (!hologramsDebugInfo.isEmpty()) {
			foundAnyHologram = true;
			sender.sendMessage(Colors.PRIMARY + "Holograms in world '" + world.getName() + "':");
			
			for (Entry<Hologram, HologramDebugInfo> entry : hologramsDebugInfo.entrySet()) {
				Hologram hologram = entry.getKey();
				String displayName = getHologramDisplayName(hologram);
				HologramDebugInfo debugInfo = entry.getValue();
				sender.sendMessage(Colors.PRIMARY_SHADOW + "- '" + displayName + "': " + hologram.size() + " lines, "
						+ debugInfo.getTotalEntities() + " entities (" + debugInfo.aliveEntities + " alive, " + debugInfo.deadEntities + " dead)");
			}
		}
	}
	
	if (!foundAnyHologram) {
		sender.sendMessage(Colors.ERROR + "Couldn't find any loaded hologram (holograms may be in unloaded chunks).");
	}
	
}
 
Example 16
Source File: Utils.java    From Shopkeepers with GNU General Public License v3.0 4 votes vote down vote up
public static List<Entity> getNearbyEntities(Location location, double radius, EntityType... types) {
	List<Entity> entities = new ArrayList<Entity>();
	if (location == null) return entities;
	if (radius <= 0.0D) return entities;

	double radius2 = radius * radius;
	int chunkRadius = ((int) (radius / 16)) + 1;
	Chunk center = location.getChunk();
	int startX = center.getX() - chunkRadius;
	int endX = center.getX() + chunkRadius;
	int startZ = center.getZ() - chunkRadius;
	int endZ = center.getZ() + chunkRadius;
	World world = location.getWorld();
	for (int chunkX = startX; chunkX <= endX; chunkX++) {
		for (int chunkZ = startZ; chunkZ <= endZ; chunkZ++) {
			if (!world.isChunkLoaded(chunkX, chunkZ)) continue;
			Chunk chunk = world.getChunkAt(chunkX, chunkZ);
			for (Entity entity : chunk.getEntities()) {
				Location entityLoc = entity.getLocation();
				// TODO: this is a workaround: for some yet unknown reason entities sometimes report to be in a
				// different world..
				if (!entityLoc.getWorld().equals(world)) {
					Log.debug("Found an entity which reports to be in a different world than the chunk we got it from:");
					Log.debug("Location=" + location + ", Chunk=" + chunk + ", ChunkWorld=" + chunk.getWorld()
							+ ", entityType=" + entity.getType() + ", entityLocation=" + entityLoc);
					continue; // skip this entity
				}

				if (entityLoc.distanceSquared(location) <= radius2) {
					if (types == null) {
						entities.add(entity);
					} else {
						EntityType type = entity.getType();
						for (EntityType t : types) {
							if (type.equals(t)) {
								entities.add(entity);
								break;
							}
						}
					}
				}
			}
		}
	}
	return entities;
}