Search in sources :

Example 96 with Location

use of org.spongepowered.api.world.Location in project SpongeCommon by SpongePowered.

the class EntitySpawnTest method onInitialization.

@Listener
public void onInitialization(final GameInitializationEvent event) {
    Sponge.getCommandManager().register(this, CommandSpec.builder().arguments(GenericArguments.allOf(GenericArguments.catalogedElement(Text.of("type"), EntityType.class))).executor((src, args) -> {
        if (!(src instanceof Player)) {
            throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
        }
        final List<EntityType> types = new ArrayList<>(args.getAll("type"));
        final int size = types.size();
        if (size == 0) {
            throw new CommandException(Text.of(TextColors.RED, "You must specify at least one entity type to spawn any."));
        }
        final Location location = ((Player) src).getLocation();
        if (size == 1) {
            boolean failed = false;
            final EntityType type = types.get(0);
            final Entity entity = location.createEntity(type);
            try {
                if (location.getExtent().spawnEntity(entity)) {
                    src.sendMessage(Text.of(TextColors.GOLD, "You have successfully spawned a ", TextColors.DARK_GREEN, entity.getTranslation()));
                } else {
                    failed = true;
                }
            } catch (Exception e) {
                failed = true;
            }
            if (failed) {
                throw new CommandException(Text.of(TextColors.RED, "You have failed to spawn a " + type.getId()));
            }
        } else {
            src.sendMessage(Text.of(TextColors.GOLD, "You have spawned the following entities:"));
            location.getExtent().spawnEntities(types.stream().map(location::createEntity).collect(Collectors.toList())).forEach(e -> src.sendMessage(Text.of(TextColors.DARK_GREEN, e.getTranslation())));
        }
        return CommandResult.success();
    }).build(), "spawnspongeentity");
}
Also used : EntityType(org.spongepowered.api.entity.EntityType) Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) ArrayList(java.util.ArrayList) CommandException(org.spongepowered.api.command.CommandException) CommandException(org.spongepowered.api.command.CommandException) Location(org.spongepowered.api.world.Location) Listener(org.spongepowered.api.event.Listener)

Example 97 with Location

use of org.spongepowered.api.world.Location in project SpongeCommon by SpongePowered.

the class PacketUtil method firePreEvents.

