Search in sources :

Example 1 with BlockStackSettings

use of dev.rosewood.rosestacker.stack.settings.BlockStackSettings in project RoseStacker by Rosewood-Development.

the class BlockListener method onBlockPlace.

@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
    StackManager stackManager = this.rosePlugin.getManager(StackManager.class);
    if (stackManager.isWorldDisabled(event.getPlayer().getWorld()))
        return;
    Player player = event.getPlayer();
    Block block = event.getBlock();
    if (block.getType() == Material.SPAWNER) {
        if (!stackManager.isSpawnerStackingEnabled() || !stackManager.isSpawnerTypeStackable(((CreatureSpawner) block.getState()).getSpawnedType()))
            return;
    } else {
        if (!stackManager.isBlockStackingEnabled() || !stackManager.isBlockTypeStackable(block))
            return;
    }
    Block against = event.getBlockAgainst();
    if (against.equals(block))
        against = against.getRelative(BlockFace.DOWN);
    // Get the block in the player's hand that's being placed
    ItemStack placedItem = player.getInventory().getItemInMainHand();
    boolean isOffHand = false;
    if (placedItem.getType() == Material.AIR || !placedItem.getType().isBlock()) {
        placedItem = player.getInventory().getItemInOffHand();
        isOffHand = true;
    }
    // Will be true if we are adding to an existing stack (including a stack of 1), or false if we are creating a new one from an itemstack with a stack value
    boolean isDistanceStack = false;
    boolean isAdditiveStack = against.getType() == block.getType();
    EntityType entityType = placedItem.getType() == Material.SPAWNER ? ItemUtils.getStackedItemEntityType(placedItem) : null;
    int stackAmount = ItemUtils.getStackedItemStackAmount(placedItem);
    // See if we can stack the spawner (if applicable) into one nearby
    int autoStackRange = Setting.SPAWNER_AUTO_STACK_RANGE.getInt();
    boolean autoStackChunk = Setting.SPAWNER_AUTO_STACK_CHUNK.getBoolean();
    boolean useAutoStack = autoStackRange > 0 || autoStackChunk;
    if (useAutoStack && block.getType() == Material.SPAWNER) {
        StackedSpawner nearest = null;
        boolean anyNearby = false;
        List<StackedSpawner> spawners = new ArrayList<>(stackManager.getStackingThread(block.getWorld()).getStackedSpawners().values());
        if (!autoStackChunk) {
            double closestDistance = autoStackRange * autoStackRange;
            for (StackedSpawner spawner : spawners) {
                double distance = spawner.getLocation().distanceSquared(block.getLocation());
                if (distance < closestDistance) {
                    boolean sameType = spawner.getSpawnerTile().getSpawnedType() == entityType;
                    anyNearby = Setting.SPAWNER_AUTO_STACK_PREVENT_MULTIPLE_IN_RANGE.getBoolean() || sameType;
                    if (sameType && spawner.getStackSize() + stackAmount <= spawner.getStackSettings().getMaxStackSize()) {
                        closestDistance = distance;
                        nearest = spawner;
                    }
                }
            }
        } else {
            Chunk chunk = block.getChunk();
            for (StackedSpawner spawner : spawners) {
                if (chunk == spawner.getBlock().getChunk()) {
                    boolean sameType = spawner.getSpawnerTile().getSpawnedType() == entityType;
                    anyNearby = Setting.SPAWNER_AUTO_STACK_PREVENT_MULTIPLE_IN_RANGE.getBoolean() || sameType;
                    if (sameType && spawner.getStackSize() + stackAmount <= spawner.getStackSettings().getMaxStackSize()) {
                        nearest = spawner;
                        break;
                    }
                }
            }
        }
        if (nearest != null) {
            against = nearest.getBlock();
            isAdditiveStack = true;
            isDistanceStack = true;
        } else if (anyNearby) {
            event.setCancelled(true);
            return;
        }
    }
    // Don't allow placing if they don't have permission
    if (entityType != null && Setting.SPAWNER_ADVANCED_PERMISSIONS.getBoolean() && !player.hasPermission("rosestacker.spawnerplace." + entityType.name().toLowerCase())) {
        this.rosePlugin.getManager(LocaleManager.class).sendMessage(player, "spawner-advanced-place-no-permission");
        event.setCancelled(true);
        return;
    }
    if (isAdditiveStack && against.getType() == Material.SPAWNER)
        isAdditiveStack = ((CreatureSpawner) against.getState()).getSpawnedType() == entityType;
    if (isAdditiveStack && (!player.isSneaking() || isDistanceStack)) {
        if (block.getType() == Material.SPAWNER) {
            if (!stackManager.isSpawnerTypeStackable(entityType))
                return;
            // Handle spawner stacking
            StackedSpawner stackedSpawner = stackManager.getStackedSpawner(against);
            if (stackedSpawner != null && stackedSpawner.getStackSize() + stackAmount > stackedSpawner.getStackSettings().getMaxStackSize()) {
                event.setCancelled(true);
                return;
            }
            if (stackedSpawner != null) {
                SpawnerStackEvent spawnerStackEvent = new SpawnerStackEvent(player, stackedSpawner, stackAmount, false);
                Bukkit.getPluginManager().callEvent(spawnerStackEvent);
                if (spawnerStackEvent.isCancelled()) {
                    event.setCancelled(true);
                    return;
                }
                stackAmount = spawnerStackEvent.getIncreaseAmount();
            } else {
                stackedSpawner = stackManager.createSpawnerStack(against, 1, false);
                SpawnerStackEvent spawnerStackEvent = new SpawnerStackEvent(player, stackedSpawner, stackAmount, true);
                Bukkit.getPluginManager().callEvent(spawnerStackEvent);
                if (spawnerStackEvent.isCancelled()) {
                    event.setCancelled(true);
                    return;
                }
                if (stackedSpawner.getStackSize() + stackAmount > stackedSpawner.getStackSettings().getMaxStackSize()) {
                    event.setCancelled(true);
                    return;
                }
            }
            stackedSpawner.increaseStackSize(stackAmount);
            // Fling particles from the attempted place location to the actual place location
            if (isDistanceStack && Setting.SPAWNER_AUTO_STACK_PARTICLES.getBoolean()) {
                for (int i = 0; i < 50; i++) {
                    Vector offset = Vector.getRandom();
                    Location startLoc = block.getLocation().clone().add(offset);
                    Vector start = startLoc.toVector();
                    Vector end = against.getLocation().toVector().add(offset).add(new Vector(0.0, 0.1, 0.0));
                    Vector angle = end.clone().subtract(start);
                    double length = angle.length() * 0.09;
                    angle.normalize();
                    player.spawnParticle(Particle.END_ROD, startLoc, 0, angle.getX(), angle.getY(), angle.getZ(), length);
                }
            }
        } else {
            if (!stackManager.isBlockTypeStackable(against))
                return;
            // Handle normal block stacking
            StackedBlock stackedBlock = stackManager.getStackedBlock(against);
            if (stackedBlock != null) {
                if (stackedBlock.isLocked()) {
                    event.setCancelled(true);
                    return;
                }
                if (stackedBlock.getStackSize() + stackAmount > stackedBlock.getStackSettings().getMaxStackSize()) {
                    event.setCancelled(true);
                    return;
                }
                BlockStackEvent blockStackEvent = new BlockStackEvent(player, stackedBlock, stackAmount, false);
                Bukkit.getPluginManager().callEvent(blockStackEvent);
                if (blockStackEvent.isCancelled()) {
                    event.setCancelled(true);
                    return;
                }
                stackAmount = blockStackEvent.getIncreaseAmount();
            } else {
                stackedBlock = stackManager.createBlockStack(against, 1);
                BlockStackEvent blockStackEvent = new BlockStackEvent(player, stackedBlock, stackAmount, false);
                Bukkit.getPluginManager().callEvent(blockStackEvent);
                if (blockStackEvent.isCancelled()) {
                    event.setCancelled(true);
                    return;
                }
                if (stackedBlock.getStackSize() + stackAmount > stackedBlock.getStackSettings().getMaxStackSize()) {
                    event.setCancelled(true);
                    return;
                }
            }
            stackedBlock.increaseStackSize(stackAmount);
        }
        event.setCancelled(true);
        BlockLoggingHook.recordBlockPlace(player, against);
    } else {
        // Handle singular items that have a stack multiplier
        // Set the spawner type
        StackSettingManager stackSettingManager = this.rosePlugin.getManager(StackSettingManager.class);
        if (placedItem.getType() == Material.SPAWNER) {
            EntityType spawnedType = ItemUtils.getStackedItemEntityType(placedItem);
            if (spawnedType == null)
                return;
            SpawnerStackSettings spawnerStackSettings = stackSettingManager.getSpawnerStackSettings(spawnedType);
            if (spawnerStackSettings == null)
                return;
            if (stackAmount <= 0)
                return;
            if (stackAmount > spawnerStackSettings.getMaxStackSize()) {
                event.setCancelled(true);
                return;
            }
            StackedSpawner tempStackedSpawner = new StackedSpawner(0, block, true);
            SpawnerStackEvent spawnerStackEvent = new SpawnerStackEvent(player, tempStackedSpawner, stackAmount, true);
            Bukkit.getPluginManager().callEvent(spawnerStackEvent);
            if (spawnerStackEvent.isCancelled()) {
                tempStackedSpawner.setStackSize(0);
                event.setCancelled(true);
                return;
            }
            stackAmount = spawnerStackEvent.getIncreaseAmount();
            StackedSpawner stackedSpawner = stackManager.createSpawnerStack(block, stackAmount, true);
            if (stackedSpawner != null) {
                stackedSpawner.getSpawnerTile().setSpawnedType(spawnedType);
                stackedSpawner.updateSpawnerProperties(true);
            }
        } else {
            if (stackAmount <= 1)
                return;
            BlockStackSettings blockStackSettings = stackSettingManager.getBlockStackSettings(block);
            if (blockStackSettings == null)
                return;
            if (stackAmount > blockStackSettings.getMaxStackSize()) {
                event.setCancelled(true);
                return;
            }
            StackedBlock tempStackedBlock = new StackedBlock(0, block);
            BlockStackEvent blockStackEvent = new BlockStackEvent(player, tempStackedBlock, stackAmount, true);
            Bukkit.getPluginManager().callEvent(blockStackEvent);
            if (blockStackEvent.isCancelled()) {
                tempStackedBlock.setStackSize(0);
                event.setCancelled(true);
                return;
            }
            stackManager.createBlockStack(block, stackAmount);
        }
    }
    // Take an item from the player's hand
    ItemUtils.takeOneItem(player, isOffHand ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND);
}
Also used : SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) Player(org.bukkit.entity.Player) StackedSpawner(dev.rosewood.rosestacker.stack.StackedSpawner) StackManager(dev.rosewood.rosestacker.manager.StackManager) ArrayList(java.util.ArrayList) StackSettingManager(dev.rosewood.rosestacker.manager.StackSettingManager) Chunk(org.bukkit.Chunk) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) EntityType(org.bukkit.entity.EntityType) StackedBlock(dev.rosewood.rosestacker.stack.StackedBlock) Block(org.bukkit.block.Block) StackedBlock(dev.rosewood.rosestacker.stack.StackedBlock) LocaleManager(dev.rosewood.rosestacker.manager.LocaleManager) SpawnerStackEvent(dev.rosewood.rosestacker.event.SpawnerStackEvent) ItemStack(org.bukkit.inventory.ItemStack) Vector(org.bukkit.util.Vector) BlockStackEvent(dev.rosewood.rosestacker.event.BlockStackEvent) Location(org.bukkit.Location) EventHandler(org.bukkit.event.EventHandler)

