Search in sources :

Example 11 with MapView

use of org.bukkit.map.MapView in project MagicPlugin by elBukkit.

the class AlterSpell method alterEntity.

protected SpellResult alterEntity(Entity entity) {
    EntityType entityType = entity.getType();
    switch(entityType) {
        case PAINTING:
            registerModified(entity);
            Painting painting = (Painting) entity;
            Art[] artValues = Art.values();
            Art oldArt = painting.getArt();
            Art newArt = oldArt;
            int ordinal = (oldArt.ordinal() + 1);
            for (int i = 0; i < artValues.length; i++) {
                newArt = artValues[ordinal++ % artValues.length];
                painting.setArt(newArt);
                newArt = painting.getArt();
                if (oldArt != newArt) {
                    break;
                }
            }
            if (oldArt == newArt) {
                return SpellResult.FAIL;
            }
            mage.sendDebugMessage("Altering art from " + oldArt + " to " + newArt);
            break;
        case ITEM_FRAME:
            ItemFrame itemFrame = (ItemFrame) entity;
            ItemStack frameItem = itemFrame.getItem();
            if (frameItem == null || frameItem.getType() != Material.MAP) {
                return SpellResult.NO_TARGET;
            }
            short data = frameItem.getDurability();
            data++;
            MapView mapView = DeprecatedUtils.getMap(data);
            if (mapView == null) {
                data = 0;
                mapView = DeprecatedUtils.getMap(data);
                if (mapView == null) {
                    return SpellResult.NO_TARGET;
                }
            }
            registerModified(entity);
            frameItem.setDurability(data);
            itemFrame.setItem(frameItem);
            break;
        case HORSE:
            registerModified(entity);
            Horse horse = (Horse) entity;
            Color color = horse.getColor();
            Color[] colorValues = Color.values();
            color = colorValues[(color.ordinal() + 1) % colorValues.length];
            Style horseStyle = horse.getStyle();
            Style[] styleValues = Style.values();
            horseStyle = styleValues[(horseStyle.ordinal() + 1) % styleValues.length];
            horse.setStyle(horseStyle);
            horse.setColor(color);
            break;
        case OCELOT:
            registerModified(entity);
            Ocelot ocelot = (Ocelot) entity;
            Type catType = ocelot.getCatType();
            Type[] typeValues = Type.values();
            catType = typeValues[(catType.ordinal() + 1) % typeValues.length];
            ocelot.setCatType(catType);
            break;
        case VILLAGER:
            registerModified(entity);
            Villager villager = (Villager) entity;
            Profession profession = villager.getProfession();
            Profession[] professionValues = Profession.values();
            profession = professionValues[(profession.ordinal() + 1) % professionValues.length];
            villager.setProfession(profession);
            break;
        case WOLF:
            registerModified(entity);
            Wolf wolf = (Wolf) entity;
            DyeColor wolfColor = wolf.getCollarColor();
            DyeColor[] wolfColorValues = DyeColor.values();
            wolfColor = wolfColorValues[(wolfColor.ordinal() + 1) % wolfColorValues.length];
            wolf.setCollarColor(wolfColor);
            break;
        case SHEEP:
            registerModified(entity);
            Sheep sheep = (Sheep) entity;
            DyeColor dyeColor = sheep.getColor();
            DyeColor[] dyeColorValues = DyeColor.values();
            dyeColor = dyeColorValues[(dyeColor.ordinal() + 1) % dyeColorValues.length];
            sheep.setColor(dyeColor);
            break;
        case SKELETON:
            registerModified(entity);
            Skeleton skeleton = (Skeleton) entity;
            SkeletonType skeletonType = skeleton.getSkeletonType();
            SkeletonType[] skeletonTypeValues = SkeletonType.values();
            skeletonType = skeletonTypeValues[(skeletonType.ordinal() + 1) % skeletonTypeValues.length];
            skeleton.setSkeletonType(skeletonType);
            break;
        default:
            return SpellResult.NO_TARGET;
    }
    ;
    registerForUndo();
    return SpellResult.CAST;
}
Also used : Art(org.bukkit.Art) ItemFrame(org.bukkit.entity.ItemFrame) SkeletonType(org.bukkit.entity.Skeleton.SkeletonType) Horse(org.bukkit.entity.Horse) Villager(org.bukkit.entity.Villager) MapView(org.bukkit.map.MapView) Style(org.bukkit.entity.Horse.Style) Skeleton(org.bukkit.entity.Skeleton) Wolf(org.bukkit.entity.Wolf) Color(org.bukkit.entity.Horse.Color) DyeColor(org.bukkit.DyeColor) DyeColor(org.bukkit.DyeColor) Painting(org.bukkit.entity.Painting) EntityType(org.bukkit.entity.EntityType) Ocelot(org.bukkit.entity.Ocelot) SkeletonType(org.bukkit.entity.Skeleton.SkeletonType) Type(org.bukkit.entity.Ocelot.Type) EntityType(org.bukkit.entity.EntityType) Profession(org.bukkit.entity.Villager.Profession) Sheep(org.bukkit.entity.Sheep) ItemStack(org.bukkit.inventory.ItemStack)

Example 12 with MapView

use of org.bukkit.map.MapView in project MagicPlugin by elBukkit.

the class URLMap method getMapView.