private static boolean firePreEvents(Packet<?> packetIn, EntityPlayerMP playerMP) {
    if (packetIn instanceof CPacketAnimation) {
        CPacketAnimation packet = (CPacketAnimation) packetIn;
        SpongeCommonEventFactory.lastAnimationPacketTick = SpongeImpl.getServer().getTickCounter();
        SpongeCommonEventFactory.lastAnimationPlayer = new WeakReference<>(playerMP);
        HandType handType = packet.getHand() == EnumHand.MAIN_HAND ? HandTypes.MAIN_HAND : HandTypes.OFF_HAND;
        final ItemStack heldItem = playerMP.getHeldItem(packet.getHand());
        Sponge.getCauseStackManager().addContext(EventContextKeys.USED_ITEM, ItemStackUtil.snapshotOf(heldItem));
        AnimateHandEvent event = SpongeEventFactory.createAnimateHandEvent(Sponge.getCauseStackManager().getCurrentCause(), handType, (Humanoid) playerMP);
        if (SpongeImpl.postEvent(event)) {
            return true;
        }
        return false;
    } else if (packetIn instanceof CPacketPlayerDigging) {
        SpongeCommonEventFactory.lastPrimaryPacketTick = SpongeImpl.getServer().getTickCounter();
        CPacketPlayerDigging packet = (CPacketPlayerDigging) packetIn;
        ItemStack stack = playerMP.getHeldItemMainhand();
        Sponge.getCauseStackManager().addContext(EventContextKeys.USED_ITEM, ItemStackUtil.snapshotOf(stack));
        switch(packet.getAction()) {
            case DROP_ITEM:
            case DROP_ALL_ITEMS:
                if (!stack.isEmpty() && !playerMP.isSpectator()) {
                    ((IMixinEntityPlayerMP) playerMP).setPacketItem(stack.copy());
                }
                return false;
            case START_DESTROY_BLOCK:
            case ABORT_DESTROY_BLOCK:
            case STOP_DESTROY_BLOCK:
                final BlockPos pos = packet.getPosition();
                final Vector3d interactionPoint = VecHelper.toVector3d(pos);
                final BlockSnapshot blockSnapshot = new Location<>((World) playerMP.world, interactionPoint).createSnapshot();
                final RayTraceResult result = SpongeImplHooks.rayTraceEyes(playerMP, SpongeImplHooks.getBlockReachDistance(playerMP));
                if (SpongeCommonEventFactory.callInteractItemEventPrimary(playerMP, stack, EnumHand.MAIN_HAND, result == null ? null : VecHelper.toVector3d(result.hitVec), blockSnapshot).isCancelled()) {
                    ((IMixinEntityPlayerMP) playerMP).sendBlockChange(pos, playerMP.world.getBlockState(pos));
                    return true;
                }
                double d0 = playerMP.posX - ((double) pos.getX() + 0.5D);
                double d1 = playerMP.posY - ((double) pos.getY() + 0.5D) + 1.5D;
                double d2 = playerMP.posZ - ((double) pos.getZ() + 0.5D);
                double d3 = d0 * d0 + d1 * d1 + d2 * d2;
                double dist = SpongeImplHooks.getBlockReachDistance(playerMP) + 1;
                dist *= dist;
                if (d3 > dist) {
                    return true;
                } else if (pos.getY() >= SpongeImpl.getServer().getBuildLimit()) {
                    return true;
                }
                if (packet.getAction() == CPacketPlayerDigging.Action.START_DESTROY_BLOCK) {
                    if (SpongeCommonEventFactory.callInteractBlockEventPrimary(playerMP, blockSnapshot, EnumHand.MAIN_HAND, packet.getFacing(), result == null ? null : VecHelper.toVector3d(result.hitVec)).isCancelled()) {
                        ((IMixinEntityPlayerMP) playerMP).sendBlockChange(pos, playerMP.world.getBlockState(pos));
                        return true;
                    }
                }
                return false;
            default:
                break;
        }
    } else if (packetIn instanceof CPacketPlayerTryUseItem) {
        CPacketPlayerTryUseItem packet = (CPacketPlayerTryUseItem) packetIn;
        SpongeCommonEventFactory.lastSecondaryPacketTick = SpongeImpl.getServer().getTickCounter();
        long packetDiff = System.currentTimeMillis() - lastTryBlockPacketTimeStamp;
        // If the time between packets is small enough, use the last result.
        if (packetDiff < 100) {
            // Use previous result and avoid firing a second event
            return lastTryBlockPacketItemResult;
        }
        final ItemStack heldItem = playerMP.getHeldItem(packet.getHand());
        Sponge.getCauseStackManager().addContext(EventContextKeys.USED_ITEM, ItemStackUtil.snapshotOf(heldItem));
        final RayTraceResult result = SpongeImplHooks.rayTraceEyes(playerMP, SpongeImplHooks.getBlockReachDistance(playerMP));
        final boolean isCancelled = SpongeCommonEventFactory.callInteractItemEventSecondary(playerMP, heldItem, packet.getHand(), result == null ? null : VecHelper.toVector3d(result.hitVec), BlockSnapshot.NONE).isCancelled();
        SpongeCommonEventFactory.callInteractBlockEventSecondary(playerMP, heldItem, result == null ? null : VecHelper.toVector3d(result.hitVec), BlockSnapshot.NONE, Direction.NONE, packet.getHand());
        if (isCancelled) {
            // Multiple slots may have been changed on the client. Right
            // clicking armor is one example - the client changes it
            // without the server telling it to.
            playerMP.sendAllContents(playerMP.openContainer, playerMP.openContainer.getInventory());
            return true;
        }
    } else if (packetIn instanceof CPacketPlayerTryUseItemOnBlock) {
        CPacketPlayerTryUseItemOnBlock packet = (CPacketPlayerTryUseItemOnBlock) packetIn;
        lastTryBlockPacketTimeStamp = System.currentTimeMillis();
        SpongeCommonEventFactory.lastSecondaryPacketTick = SpongeImpl.getServer().getTickCounter();
        Vector3d interactionPoint = VecHelper.toVector3d(packet.getPos());
        final RayTraceResult result = SpongeImplHooks.rayTraceEyes(playerMP, SpongeImplHooks.getBlockReachDistance(playerMP));
        BlockSnapshot blockSnapshot = new Location<>((World) playerMP.world, interactionPoint).createSnapshot();
        final ItemStack heldItem = playerMP.getHeldItem(packet.getHand());
        Sponge.getCauseStackManager().addContext(EventContextKeys.USED_ITEM, ItemStackUtil.snapshotOf(heldItem));
        boolean isCancelled = SpongeCommonEventFactory.callInteractItemEventSecondary(playerMP, heldItem, packet.getHand(), result == null ? null : VecHelper.toVector3d(result.hitVec), blockSnapshot).isCancelled();
        lastTryBlockPacketItemResult = isCancelled;
        if (isCancelled) {
            // update client
            BlockPos pos = packet.getPos();
            playerMP.connection.sendPacket(new SPacketBlockChange(playerMP.world, pos));
            playerMP.connection.sendPacket(new SPacketBlockChange(playerMP.world, pos.offset(packet.getDirection())));
            // See above
            playerMP.sendAllContents(playerMP.openContainer, playerMP.openContainer.getInventory());
            return true;
        }
    }
    return false;
}
Also used : CPacketPlayerDigging(net.minecraft.network.play.client.CPacketPlayerDigging) HandType(org.spongepowered.api.data.type.HandType) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) RayTraceResult(net.minecraft.util.math.RayTraceResult) AnimateHandEvent(org.spongepowered.api.event.entity.living.humanoid.AnimateHandEvent) CPacketAnimation(net.minecraft.network.play.client.CPacketAnimation) CPacketPlayerTryUseItemOnBlock(net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock) SPacketBlockChange(net.minecraft.network.play.server.SPacketBlockChange) CPacketPlayerTryUseItem(net.minecraft.network.play.client.CPacketPlayerTryUseItem) Vector3d(com.flowpowered.math.vector.Vector3d) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) Location(org.spongepowered.api.world.Location)