Example 2 with BlockStackSettings

use of dev.rosewood.rosestacker.stack.settings.BlockStackSettings in project RoseStacker by Rosewood-Development.

the class ItemUtils method getBlockAsStackedItemStack.

public static ItemStack getBlockAsStackedItemStack(Material material, int amount) {
    ItemStack itemStack = new ItemStack(material);
    if (amount == 1)
        return itemStack;
    ItemMeta itemMeta = itemStack.getItemMeta();
    if (itemMeta == null)
        return itemStack;
    BlockStackSettings stackSettings = RoseStacker.getInstance().getManager(StackSettingManager.class).getBlockStackSettings(material);
    StringPlaceholders placeholders = StringPlaceholders.builder("amount", amount).addPlaceholder("name", stackSettings.getDisplayName()).build();
    String displayString = RoseStacker.getInstance().getManager(LocaleManager.class).getLocaleMessage("block-stack-display", placeholders);
    itemMeta.setDisplayName(displayString);
    // Set the lore, if defined
    List<String> lore = RoseStacker.getInstance().getManager(LocaleManager.class).getLocaleMessages("stack-item-lore-block", placeholders);
    if (!lore.isEmpty())
        itemMeta.setLore(lore);
    itemStack.setItemMeta(itemMeta);
    // Set stack size
    NMSHandler nmsHandler = NMSAdapter.getHandler();
    itemStack = nmsHandler.setItemStackNBT(itemStack, "StackSize", amount);
    return itemStack;
}
Also used : StringPlaceholders(dev.rosewood.rosegarden.utils.StringPlaceholders) StackSettingManager(dev.rosewood.rosestacker.manager.StackSettingManager) LocaleManager(dev.rosewood.rosestacker.manager.LocaleManager) ItemStack(org.bukkit.inventory.ItemStack) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) NMSHandler(dev.rosewood.rosestacker.nms.NMSHandler) ItemMeta(org.bukkit.inventory.meta.ItemMeta)