@Nullable
@SuppressWarnings("deprecation")
protected MapView getMapView() {
    if (!enabled) {
        return null;
    }
    MapView mapView = Bukkit.getMap(id);
    if (mapView == null) {
        enabled = false;
        controller.warning("Failed to get map id " + id + " for key " + getKey() + ", disabled, use 'mmap fix' to re-enable");
        return null;
    }
    List<MapRenderer> renderers = mapView.getRenderers();
    boolean needsRenderer = false;
    for (MapRenderer renderer : renderers) {
        if (!(renderer instanceof URLMap)) {
            mapView.removeRenderer(renderer);
            needsRenderer = true;
        }
    }
    if (needsRenderer) {
        mapView.addRenderer(this);
    }
    return mapView;
}
Also used : MapRenderer(org.bukkit.map.MapRenderer) MapView(org.bukkit.map.MapView) Nullable(javax.annotation.Nullable)

Example 13 with MapView

use of org.bukkit.map.MapView in project Denizen-For-Bukkit by DenizenScript.

the class PlayerTag method adjust.

@Override
public void adjust(Mechanism mechanism) {
    // -->
    if (mechanism.matches("noclip") && mechanism.hasValue()) {
        if (mechanism.getValue().asBoolean()) {
            DenizenPacketHandler.forceNoclip.add(getUUID());
        } else {
            DenizenPacketHandler.forceNoclip.remove(getUUID());
        }
    }
    // -->
    if (mechanism.matches("respawn")) {
        NMSHandler.getPacketHelper().respawn(getPlayerEntity());
    }
    // -->
    if (mechanism.matches("vision")) {
        if (mechanism.hasValue() && mechanism.requireEnum(EntityType.class)) {
            NMSHandler.getPacketHelper().setVision(getPlayerEntity(), EntityType.valueOf(mechanism.getValue().asString().toUpperCase()));
        } else {
            NMSHandler.getPacketHelper().forceSpectate(getPlayerEntity(), getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("level") && mechanism.requireInteger()) {
        setLevel(mechanism.getValue().asInt());
    }
    // -->
    if (mechanism.matches("item_slot") && mechanism.requireInteger()) {
        if (isOnline()) {
            getPlayerEntity().getInventory().setHeldItemSlot(mechanism.getValue().asInt() - 1);
        } else {
            getNBTEditor().setItemInHand(mechanism.getValue().asInt() - 1);
        }
    }
    // -->
    if (mechanism.matches("window_property")) {
        String[] split = mechanism.getValue().asString().split(",", 2);
        if (split.length != 2) {
            Debug.echoError("Invalid input! Must be in the form PROPERTY,VALUE");
        } else {
            try {
                getPlayerEntity().setWindowProperty(InventoryView.Property.valueOf(split[0].toUpperCase()), Integer.parseInt(split[1]));
            } catch (NumberFormatException e) {
                Debug.echoError("Input value must be a number!");
            } catch (IllegalArgumentException e) {
                Debug.echoError("Must specify a valid window property!");
            }
        }
    }
    // -->
    if (mechanism.matches("item_on_cursor") && mechanism.requireObject(ItemTag.class)) {
        getPlayerEntity().setItemOnCursor(mechanism.valueAsType(ItemTag.class).getItemStack());
    }
    // -->
    if (mechanism.matches("award_advancement")) {
        Advancement adv = AdvancementHelper.getAdvancement(mechanism.getValue().asString());
        if (adv == null) {
            if (mechanism.shouldDebug()) {
                Debug.echoError("Advancement '" + mechanism.getValue().asString() + "' does not exist.");
            }
            return;
        }
        AdvancementProgress prog = getPlayerEntity().getAdvancementProgress(adv);
        for (String criteria : prog.getRemainingCriteria()) {
            prog.awardCriteria(criteria);
        }
    }
    // -->
    if (mechanism.matches("revoke_advancement")) {
        Advancement adv = AdvancementHelper.getAdvancement(mechanism.getValue().asString());
        if (adv == null) {
            if (mechanism.shouldDebug()) {
                Debug.echoError("Advancement '" + mechanism.getValue().asString() + "' does not exist.");
            }
            return;
        }
        AdvancementProgress prog = getPlayerEntity().getAdvancementProgress(adv);
        for (String criteria : prog.getAwardedCriteria()) {
            prog.revokeCriteria(criteria);
        }
    }
    // -->
    if (mechanism.matches("fake_absorption_health") && mechanism.requireFloat()) {
        NMSHandler.getPacketHelper().setFakeAbsorption(getPlayerEntity(), mechanism.getValue().asFloat());
    }
    // -->
    if (mechanism.matches("health_scale") && mechanism.requireDouble()) {
        getPlayerEntity().setHealthScale(mechanism.getValue().asDouble());
    }
    // -->
    if (mechanism.matches("scale_health") && mechanism.requireBoolean()) {
        getPlayerEntity().setHealthScaled(mechanism.getValue().asBoolean());
    }
    // Allow offline editing of health values
    if (mechanism.matches("max_health") && mechanism.requireDouble()) {
        setMaxHealth(mechanism.getValue().asDouble());
    }
    if (mechanism.matches("health") && mechanism.requireDouble()) {
        setHealth(mechanism.getValue().asDouble());
    }
    // -->
    if (mechanism.matches("resource_pack") || mechanism.matches("texture_pack")) {
        Deprecations.playerResourcePackMech.warn(mechanism.context);
        String pack = mechanism.getValue().asString();
        int pipe = pack.indexOf('|');
        if (pipe > 0) {
            String hash = pack.substring(pipe + 1);
            pack = pack.substring(0, pipe);
            if (hash.length() != 40) {
                Debug.echoError("Invalid resource_pack hash. Should be 40 characters of hexadecimal data.");
                return;
            }
            byte[] hashData = new byte[20];
            for (int i = 0; i < 20; i++) {
                hashData[i] = (byte) Integer.parseInt(hash.substring(i * 2, i * 2 + 2), 16);
            }
            getPlayerEntity().setResourcePack(pack, hashData);
        } else {
            getPlayerEntity().setResourcePack(pack);
        }
    }
    // -->
    if (mechanism.matches("saturation") && mechanism.requireFloat()) {
        if (isOnline()) {
            getPlayerEntity().setSaturation(mechanism.getValue().asFloat());
        } else {
            getNBTEditor().setSaturation(mechanism.getValue().asFloat());
        }
    }
    // -->
    if (mechanism.matches("send_map") && mechanism.requireInteger()) {
        MapView map = Bukkit.getServer().getMap((short) mechanism.getValue().asInt());
        if (map != null) {
            getPlayerEntity().sendMap(map);
        } else {
            Debug.echoError("No map found for ID " + mechanism.getValue().asInt() + "!");
        }
    }
    // -->
    if (mechanism.matches("food_level") && mechanism.requireInteger()) {
        setFoodLevel(mechanism.getValue().asInt());
    }
    // -->
    if (mechanism.matches("bed_spawn_location") && mechanism.requireObject(LocationTag.class)) {
        setBedSpawnLocation(mechanism.valueAsType(LocationTag.class));
    }
    // -->
    if (mechanism.matches("spawn_forced") && mechanism.requireBoolean()) {
        if (isOnline()) {
            NMSHandler.getPlayerHelper().setSpawnForced(getPlayerEntity(), mechanism.getValue().asBoolean());
        } else {
            ImprovedOfflinePlayer editor = getNBTEditor();
            editor.setBedSpawnLocation(editor.getBedSpawnLocation(), mechanism.getValue().asBoolean());
        }
    }
    // -->
    if (mechanism.matches("can_fly") && mechanism.requireBoolean()) {
        if (isOnline()) {
            getPlayerEntity().setAllowFlight(mechanism.getValue().asBoolean());
        } else {
            getNBTEditor().setAllowFlight(mechanism.getValue().asBoolean());
        }
    }
    // -->
    if (mechanism.matches("fly_speed") && mechanism.requireFloat()) {
        setFlySpeed(mechanism.getValue().asFloat());
    }
    // -->
    if (mechanism.matches("flying") && mechanism.requireBoolean()) {
        getPlayerEntity().setFlying(mechanism.getValue().asBoolean());
    }
    // -->
    if (mechanism.matches("sprinting") && mechanism.requireBoolean()) {
        getPlayerEntity().setSprinting(mechanism.getValue().asBoolean());
    }
    // -->
    if (mechanism.matches("gamemode") && mechanism.requireEnum(GameMode.class)) {
        setGameMode(GameMode.valueOf(mechanism.getValue().asString().toUpperCase()));
    }
    if (mechanism.matches("kick")) {
        Deprecations.oldKickMech.warn(mechanism.context);
        getPlayerEntity().kickPlayer(mechanism.getValue().asString());
    }
    if (mechanism.matches("weather") && mechanism.requireEnum(WeatherType.class)) {
        Deprecations.oldWeatherMech.warn(mechanism.context);
        getPlayerEntity().setPlayerWeather(WeatherType.valueOf(mechanism.getValue().asString().toUpperCase()));
    }
    if (mechanism.matches("reset_weather")) {
        Deprecations.oldWeatherMech.warn(mechanism.context);
        getPlayerEntity().resetPlayerWeather();
    }
    // -->
    if (mechanism.matches("player_list_name")) {
        AdvancedTextImpl.instance.setPlayerListName(getPlayerEntity(), mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("display_name")) {
        getPlayerEntity().setDisplayName(mechanism.getValue().asString());
        return;
    }
    // -->
    if (mechanism.matches("show_workbench") && mechanism.requireObject(LocationTag.class)) {
        getPlayerEntity().openWorkbench(mechanism.valueAsType(LocationTag.class), true);
        return;
    }
    // -->
    if (mechanism.matches("location") && mechanism.requireObject(LocationTag.class)) {
        setLocation(mechanism.valueAsType(LocationTag.class));
    }
    if (mechanism.matches("time") && mechanism.requireInteger()) {
        Deprecations.oldTimeMech.warn(mechanism.context);
        getPlayerEntity().setPlayerTime(mechanism.getValue().asInt(), true);
    }
    if (mechanism.matches("freeze_time")) {
        Deprecations.oldTimeMech.warn(mechanism.context);
        if (mechanism.requireInteger("Invalid integer specified. Assuming current world time.")) {
            getPlayerEntity().setPlayerTime(mechanism.getValue().asInt(), false);
        } else {
            getPlayerEntity().setPlayerTime(getPlayerEntity().getWorld().getTime(), false);
        }
    }
    if (mechanism.matches("reset_time")) {
        Deprecations.oldTimeMech.warn(mechanism.context);
        getPlayerEntity().resetPlayerTime();
    }
    // -->
    if (mechanism.matches("walk_speed") && mechanism.requireFloat()) {
        if (isOnline()) {
            getPlayerEntity().setWalkSpeed(mechanism.getValue().asFloat());
        } else {
            getNBTEditor().setWalkSpeed(mechanism.getValue().asFloat());
        }
    }
    // -->
    if (mechanism.matches("exhaustion") && mechanism.requireFloat()) {
        if (isOnline()) {
            getPlayerEntity().setExhaustion(mechanism.getValue().asFloat());
        } else {
            getNBTEditor().setExhaustion(mechanism.getValue().asFloat());
        }
    }
    // -->
    if (mechanism.matches("show_entity") && mechanism.requireObject(EntityTag.class)) {
        HideEntitiesHelper.unhideEntity(getPlayerEntity(), mechanism.valueAsType(EntityTag.class).getBukkitEntity());
    }
    // -->
    if (mechanism.matches("hide_entity")) {
        if (!mechanism.getValue().asString().isEmpty()) {
            ListTag split = mechanism.valueAsType(ListTag.class);
            if (split.size() > 0 && new ElementTag(split.get(0)).matchesType(EntityTag.class)) {
                EntityTag entity = EntityTag.valueOf(split.get(0), mechanism.context);
                if (!entity.isSpawnedOrValidForTag()) {
                    Debug.echoError("Can't hide the unspawned entity '" + split.get(0) + "'!");
                } else {
                    HideEntitiesHelper.hideEntity(getPlayerEntity(), entity.getBukkitEntity());
                }
            } else {
                Debug.echoError("'" + split.get(0) + "' is not a valid entity!");
            }
        } else {
            Debug.echoError("Must specify an entity to hide!");
        }
    }
    // -->
    if (mechanism.matches("hide_entities") && mechanism.hasValue()) {
        HideEntitiesHelper.PlayerHideMap map = HideEntitiesHelper.getPlayerMapFor(getUUID());
        String hideMe = mechanism.getValue().asString();
        map.matchersHidden.add(hideMe);
        if (isOnline()) {
            for (Entity ent : getPlayerEntity().getWorld().getEntities()) {
                if (BukkitScriptEvent.tryEntity(new EntityTag(ent), hideMe) && map.shouldHide(ent)) {
                    NMSHandler.getEntityHelper().sendHidePacket(getPlayerEntity(), ent);
                }
            }
        }
    }
    // -->
    if (mechanism.matches("unhide_entities") && mechanism.hasValue()) {
        HideEntitiesHelper.PlayerHideMap map = HideEntitiesHelper.getPlayerMapFor(getUUID());
        String unhideMe = mechanism.getValue().asString();
        map.matchersHidden.remove(unhideMe);
        if (map.matchersHidden.isEmpty() && map.entitiesHidden.isEmpty() && map.overridinglyShow.isEmpty()) {
            HideEntitiesHelper.playerHides.remove(getUUID());
        }
        if (isOnline()) {
            for (Entity ent : getPlayerEntity().getWorld().getEntities()) {
                if (BukkitScriptEvent.tryEntity(new EntityTag(ent), unhideMe) && !map.shouldHide(ent)) {
                    NMSHandler.getEntityHelper().sendShowPacket(getPlayerEntity(), ent);
                }
            }
        }
    }
    if (mechanism.matches("show_boss_bar")) {
        Deprecations.oldBossBarMech.warn(mechanism.context);
        if (!mechanism.getValue().asString().isEmpty()) {
            String[] split = mechanism.getValue().asString().split("\\|", 2);
            if (split.length == 2 && new ElementTag(split[0]).isDouble()) {
                BossBarHelper.showSimpleBossBar(getPlayerEntity(), split[1], new ElementTag(split[0]).asDouble() * (1.0 / 200.0));
            } else {
                BossBarHelper.showSimpleBossBar(getPlayerEntity(), split[0], 1.0);
            }
        } else {
            BossBarHelper.removeSimpleBossBar(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("fake_experience")) {
        if (!mechanism.getValue().asString().isEmpty()) {
            String[] split = mechanism.getValue().asString().split("\\|", 2);
            if (split.length > 0 && new ElementTag(split[0]).isFloat()) {
                if (split.length > 1 && new ElementTag(split[1]).isInt()) {
                    NMSHandler.getPacketHelper().showExperience(getPlayerEntity(), new ElementTag(split[0]).asFloat(), new ElementTag(split[1]).asInt());
                } else {
                    NMSHandler.getPacketHelper().showExperience(getPlayerEntity(), new ElementTag(split[0]).asFloat(), getPlayerEntity().getLevel());
                }
            } else {
                Debug.echoError("'" + split[0] + "' is not a valid decimal number!");
            }
        } else {
            NMSHandler.getPacketHelper().resetExperience(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("fake_health")) {
        if (!mechanism.getValue().asString().isEmpty()) {
            String[] split = mechanism.getValue().asString().split("\\|", 3);
            if (split.length > 0 && new ElementTag(split[0]).isFloat()) {
                if (split.length > 1 && new ElementTag(split[1]).isInt()) {
                    if (split.length > 2 && new ElementTag(split[2]).isFloat()) {
                        NMSHandler.getPacketHelper().showHealth(getPlayerEntity(), new ElementTag(split[0]).asFloat(), new ElementTag(split[1]).asInt(), new ElementTag(split[2]).asFloat());
                    } else {
                        NMSHandler.getPacketHelper().showHealth(getPlayerEntity(), new ElementTag(split[0]).asFloat(), new ElementTag(split[1]).asInt(), getPlayerEntity().getSaturation());
                    }
                } else {
                    NMSHandler.getPacketHelper().showHealth(getPlayerEntity(), new ElementTag(split[0]).asFloat(), getPlayerEntity().getFoodLevel(), getPlayerEntity().getSaturation());
                }
            } else {
                Debug.echoError("'" + split[0] + "' is not a valid decimal number!");
            }
        } else {
            NMSHandler.getPacketHelper().resetHealth(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("fake_mount_health")) {
        if (!isOnline() || !getPlayerEntity().isInsideVehicle()) {
            mechanism.echoError("Cannot run fake_mount_health - player is offline or unmounted.");
            return;
        }
        Entity vehicle = getPlayerEntity().getVehicle();
        if (!(vehicle instanceof LivingEntity)) {
            mechanism.echoError("Cannot run fake_mount_health - vehicle is not a living entity.");
            return;
        }
        LivingEntity liveVehicle = (LivingEntity) vehicle;
        double current, maximum;
        if (mechanism.hasValue()) {
            ListTag input = mechanism.valueAsType(ListTag.class);
            if (input.size() != 2) {
                mechanism.echoError("Cannot run fake_mount_health - improper input.");
                return;
            }
            current = new ElementTag(input.get(0)).asDouble();
            maximum = new ElementTag(input.get(1)).asDouble();
        } else {
            current = liveVehicle.getHealth();
            maximum = liveVehicle.getMaxHealth();
        }
        NMSHandler.getPacketHelper().showMobHealth(getPlayerEntity(), liveVehicle, current, maximum);
    }
    // -->
    if (mechanism.matches("fake_entity_health") && mechanism.requireObject(MapTag.class)) {
        if (!isOnline()) {
            mechanism.echoError("Cannot run fake_entity_health - player is offline.");
            return;
        }
        MapTag map = mechanism.valueAsType(MapTag.class);
        ObjectTag entityObject = map.getObject("entity");
        ObjectTag healthObject = map.getObject("health");
        ObjectTag maxObject = map.getObject("max");
        if (entityObject == null || healthObject == null) {
            mechanism.echoError("Cannot run fake_entity_health - input map is missing keys.");
            return;
        }
        EntityTag entity = entityObject.asType(EntityTag.class, mechanism.context);
        double health = new ElementTag(healthObject.toString()).asDouble();
        if (entity == null || !entity.isLivingEntity()) {
            mechanism.echoError("Cannot run fake_entity_health - entity is invalid or not living.");
            return;
        }
        double max = maxObject == null ? entity.getLivingEntity().getMaxHealth() : maxObject.asElement().asDouble();
        NMSHandler.getPacketHelper().showMobHealth(getPlayerEntity(), entity.getLivingEntity(), health, max);
    }
    // -->
    if (mechanism.matches("fake_equipment")) {
        if (!mechanism.getValue().asString().isEmpty()) {
            String[] split = mechanism.getValue().asString().split("\\|", 3);
            if (split.length > 0 && new ElementTag(split[0]).matchesType(EntityTag.class)) {
                String slot = split.length > 1 ? split[1].toUpperCase() : null;
                if (split.length > 1 && (new ElementTag(slot).matchesEnum(EquipmentSlot.class) || slot.equals("MAIN_HAND") || slot.equals("BOOTS"))) {
                    if (split.length > 2 && new ElementTag(split[2]).matchesType(ItemTag.class)) {
                        if (slot.equals("MAIN_HAND")) {
                            slot = "HAND";
                        } else if (slot.equals("BOOTS")) {
                            slot = "FEET";
                        }
                        NMSHandler.getPacketHelper().showEquipment(getPlayerEntity(), new ElementTag(split[0]).asType(EntityTag.class, mechanism.context).getLivingEntity(), EquipmentSlot.valueOf(slot), new ElementTag(split[2]).asType(ItemTag.class, mechanism.context).getItemStack());
                    } else if (split.length > 2) {
                        Debug.echoError("'" + split[2] + "' is not a valid ItemTag!");
                    }
                } else if (split.length > 1) {
                    Debug.echoError("'" + split[1] + "' is not a valid slot; must be HAND, OFF_HAND, BOOTS, LEGS, CHEST, or HEAD!");
                } else {
                    NMSHandler.getPacketHelper().resetEquipment(getPlayerEntity(), new ElementTag(split[0]).asType(EntityTag.class, mechanism.context).getLivingEntity());
                }
            } else {
                Debug.echoError("'" + split[0] + "' is not a valid EntityTag!");
            }
        }
    }
    // -->
    if (mechanism.matches("fov_multiplier")) {
        if (mechanism.hasValue() && mechanism.requireFloat()) {
            NMSHandler.getPacketHelper().setFieldOfView(getPlayerEntity(), mechanism.getValue().asFloat());
        } else {
            NMSHandler.getPacketHelper().setFieldOfView(getPlayerEntity(), Float.NaN);
        }
    }
    if (mechanism.matches("item_message")) {
        Deprecations.itemMessage.warn(mechanism.context);
        ItemChangeMessage.sendMessage(getPlayerEntity(), mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("show_endcredits")) {
        NMSHandler.getPlayerHelper().showEndCredits(getPlayerEntity());
    }
    // -->
    if (mechanism.matches("show_demo")) {
        if (NMSHandler.getVersion().isAtLeast(NMSVersion.v1_18)) {
            getPlayerEntity().showDemoScreen();
        } else {
            NMSHandler.getPacketHelper().showDemoScreen(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("spectator_target")) {
        if (mechanism.hasValue()) {
            getPlayerEntity().setGameMode(GameMode.SPECTATOR);
            getPlayerEntity().setSpectatorTarget(mechanism.valueAsType(EntityTag.class).getBukkitEntity());
        } else if (getPlayerEntity().getGameMode() == GameMode.SPECTATOR) {
            getPlayerEntity().setSpectatorTarget(null);
        }
    }
    // -->
    if (mechanism.matches("spectate") && mechanism.requireObject(EntityTag.class)) {
        NMSHandler.getPacketHelper().forceSpectate(getPlayerEntity(), mechanism.valueAsType(EntityTag.class).getBukkitEntity());
    }
    // -->
    if (mechanism.matches("open_book")) {
        NMSHandler.getPacketHelper().openBook(getPlayerEntity(), EquipmentSlot.HAND);
    }
    // -->
    if (mechanism.matches("open_offhand_book")) {
        NMSHandler.getPacketHelper().openBook(getPlayerEntity(), EquipmentSlot.OFF_HAND);
    }
    // -->
    if (mechanism.matches("show_book") && mechanism.requireObject(ItemTag.class)) {
        ItemTag book = mechanism.valueAsType(ItemTag.class);
        if (!(book.getItemMeta() instanceof BookMeta)) {
            Debug.echoError("show_book mechanism must have a book as input.");
            return;
        }
        NMSHandler.getPacketHelper().showEquipment(getPlayerEntity(), getPlayerEntity(), EquipmentSlot.OFF_HAND, book.getItemStack());
        NMSHandler.getPacketHelper().openBook(getPlayerEntity(), EquipmentSlot.OFF_HAND);
        NMSHandler.getPacketHelper().showEquipment(getPlayerEntity(), getPlayerEntity(), EquipmentSlot.OFF_HAND, getPlayerEntity().getEquipment().getItemInOffHand());
    }
    // -->
    if (mechanism.matches("resend_recipes")) {
        NMSHandler.getPlayerHelper().resendRecipeDetails(getPlayerEntity());
        NMSHandler.getPlayerHelper().resendDiscoveredRecipes(getPlayerEntity());
    }
    // -->
    if (mechanism.matches("resend_discovered_recipes")) {
        NMSHandler.getPlayerHelper().resendDiscoveredRecipes(getPlayerEntity());
    }
    // -->
    if (mechanism.matches("quietly_discover_recipe")) {
        for (String keyText : mechanism.valueAsType(ListTag.class)) {
            NamespacedKey key = Utilities.parseNamespacedKey(keyText);
            NMSHandler.getPlayerHelper().quietlyAddRecipe(getPlayerEntity(), key);
        }
    }
    // -->
    if (mechanism.matches("discover_recipe")) {
        List<NamespacedKey> keys = new ArrayList<>();
        for (String key : mechanism.valueAsType(ListTag.class)) {
            keys.add(Utilities.parseNamespacedKey(key));
        }
        getPlayerEntity().discoverRecipes(keys);
    }
    // -->
    if (mechanism.matches("forget_recipe")) {
        List<NamespacedKey> keys = new ArrayList<>();
        for (String key : mechanism.valueAsType(ListTag.class)) {
            keys.add(Utilities.parseNamespacedKey(key));
        }
        getPlayerEntity().undiscoverRecipes(keys);
    }
    // -->
    if (mechanism.matches("edit_sign")) {
        if (!NMSHandler.getPacketHelper().showSignEditor(getPlayerEntity(), mechanism.hasValue() ? mechanism.valueAsType(LocationTag.class) : null)) {
            Debug.echoError("Can't edit non-sign materials!");
        }
    }
    // -->
    if (mechanism.matches("tab_list_info")) {
        if (!mechanism.getValue().asString().isEmpty()) {
            String[] split = mechanism.getValue().asString().split("\\|", 2);
            if (split.length > 0) {
                String header = split[0];
                String footer = "";
                if (split.length > 1) {
                    footer = split[1];
                }
                NMSHandler.getPacketHelper().showTabListHeaderFooter(getPlayerEntity(), header, footer);
            } else {
                Debug.echoError("Must specify a header and footer to show!");
            }
        } else {
            NMSHandler.getPacketHelper().resetTabListHeaderFooter(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("sign_update")) {
        if (!mechanism.getValue().asString().isEmpty()) {
            String[] split = mechanism.getValue().asString().split("\\|", 2);
            if (LocationTag.matches(split[0]) && split.length > 1) {
                ListTag lines = ListTag.valueOf(split[1], mechanism.context);
                LocationTag location = LocationTag.valueOf(split[0], mechanism.context);
                AdvancedTextImpl.instance.sendSignUpdate(getPlayerEntity(), location, lines.toArray(new String[4]));
            } else {
                Debug.echoError("Must specify a valid location and at least one sign line!");
            }
        } else {
            Debug.echoError("Must specify a valid location and at least one sign line!");
        }
    }
    // -->
    if (mechanism.matches("banner_update")) {
        if (mechanism.getValue().asString().length() > 0) {
            String[] split = mechanism.getValue().asString().split("\\|");
            List<org.bukkit.block.banner.Pattern> patterns = new ArrayList<>();
            if (LocationTag.matches(split[0]) && split.length > 1) {
                List<String> splitList;
                for (int i = 1; i < split.length; i++) {
                    String string = split[i];
                    if (i == 1 && !string.contains("/")) {
                        // Comapt with old input format that had base_color
                        continue;
                    }
                    try {
                        splitList = CoreUtilities.split(string, '/', 2);
                        patterns.add(new org.bukkit.block.banner.Pattern(DyeColor.valueOf(splitList.get(0).toUpperCase()), PatternType.valueOf(splitList.get(1).toUpperCase())));
                    } catch (Exception e) {
                        Debug.echoError("Could not apply pattern to banner: " + string);
                    }
                }
                LocationTag location = LocationTag.valueOf(split[0], mechanism.context);
                NMSHandler.getPacketHelper().showBannerUpdate(getPlayerEntity(), location, DyeColor.WHITE, patterns);
            } else {
                Debug.echoError("Must specify a valid location and pattern list!");
            }
        }
    }
    // -->
    if (mechanism.matches("stop_sound")) {
        SoundCategory category = null;
        String key = null;
        if (mechanism.hasValue()) {
            try {
                if (mechanism.getValue().matchesEnum(SoundCategory.class)) {
                    category = SoundCategory.valueOf(mechanism.getValue().asString().toUpperCase());
                } else {
                    key = mechanism.getValue().asString();
                }
            } catch (Exception e) {
            }
        } else {
            category = SoundCategory.MASTER;
        }
        NMSHandler.getPlayerHelper().stopSound(getPlayerEntity(), key, category);
    }
    if (mechanism.matches("action_bar")) {
        Deprecations.playerActionBarMech.warn(mechanism.context);
        getPlayerEntity().spigot().sendMessage(ChatMessageType.ACTION_BAR, FormattedTextHelper.parse(mechanism.getValue().asString(), ChatColor.WHITE));
    }
    // -->
    if (mechanism.matches("update_advancements")) {
        NMSHandler.getAdvancementHelper().update(getPlayerEntity());
    }
    // -->
    if (mechanism.matches("name")) {
        String name = mechanism.getValue().asString();
        if (name.length() > 16) {
            Debug.echoError("Must specify a name with no more than 16 characters.");
        } else {
            NMSHandler.getInstance().getProfileEditor().setPlayerName(getPlayerEntity(), mechanism.getValue().asString());
        }
    }
    // -->
    if (mechanism.matches("skin")) {
        String name = mechanism.getValue().asString();
        if (name.length() > 16) {
            Debug.echoError("Must specify a name with no more than 16 characters.");
        } else {
            NMSHandler.getInstance().getProfileEditor().setPlayerSkin(getPlayerEntity(), mechanism.getValue().asString());
        }
    }
    // -->
    if (mechanism.matches("skin_blob")) {
        NMSHandler.getInstance().getProfileEditor().setPlayerSkinBlob(getPlayerEntity(), mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("is_whitelisted") && mechanism.requireBoolean()) {
        getPlayerEntity().setWhitelisted(mechanism.getValue().asBoolean());
    }
    // -->
    if (mechanism.matches("is_op") && mechanism.requireBoolean()) {
        getOfflinePlayer().setOp(mechanism.getValue().asBoolean());
    }
    if (mechanism.matches("money") && mechanism.requireDouble() && Depends.economy != null) {
        Deprecations.oldMoneyMech.warn(mechanism.context);
        double bal = Depends.economy.getBalance(getOfflinePlayer());
        double goal = mechanism.getValue().asDouble();
        if (goal > bal) {
            Depends.economy.depositPlayer(getOfflinePlayer(), goal - bal);
        } else if (bal > goal) {
            Depends.economy.withdrawPlayer(getOfflinePlayer(), bal - goal);
        }
    }
    // -->
    if (mechanism.matches("chat_prefix")) {
        if (Depends.chat == null) {
            Debug.echoError("Chat_Prefix mechanism invalid: No linked Chat plugin.");
            return;
        }
        Depends.chat.setPlayerPrefix(getPlayerEntity(), mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("chat_suffix")) {
        if (Depends.chat == null) {
            Debug.echoError("Chat_Suffix mechanism invalid: No linked Chat plugin.");
            return;
        }
        Depends.chat.setPlayerSuffix(getPlayerEntity(), mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("selected_npc") && Depends.citizens != null && mechanism.requireObject(NPCTag.class)) {
        ((NPCSelector) CitizensAPI.getDefaultNPCSelector()).select(getPlayerEntity(), mechanism.valueAsType(NPCTag.class).getCitizen());
    }
    // -->
    if (mechanism.matches("hide_particles")) {
        if (!mechanism.hasValue()) {
            HideParticles.hidden.remove(getUUID());
        } else {
            NetworkInterceptHelper.enable();
            HashSet<Particle> particles = HideParticles.hidden.computeIfAbsent(getUUID(), k -> new HashSet<>());
            Particle particle = Particle.valueOf(mechanism.getValue().asString().toUpperCase());
            particles.add(particle);
        }
    }
    // -->
    if (mechanism.matches("send_to") && mechanism.hasValue()) {
        if (!isOnline()) {
            Debug.echoError("Cannot use send_to on offline player.");
            return;
        }
        Depends.bungeeSendPlayer(getPlayerEntity(), mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("send_server_brand") && mechanism.hasValue()) {
        if (!isOnline()) {
            Debug.echoError("Cannot use send_server_brand on offline player.");
            return;
        }
        NMSHandler.getPacketHelper().sendBrand(getPlayerEntity(), mechanism.getValue().asString());
    }
    CoreUtilities.autoPropertyMechanism(this, mechanism);
    // Pass along to EntityTag mechanism handler if not already handled.
    if (!mechanism.fulfilled()) {
        if (isOnline()) {
            new EntityTag(getPlayerEntity()).adjust(mechanism);
        } else {
            if (mechanism.matches("show_to_players")) {
                HideEntitiesHelper.removeHide(null, getUUID());
            }
            if (mechanism.matches("hide_from_players")) {
                HideEntitiesHelper.addHide(null, getUUID());
            }
        }
    }
}
Also used : FakeEntity(com.denizenscript.denizen.utilities.entity.FakeEntity) org.bukkit(org.bukkit) ImprovedOfflinePlayer(com.denizenscript.denizen.nms.abstracts.ImprovedOfflinePlayer) HideEntitiesHelper(com.denizenscript.denizen.utilities.entity.HideEntitiesHelper) MapView(org.bukkit.map.MapView) AdvancementProgress(org.bukkit.advancement.AdvancementProgress) NPCSelector(net.citizensnpcs.npc.NPCSelector) BookMeta(org.bukkit.inventory.meta.BookMeta) Advancement(org.bukkit.advancement.Advancement)

Example 14 with MapView

use of org.bukkit.map.MapView in project Denizen-For-Bukkit by DenizenScript.

the class DenizenMapManager method reloadMaps.

public static void reloadMaps() {
    Map<Integer, List<MapRenderer>> oldMapRenderers = new HashMap<>();
    for (Map.Entry<Integer, DenizenMapRenderer> entry : mapRenderers.entrySet()) {
        DenizenMapRenderer renderer = entry.getValue();
        oldMapRenderers.put(entry.getKey(), renderer.getOldRenderers());
        renderer.deactivate();
    }
    mapRenderers.clear();
    downloadedByUrl.clear();
    mapsConfig = YamlConfiguration.loadConfiguration(mapsFile);
    ConfigurationSection mapsSection = mapsConfig.getConfigurationSection("MAPS");
    if (mapsSection == null) {
        return;
    }
    for (String key : mapsSection.getKeys(false)) {
        int mapId = Integer.valueOf(key);
        // TODO: ??? (deprecated short method)
        MapView mapView = Bukkit.getServer().getMap((short) mapId);
        if (mapView == null) {
            Debug.echoError("Map #" + key + " does not exist. Has it been removed? Deleting from maps.yml...");
            mapsSection.set(key, null);
            continue;
        }
        ConfigurationSection objectsData = mapsSection.getConfigurationSection(key + ".objects");
        List<MapRenderer> oldRenderers;
        if (oldMapRenderers.containsKey(mapId)) {
            oldRenderers = oldMapRenderers.get(mapId);
        } else {
            oldRenderers = mapView.getRenderers();
            for (MapRenderer oldRenderer : oldRenderers) {
                mapView.removeRenderer(oldRenderer);
            }
        }
        boolean contextual = mapsSection.getBoolean(key + ".contextual", true);
        DenizenMapRenderer renderer = new DenizenMapRenderer(oldRenderers, mapsSection.getBoolean(key + ".auto update", false), contextual);
        renderer.displayOriginal = mapsSection.getBoolean(key + ".original", true);
        List<String> objects = new ArrayList<>(objectsData.getKeys(false));
        objects.sort(new NaturalOrderComparator());
        for (String objectKey : objects) {
            String type = objectsData.getString(objectKey + ".type").toUpperCase();
            String xTag = objectsData.getString(objectKey + ".x");
            String yTag = objectsData.getString(objectKey + ".y");
            String visibilityTag = objectsData.getString(objectKey + ".visibility");
            boolean debug = objectsData.getString(objectKey + ".debug", "false").equalsIgnoreCase("true");
            MapObject object = null;
            switch(type) {
                case "CURSOR":
                    object = new MapCursor(xTag, yTag, visibilityTag, debug, objectsData.getString(objectKey + ".direction"), objectsData.getString(objectKey + ".cursor"));
                    break;
                case "IMAGE":
                    String file = objectsData.getString(objectKey + ".image");
                    int width = objectsData.getInt(objectKey + ".width", 0);
                    int height = objectsData.getInt(objectKey + ".height", 0);
                    object = new MapImage(renderer, xTag, yTag, visibilityTag, debug, file, width, height);
                    break;
                case "TEXT":
                    object = new MapText(xTag, yTag, visibilityTag, debug, objectsData.getString(objectKey + ".text"), objectsData.getString(objectKey + ".color"));
                    break;
                case "DOT":
                    object = new MapDot(xTag, yTag, visibilityTag, debug, objectsData.getString(objectKey + ".radius"), objectsData.getString(objectKey + ".color"));
                    break;
            }
            if (object != null) {
                object.worldCoordinates = objectsData.getString(objectKey + ".world_coordinates", "false").equalsIgnoreCase("true");
                object.showPastEdge = objectsData.getString(objectKey + ".show_past_edge", "false").equalsIgnoreCase("true");
                renderer.addObject(object);
            }
        }
        mapView.addRenderer(renderer);
        mapRenderers.put(mapId, renderer);
    }
    for (Map.Entry<Integer, List<MapRenderer>> entry : oldMapRenderers.entrySet()) {
        int id = entry.getKey();
        if (!mapRenderers.containsKey(id)) {
            // TODO: ??? (deprecated short method)
            MapView mapView = Bukkit.getServer().getMap((short) id);
            if (mapView != null) {
                for (MapRenderer renderer : entry.getValue()) {
                    mapView.addRenderer(renderer);
                }
            }
        // If it's null, the server no longer has the map - don't do anything about it
        }
    }
    ConfigurationSection downloadedImages = mapsConfig.getConfigurationSection("DOWNLOADED");
    if (downloadedImages == null) {
        return;
    }
    for (String image : downloadedImages.getKeys(false)) {
        downloadedByUrl.put(CoreUtilities.toLowerCase(downloadedImages.getString(image)), image.replace("DOT", "."));
    }
}
Also used : NaturalOrderComparator(com.denizenscript.denizencore.utilities.NaturalOrderComparator) MapRenderer(org.bukkit.map.MapRenderer) MapView(org.bukkit.map.MapView) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Aggregations

MapView (org.bukkit.map.MapView)14 MapRenderer (org.bukkit.map.MapRenderer)6 Nullable (javax.annotation.Nullable)3 DyeColor (org.bukkit.DyeColor)3 ItemStack (org.bukkit.inventory.ItemStack)3 org.bukkit (org.bukkit)2 Art (org.bukkit.Art)2 World (org.bukkit.World)2 ConfigurationSection (org.bukkit.configuration.ConfigurationSection)2 EntityType (org.bukkit.entity.EntityType)2 Horse (org.bukkit.entity.Horse)2 ItemFrame (org.bukkit.entity.ItemFrame)2 Ocelot (org.bukkit.entity.Ocelot)2 Painting (org.bukkit.entity.Painting)2 Sheep (org.bukkit.entity.Sheep)2 Villager (org.bukkit.entity.Villager)2 Wolf (org.bukkit.entity.Wolf)2 ImprovedOfflinePlayer (com.denizenscript.denizen.nms.abstracts.ImprovedOfflinePlayer)1 LocationTag (com.denizenscript.denizen.objects.LocationTag)1 WorldTag (com.denizenscript.denizen.objects.WorldTag)1