Example 98 with Location

use of org.spongepowered.api.world.Location in project HuskyCrates-Sponge by codeHusky.

the class HuskyCrates method updatePhysicalCrates.

public void updatePhysicalCrates() {
    if (updating)
        return;
    updating = true;
    try {
        CommentedConfigurationNode root = crateConfig.load();
        root.getNode("positions").setValue(null);
        for (Object ob : ((HashMap) crateUtilities.physicalCrates.clone()).keySet()) {
            Location<World> e = (Location<World>) ob;
            CommentedConfigurationNode node = root.getNode("positions").getAppendedNode();
            node.getNode("location").setValue(TypeToken.of(Location.class), e);
            //System.out.println("echo");
            try {
                node.getNode("crateID").setValue(crateUtilities.physicalCrates.get(e).vc.id);
            } catch (NullPointerException err) {
                System.out.println("removing a crate!");
                node.setValue(null);
                crateUtilities.physicalCrates.remove(ob);
                logger.warn("Invalid crate at (" + e.getPosition().getFloorX() + ", " + e.getPosition().getFloorY() + ", " + e.getPosition().getFloorZ() + ")!");
            }
        }
        crateConfig.save(root);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ObjectMappingException e) {
        e.printStackTrace();
    }
    crateUtilities.flag = false;
    updating = false;
}
Also used : CommentedConfigurationNode(ninja.leaping.configurate.commented.CommentedConfigurationNode) JSONObject(org.json.JSONObject) IOException(java.io.IOException) World(org.spongepowered.api.world.World) Location(org.spongepowered.api.world.Location) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException)

Example 99 with Location

use of org.spongepowered.api.world.Location in project HuskyCrates-Sponge by codeHusky.

the class HuskyCrates method postGameStart.