Example 3 with BlockStackSettings

use of dev.rosewood.rosestacker.stack.settings.BlockStackSettings in project RoseStacker by Rosewood-Development.

the class StackedBlockGui method buildGui.

/**
 * Builds the GUI from scratch
 */
private void buildGui() {
    this.guiContainer = GuiFactory.createContainer();
    List<Integer> paginatedSlots = new ArrayList<>();
    for (int i = 10; i <= 16; i++) paginatedSlots.add(i);
    for (int i = 19; i <= 25; i++) paginatedSlots.add(i);
    for (int i = 28; i <= 34; i++) paginatedSlots.add(i);
    for (int i = 37; i <= 43; i++) paginatedSlots.add(i);
    List<Integer> borderSlots = new ArrayList<>();
    for (int i = 0; i <= 8; i++) borderSlots.add(i);
    for (int i = 9; i <= 36; i += 9) borderSlots.add(i);
    for (int i = 17; i <= 44; i += 9) borderSlots.add(i);
    for (int i = 46; i <= 52; i += 2) borderSlots.add(i);
    borderSlots.addAll(Arrays.asList(45, 53));
    ItemStack borderItem = new ItemStack(GuiHelper.parseMaterial(Setting.BLOCK_GUI_BORDER_MATERIAL.getString()));
    ItemMeta itemMeta = borderItem.getItemMeta();
    if (itemMeta != null) {
        itemMeta.setDisplayName(" ");
        itemMeta.addItemFlags(ItemFlag.values());
        borderItem.setItemMeta(itemMeta);
    }
    List<Integer> destroyBorderSlots = new ArrayList<>();
    for (int i = 0; i <= 26; i++) destroyBorderSlots.add(i);
    destroyBorderSlots.removeAll(Arrays.asList(12, 14));
    GuiScreenSection editableSection = GuiFactory.createScreenSection(paginatedSlots);
    LocaleManager localeManager = this.rosePlugin.getManager(LocaleManager.class);
    BlockStackSettings stackSettings = this.stackedBlock.getStackSettings();
    GuiStringHelper pageBackString = new GuiStringHelper(localeManager.getGuiLocaleMessage("gui-stacked-block-page-back", StringPlaceholders.empty()));
    GuiStringHelper destroyString = new GuiStringHelper(localeManager.getGuiLocaleMessage("gui-stacked-block-destroy", StringPlaceholders.empty()));
    GuiStringHelper pageForwardString = new GuiStringHelper(localeManager.getGuiLocaleMessage("gui-stacked-block-page-forward", StringPlaceholders.empty()));
    GuiStringHelper confirmDestroyString = new GuiStringHelper(localeManager.getGuiLocaleMessage("gui-stacked-block-destroy-confirm", StringPlaceholders.empty()));
    GuiStringHelper confirmCancelString = new GuiStringHelper(localeManager.getGuiLocaleMessage("gui-stacked-block-destroy-cancel", StringPlaceholders.empty()));
    List<ItemStack> stackItems = GuiUtil.getMaterialAmountAsItemStacks(this.stackedBlock.getBlock().getType(), this.stackedBlock.getStackSize());
    int pages = (int) Math.ceil((double) stackItems.size() / paginatedSlots.size()) + 1;
    while (stackItems.size() < pages * paginatedSlots.size()) stackItems.add(new ItemStack(Material.AIR));
    GuiScreen mainScreen = GuiFactory.createScreen(this.guiContainer, GuiSize.ROWS_SIX).setTitle(localeManager.getLocaleMessage("gui-stacked-block-title", StringPlaceholders.single("name", stackSettings.getDisplayName()))).setEditableSection(editableSection, stackItems, this::updateStackedBlock).setEditFilters(GuiFactory.createScreenEditFilters().setWhitelist(this.stackedBlock.getBlock().getType()).setAllowModified(false)).addButtonAt(47, GuiFactory.createButton().setIcon(Material.PAPER).setName(pageBackString.getName()).setLore(pageBackString.getLore()).setClickAction(event -> ClickAction.PAGE_BACKWARDS).setFlags(GuiButtonFlag.HIDE_IF_FIRST_PAGE).setHiddenReplacement(borderItem)).addButtonAt(49, GuiFactory.createButton().setIcon(Material.BARRIER).setName(destroyString.getName()).setLore(destroyString.getLore()).setClickAction(event -> ClickAction.TRANSITION_FORWARDS)).addButtonAt(51, GuiFactory.createButton().setIcon(Material.PAPER).setName(pageForwardString.getName()).setLore(pageForwardString.getLore()).setClickAction(event -> ClickAction.PAGE_FORWARDS).setFlags(GuiButtonFlag.HIDE_IF_LAST_PAGE).setHiddenReplacement(borderItem));
    for (int slot : borderSlots) mainScreen.addItemStackAt(slot, borderItem);
    GuiScreen confirmScreen = GuiFactory.createScreen(this.guiContainer, GuiSize.ROWS_THREE).setTitle(localeManager.getLocaleMessage("gui-stacked-block-destroy-title", StringPlaceholders.single("name", stackSettings.getDisplayName()))).addButtonAt(12, GuiFactory.createButton().setIcon(Material.EMERALD_BLOCK).setName(confirmDestroyString.getName()).setLore(confirmDestroyString.getLore()).setClickAction(event -> {
        this.destroyStackedBlock((Player) event.getWhoClicked());
        return ClickAction.NOTHING;
    })).addButtonAt(14, GuiFactory.createButton().setIcon(Material.REDSTONE_BLOCK).setName(confirmCancelString.getName()).setLore(confirmCancelString.getLore()).setClickAction(event -> ClickAction.TRANSITION_BACKWARDS));
    for (int slot : destroyBorderSlots) confirmScreen.addItemStackAt(slot, borderItem);
    this.guiContainer.addScreen(mainScreen);
    this.guiContainer.addScreen(confirmScreen);
    this.guiFramework.getGuiManager().registerGui(this.guiContainer);
}
Also used : ItemFlag(org.bukkit.inventory.ItemFlag) GuiFactory(dev.rosewood.guiframework.GuiFactory) Arrays(java.util.Arrays) GuiSize(dev.rosewood.guiframework.gui.GuiSize) ItemMeta(org.bukkit.inventory.meta.ItemMeta) RoseStacker(dev.rosewood.rosestacker.RoseStacker) Player(org.bukkit.entity.Player) ClickAction(dev.rosewood.guiframework.gui.ClickAction) ItemUtils(dev.rosewood.rosestacker.utils.ItemUtils) Inventory(org.bukkit.inventory.Inventory) ArrayList(java.util.ArrayList) GuiUtil(dev.rosewood.guiframework.framework.util.GuiUtil) StackedBlock(dev.rosewood.rosestacker.stack.StackedBlock) FrameworkView(dev.rosewood.guiframework.framework.gui.FrameworkView) LocaleManager(dev.rosewood.rosestacker.manager.LocaleManager) StringPlaceholders(dev.rosewood.rosegarden.utils.StringPlaceholders) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) GuiScreenSection(dev.rosewood.guiframework.gui.screen.GuiScreenSection) BlockUnstackEvent(dev.rosewood.rosestacker.event.BlockUnstackEvent) BlockStackEvent(dev.rosewood.rosestacker.event.BlockStackEvent) Setting(dev.rosewood.rosestacker.manager.ConfigurationManager.Setting) GuiButtonFlag(dev.rosewood.guiframework.gui.GuiButtonFlag) GuiScreen(dev.rosewood.guiframework.gui.screen.GuiScreen) Sound(org.bukkit.Sound) RosePlugin(dev.rosewood.rosegarden.RosePlugin) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) ItemStack(org.bukkit.inventory.ItemStack) StackManager(dev.rosewood.rosestacker.manager.StackManager) List(java.util.List) GuiStringHelper(dev.rosewood.rosestacker.gui.GuiHelper.GuiStringHelper) GuiFramework(dev.rosewood.guiframework.GuiFramework) GuiContainer(dev.rosewood.guiframework.gui.GuiContainer) Collections(java.util.Collections) GuiScreenSection(dev.rosewood.guiframework.gui.screen.GuiScreenSection) ArrayList(java.util.ArrayList) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) GuiStringHelper(dev.rosewood.rosestacker.gui.GuiHelper.GuiStringHelper) GuiScreen(dev.rosewood.guiframework.gui.screen.GuiScreen) LocaleManager(dev.rosewood.rosestacker.manager.LocaleManager) ItemStack(org.bukkit.inventory.ItemStack) ItemMeta(org.bukkit.inventory.meta.ItemMeta)

Example 4 with BlockStackSettings

use of dev.rosewood.rosestacker.stack.settings.BlockStackSettings in project RoseStacker by Rosewood-Development.

the class CommandManager method reload.

@Override
public void reload() {
    LocaleManager localeManager = this.rosePlugin.getManager(LocaleManager.class);
    ConversionManager conversionManager = this.rosePlugin.getManager(ConversionManager.class);
    StackSettingManager stackSettingManager = this.rosePlugin.getManager(StackSettingManager.class);
    // Load custom message strings
    Map<String, String> acfCoreMessages = localeManager.getAcfCoreMessages();
    Map<String, String> acfMinecraftMessages = localeManager.getAcfMinecraftMessages();
    for (Entry<String, String> entry : acfCoreMessages.entrySet()) this.commandManager.getLocales().addMessage(Locale.ENGLISH, MessageKey.of("acf-core." + entry.getKey()), HexUtils.colorify(localeManager.getLocaleMessage("prefix") + entry.getValue()));
    for (Entry<String, String> entry : acfMinecraftMessages.entrySet()) this.commandManager.getLocales().addMessage(Locale.ENGLISH, MessageKey.of("acf-minecraft." + entry.getKey()), HexUtils.colorify(localeManager.getLocaleMessage("prefix") + entry.getValue()));
    CommandCompletions<BukkitCommandCompletionContext> completions = this.commandManager.getCommandCompletions();
    completions.registerStaticCompletion("stackableBlockMaterial", () -> stackSettingManager.getStackableBlockTypes().stream().map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("spawnableSpawnerEntityType", () -> stackSettingManager.getStackableSpawnerTypes().stream().map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("spawnableEggEntityType", () -> stackSettingManager.getStackableEntityTypes().stream().filter(x -> {
        EntityStackSettings stackSettings = stackSettingManager.getEntityStackSettings(x);
        return stackSettings.getEntityTypeData().getSpawnEggMaterial() != null;
    }).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("blockStackAmounts", ctx -> {
        Material blockType = ctx.getContextValue(Material.class);
        if (blockType == null)
            return Collections.emptyList();
        BlockStackSettings blockStackSettings = stackSettingManager.getBlockStackSettings(blockType);
        int maxStackAmount = blockStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerAsyncCompletion("spawnerStackAmounts", ctx -> {
        EntityType entityType = ctx.getContextValue(EntityType.class);
        if (entityType == null)
            return Collections.emptySet();
        SpawnerStackSettings spawnerStackSettings = stackSettingManager.getSpawnerStackSettings(entityType);
        int maxStackAmount = spawnerStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerAsyncCompletion("entityStackAmounts", ctx -> {
        EntityType entityType = ctx.getContextValue(EntityType.class);
        if (entityType == null)
            return Collections.emptySet();
        EntityStackSettings entityStackSettings = stackSettingManager.getEntityStackSettings(entityType);
        int maxStackAmount = entityStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerStaticCompletion("giveAmounts", () -> IntStream.rangeClosed(1, 5).mapToObj(String::valueOf).collect(Collectors.toList()));
    completions.registerStaticCompletion("clearallType", () -> Stream.of(ClearallType.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("stackType", () -> Stream.of(StackType.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("conversionType", ctx -> conversionManager.getEnabledConverters().stream().map(Enum::name).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("conversionEnabledType", ctx -> conversionManager.getEnabledHandlers().stream().map(ConversionHandler::getRequiredDataStackType).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("translationLocales", ctx -> localeManager.getPossibleTranslationLocales());
    this.commandManager.getCommandConditions().addCondition(int.class, "limits", (c, exec, value) -> {
        if (value == null)
            return;
        if (c.hasConfig("min") && c.getConfigValue("min", 0) > value)
            throw new ConditionFailedException(MessageKeys.PLEASE_SPECIFY_AT_LEAST, "{min}", String.valueOf(c.getConfigValue("min", 0)));
        if (c.hasConfig("max") && c.getConfigValue("max", Integer.MAX_VALUE) < value)
            throw new ConditionFailedException(MessageKeys.PLEASE_SPECIFY_AT_MOST, "{max}", String.valueOf(c.getConfigValue("max", Integer.MAX_VALUE)));
    });
}
Also used : EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) ConversionHandler(dev.rosewood.rosestacker.conversion.handler.ConversionHandler) Material(org.bukkit.Material) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) EntityType(org.bukkit.entity.EntityType) ConditionFailedException(co.aikar.commands.ConditionFailedException) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext)

Example 5 with BlockStackSettings

use of dev.rosewood.rosestacker.stack.settings.BlockStackSettings in project RoseStacker by Rosewood-Development.

the class StackSettingManager method reload.

@Override
public void reload() {
    // Settings files
    File blockSettingsFile = this.getBlockSettingsFile();
    File entitySettingsFile = this.getEntitySettingsFile();
    File itemSettingsFile = this.getItemSettingsFile();
    File spawnerSettingsFile = this.getSpawnerSettingsFile();
    // Flags for if we should save the files
    AtomicBoolean saveBlockSettingsFile = new AtomicBoolean(false);
    AtomicBoolean saveEntitySettingsFile = new AtomicBoolean(false);
    AtomicBoolean saveItemSettingsFile = new AtomicBoolean(false);
    AtomicBoolean saveSpawnerSettingsFile = new AtomicBoolean(false);
    // Load block settings
    CommentedFileConfiguration blockSettingsConfiguration = CommentedFileConfiguration.loadConfiguration(blockSettingsFile);
    StackerUtils.getPossibleStackableBlockMaterials().forEach(x -> {
        BlockStackSettings blockStackSettings = new BlockStackSettings(blockSettingsConfiguration, x);
        this.blockSettings.put(x, blockStackSettings);
        if (blockStackSettings.hasChanges())
            saveBlockSettingsFile.set(true);
    });
    // Load entity settings and data from entity_data.json
    CommentedFileConfiguration entitySettingsConfiguration = CommentedFileConfiguration.loadConfiguration(entitySettingsFile);
    try (InputStream entityDataStream = this.getClass().getResourceAsStream("/entity_data.json");
        Reader entityDataReader = new InputStreamReader(entityDataStream)) {
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = jsonParser.parse(entityDataReader).getAsJsonObject();
        List<Class<EntityStackSettings>> classes = ClassUtils.getClassesOf(this.rosePlugin, PACKAGE_PATH, EntityStackSettings.class);
        List<String> ignoredLoading = new ArrayList<>();
        for (Class<EntityStackSettings> clazz : classes) {
            try {
                EntityStackSettings entityStackSetting = clazz.getConstructor(CommentedFileConfiguration.class, JsonObject.class).newInstance(entitySettingsConfiguration, jsonObject);
                this.entitySettings.put(entityStackSetting.getEntityType(), entityStackSetting);
                if (entityStackSetting.hasChanges())
                    saveEntitySettingsFile.set(true);
            } catch (Exception e) {
                // Log entity settings that failed to load
                // This should only be caused by version incompatibilities
                String className = clazz.getSimpleName();
                ignoredLoading.add(className.substring(0, className.length() - 13));
            }
        }
        if (!ignoredLoading.isEmpty())
            this.rosePlugin.getLogger().warning("Ignored loading stack settings for entities: " + ignoredLoading);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Load item settings
    CommentedFileConfiguration itemSettingsConfiguration = CommentedFileConfiguration.loadConfiguration(itemSettingsFile);
    Stream.of(Material.values()).sorted(Comparator.comparing(Enum::name)).forEach(x -> {
        ItemStackSettings itemStackSettings = new ItemStackSettings(itemSettingsConfiguration, x);
        this.itemSettings.put(x, itemStackSettings);
        if (itemStackSettings.hasChanges())
            saveItemSettingsFile.set(true);
    });
    // Load spawner settings
    boolean addSpawnerHeaderComments = !spawnerSettingsFile.exists();
    CommentedFileConfiguration spawnerSettingsConfiguration = CommentedFileConfiguration.loadConfiguration(spawnerSettingsFile);
    if (addSpawnerHeaderComments) {
        saveSpawnerSettingsFile.set(true);
        Map<String, String> conditionTags = ConditionTags.getTagDescriptionMap();
        spawnerSettingsConfiguration.addComments("Available Spawn Requirements:", "");
        for (Entry<String, String> entry : conditionTags.entrySet()) {
            String tag = entry.getKey();
            String description = entry.getValue();
            spawnerSettingsConfiguration.addComments(tag + " - " + description);
        }
        spawnerSettingsConfiguration.addComments("", "Valid Blocks: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html", "Valid Biomes: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/block/Biome.html", "", "Want to remove all requirements? Set the value to the following:", "spawn-requirements: []");
    }
    StackerUtils.getAlphabeticalStackableEntityTypes().forEach(x -> {
        SpawnerStackSettings spawnerStackSettings = new SpawnerStackSettings(spawnerSettingsConfiguration, x);
        this.spawnerSettings.put(x, spawnerStackSettings);
        if (spawnerStackSettings.hasChanges())
            saveSpawnerSettingsFile.set(true);
    });
    // Save files if changes were made
    if (saveBlockSettingsFile.get())
        blockSettingsConfiguration.save(true);
    if (saveEntitySettingsFile.get())
        entitySettingsConfiguration.save(true);
    if (saveItemSettingsFile.get())
        itemSettingsConfiguration.save(true);
    if (saveSpawnerSettingsFile.get())
        spawnerSettingsConfiguration.save(true);
    // Register dynamic permissions on first load
    if (!this.registeredPermissions) {
        PluginManager pluginManager = Bukkit.getPluginManager();
        List<Permission> silktouch = new ArrayList<>();
        List<Permission> nosilk = new ArrayList<>();
        List<Permission> spawnerplace = new ArrayList<>();
        for (EntityType entityType : this.entitySettings.keySet()) {
            String type = entityType.name().toLowerCase();
            silktouch.add(new Permission("rosestacker.silktouch." + type));
            nosilk.add(new Permission("rosestacker.nosilk." + type));
            spawnerplace.add(new Permission("rosestacker.spawnerplace." + type));
        }
        // Register silktouch permissions
        silktouch.forEach(pluginManager::addPermission);
        pluginManager.addPermission(new Permission("rosestacker.silktouch.*", silktouch.stream().collect(Collectors.toMap(Permission::getName, x -> true))));
        // Register nosilk permissions
        nosilk.forEach(pluginManager::addPermission);
        pluginManager.addPermission(new Permission("rosestacker.nosilk.*", nosilk.stream().collect(Collectors.toMap(Permission::getName, x -> true))));
        // Register spawnerplace permissions
        spawnerplace.forEach(pluginManager::addPermission);
        pluginManager.addPermission(new Permission("rosestacker.spawnerplace.*", spawnerplace.stream().collect(Collectors.toMap(Permission::getName, x -> true))));
        this.registeredPermissions = true;
    }
}
Also used : JsonObject(com.google.gson.JsonObject) Manager(dev.rosewood.rosegarden.manager.Manager) Item(org.bukkit.entity.Item) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClassUtils(dev.rosewood.rosegarden.utils.ClassUtils) HashMap(java.util.HashMap) JsonParser(com.google.gson.JsonParser) ItemUtils(dev.rosewood.rosestacker.utils.ItemUtils) ArrayList(java.util.ArrayList) EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) Block(org.bukkit.block.Block) Map(java.util.Map) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) ItemStackSettings(dev.rosewood.rosestacker.stack.settings.ItemStackSettings) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) CreatureSpawner(org.bukkit.block.CreatureSpawner) Set(java.util.Set) Reader(java.io.Reader) EntityType(org.bukkit.entity.EntityType) LivingEntity(org.bukkit.entity.LivingEntity) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) RosePlugin(dev.rosewood.rosegarden.RosePlugin) ConditionTags(dev.rosewood.rosestacker.spawner.conditions.ConditionTags) File(java.io.File) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) Permission(org.bukkit.permissions.Permission) List(java.util.List) Stream(java.util.stream.Stream) Entry(java.util.Map.Entry) StackerUtils(dev.rosewood.rosestacker.utils.StackerUtils) Comparator(java.util.Comparator) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) InputStream(java.io.InputStream) PluginManager(org.bukkit.plugin.PluginManager) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JsonObject(com.google.gson.JsonObject) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) ItemStackSettings(dev.rosewood.rosestacker.stack.settings.ItemStackSettings) PluginManager(org.bukkit.plugin.PluginManager) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) Permission(org.bukkit.permissions.Permission) JsonParser(com.google.gson.JsonParser) EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) EntityType(org.bukkit.entity.EntityType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) File(java.io.File)

Aggregations

BlockStackSettings (dev.rosewood.rosestacker.stack.settings.BlockStackSettings)5 LocaleManager (dev.rosewood.rosestacker.manager.LocaleManager)3 SpawnerStackSettings (dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings)3 ArrayList (java.util.ArrayList)3 Material (org.bukkit.Material)3 EntityType (org.bukkit.entity.EntityType)3 ItemStack (org.bukkit.inventory.ItemStack)3 RosePlugin (dev.rosewood.rosegarden.RosePlugin)2 StringPlaceholders (dev.rosewood.rosegarden.utils.StringPlaceholders)2 BlockStackEvent (dev.rosewood.rosestacker.event.BlockStackEvent)2 StackManager (dev.rosewood.rosestacker.manager.StackManager)2 StackSettingManager (dev.rosewood.rosestacker.manager.StackSettingManager)2 EntityStackSettings (dev.rosewood.rosestacker.stack.settings.EntityStackSettings)2 ItemUtils (dev.rosewood.rosestacker.utils.ItemUtils)2 List (java.util.List)2 Bukkit (org.bukkit.Bukkit)2 ItemMeta (org.bukkit.inventory.meta.ItemMeta)2 BukkitCommandCompletionContext (co.aikar.commands.BukkitCommandCompletionContext)1 ConditionFailedException (co.aikar.commands.ConditionFailedException)1 JsonObject (com.google.gson.JsonObject)1