@Listener(order = Order.POST)
public void postGameStart(GameStartedServerEvent event) {
    Sponge.getScheduler().createTaskBuilder().async().execute(new Consumer<Task>() {

        @Override
        public void accept(Task task) {
            try {
                JSONObject obj = JsonReader.readJsonFromUrl("https://api.github.com/repos/codehusky/HuskyCrates-Sponge/releases");
                String[] thisVersion = pC.getVersion().get().split("\\.");
                String[] remoteVersion = obj.getJSONArray("releases").getJSONObject(0).getString("tag_name").replace("v", "").split("\\.");
                for (int i = 0; i < Math.min(remoteVersion.length, thisVersion.length); i++) {
                    if (!thisVersion[i].equals(remoteVersion[i])) {
                        if (Integer.parseInt(thisVersion[i]) > Integer.parseInt(remoteVersion[i])) {
                            //we're ahead
                            logger.warn("----------------------------------------------------");
                            logger.warn("Running unreleased version. (Developer build?)");
                            logger.warn("----------------------------------------------------");
                        } else {
                            //we're behind
                            logger.warn("----------------------------------------------------");
                            logger.warn("Your version of HuskyCrates is out of date!");
                            logger.warn("Your version: v" + pC.getVersion().get());
                            logger.warn("Latest version: " + obj.getJSONArray("releases").getJSONObject(0).getString("tag_name"));
                            logger.warn("Update here: https://goo.gl/hgtPMR");
                            logger.warn("----------------------------------------------------");
                        }
                        return;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).submit(this);
    Sponge.getScheduler().createTaskBuilder().execute(new Consumer<Task>() {

        @Override
        public void accept(Task task) {
            logger.info("Deleting existing armor stands...");
            for (World bit : Sponge.getServer().getWorlds()) {
                for (Entity ent : bit.getEntities()) {
                    if (ent instanceof ArmorStand) {
                        ArmorStand arm = (ArmorStand) ent;
                        if (arm.getCreator().isPresent()) {
                            if (arm.getCreator().get().equals(UUID.fromString(armorStandIdentifier))) {
                                arm.remove();
                            }
                        }
                    }
                }
            }
            logger.info("Initalizing config...");
            if (!crateUtilities.hasInitalizedVirtualCrates) {
                crateUtilities.generateVirtualCrates(crateConfig);
            }
            // doublecheck
            crateUtilities.hasInitalizedVirtualCrates = true;
            logger.info("Done initalizing config.");
            logger.info("Populating physical crates...");
            CommentedConfigurationNode root = null;
            try {
                root = crateConfig.load();
                double max = root.getNode("positions").getChildrenList().size();
                double count = 0;
                for (CommentedConfigurationNode node : root.getNode("positions").getChildrenList()) {
                    count++;
                    Location<World> ee;
                    try {
                        ee = node.getNode("location").getValue(TypeToken.of(Location.class));
                    } catch (InvalidDataException err2) {
                        logger.warn("Bug sponge developers about world UUIDs!");
                        ee = new Location<World>(Sponge.getServer().getWorld(node.getNode("location", "WorldName").getString()).get(), node.getNode("location", "X").getDouble(), node.getNode("location", "Y").getDouble(), node.getNode("location", "Z").getDouble());
                    }
                    if (!crateUtilities.physicalCrates.containsKey(ee))
                        crateUtilities.physicalCrates.put(ee, new PhysicalCrate(ee, node.getNode("crateID").getString(), HuskyCrates.instance));
                    logger.info("PROGRESS: " + Math.round((count / max) * 100) + "%");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ObjectMappingException e) {
                e.printStackTrace();
            }
            crateUtilities.startParticleEffects();
            logger.info("Done populating physical crates.");
            logger.info("Initalization complete.");
        }
    }).delayTicks(1).submit(this);
}
Also used : Entity(org.spongepowered.api.entity.Entity) Task(org.spongepowered.api.scheduler.Task) PhysicalCrate(pw.codehusky.huskycrates.crate.PhysicalCrate) IOException(java.io.IOException) World(org.spongepowered.api.world.World) Consumer(java.util.function.Consumer) JSONObject(org.json.JSONObject) ArmorStand(org.spongepowered.api.entity.living.ArmorStand) CommentedConfigurationNode(ninja.leaping.configurate.commented.CommentedConfigurationNode) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) Location(org.spongepowered.api.world.Location) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) Listener(org.spongepowered.api.event.Listener)

Example 100 with Location

use of org.spongepowered.api.world.Location in project RedProtect by FabioZumbi12.

the class RPBlockListener method onPistonEvent.

// TODO Test events
/*
    @Listener
    public void onListenEvent(TargetLivingEvent event) {    	
    	RedProtect.get().logger.severe("Event: "+ event.toString());
    }
    
    */
/*
	@Listener
	public void onVehicleBreak(DamageEntityEvent e){
		if (e.isCancelled()){
    		return;
    	}
		if (!(e.getAttacker() instanceof Player)){
			return;
		}
		Vehicle cart = e.getVehicle();
		Player p = (Player) e.getAttacker();
		Region r = RedProtect.get().rm.getTopRegion(cart.getLocation());
		if (r == null){
			return;
		}
		
		if (!r.canMinecart(p)){
			RPLang.sendMessage(p, "blocklistener.region.cantbreak");
			e.setCancelled(true);
			return;
		}
	}
	*/
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPistonEvent(ChangeBlockEvent.Pre e) {
    Location<World> piston = null;
    Location<World> block = null;
    boolean antih = RedProtect.get().cfgs.getBool("region-settings.anti-hopper");
    if (RedProtect.get().getPVHelper().checkCause(e.getCause(), "PISTON_EXTEND")) {
        if (RedProtect.get().cfgs.getBool("performance.disable-PistonEvent-handler")) {
            return;
        }
        List<Location<World>> locs = e.getLocations();
        for (Location<World> loc : locs) {
            if (piston == null) {
                piston = loc;
                continue;
            }
            block = loc;
        }
    }
    if (RedProtect.get().getPVHelper().checkCause(e.getCause(), "PISTON_RETRACT")) {
        if (RedProtect.get().cfgs.getBool("performance.disable-PistonEvent-handler")) {
            return;
        }
        List<Location<World>> locs = e.getLocations();
        for (Location<World> loc : locs) {
            if (piston == null) {
                piston = loc;
                continue;
            }
            block = loc;
        }
    }
    // process
    if (piston != null && block != null) {
        Region rPi = RedProtect.get().rm.getTopRegion(piston);
        Region rB = RedProtect.get().rm.getTopRegion(block);
        if (rPi == null && rB != null || (rPi != null && rB != null && rPi != rB && !rPi.sameLeaders(rB))) {
            e.setCancelled(true);
            return;
        }
        if (antih) {
            BlockSnapshot ib = block.add(0, 1, 0).createSnapshot();
            if (!cont.canWorldBreak(ib) || !cont.canWorldBreak(block.createSnapshot())) {
                e.setCancelled(true);
            }
        }
    }
}
Also used : BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) Region(br.net.fabiozumbi12.RedProtect.Sponge.Region) World(org.spongepowered.api.world.World) Location(org.spongepowered.api.world.Location) Listener(org.spongepowered.api.event.Listener)

Aggregations

Location (org.spongepowered.api.world.Location)166 World (org.spongepowered.api.world.World)96 Listener (org.spongepowered.api.event.Listener)44 Player (org.spongepowered.api.entity.living.player.Player)40 Vector3d (com.flowpowered.math.vector.Vector3d)38 BlockSnapshot (org.spongepowered.api.block.BlockSnapshot)32 Vector3i (com.flowpowered.math.vector.Vector3i)31 Optional (java.util.Optional)28 Entity (org.spongepowered.api.entity.Entity)27 BlockType (org.spongepowered.api.block.BlockType)24 BlockState (org.spongepowered.api.block.BlockState)23 ItemStack (org.spongepowered.api.item.inventory.ItemStack)23 Direction (org.spongepowered.api.util.Direction)21 ArrayList (java.util.ArrayList)20 Keys (org.spongepowered.api.data.key.Keys)20 List (java.util.List)19 Text (org.spongepowered.api.text.Text)19 BlockPos (net.minecraft.util.math.BlockPos)18 Sponge (org.spongepowered.api.Sponge)15 Map (java.util.Map)14