Compare commits

..

8 commits

Author SHA1 Message Date
26bba65a9d
remove legacy command 2026-06-30 23:47:16 +02:00
2bf913293b
rebase on news update 2026-06-30 23:35:00 +02:00
dbdce37c74
prepare for v2 2026-06-30 21:08:37 +02:00
f8622e9867
rebase on new update 2026-06-30 21:08:36 +02:00
9acf9a62d2
1.21 cleanup and fix
also random cleanup
2026-06-30 21:08:36 +02:00
4e8acef7c3
fix from rebase 2026-06-30 21:08:36 +02:00
297f41c347
progress on 1.21 transition 2026-06-30 21:08:36 +02:00
010b54e9ed
initial 1.21 transition 2026-06-30 21:08:32 +02:00
60 changed files with 443 additions and 1350 deletions

View file

@ -17,7 +17,7 @@ These plugins have compatibility handled by custom anvil. seek help on custom an
Also use ExcellentEnchant max enchant limit Also use ExcellentEnchant max enchant limit
- [EcoEnchant](https://www.spigotmc.org/resources/ecoenchants-%E2%AD%95-250-enchantments-%E2%9C%85-create-custom-enchants-%E2%9C%A8-essentials-cmi-support.79573/) by Auxilor: - [EcoEnchant](https://www.spigotmc.org/resources/ecoenchants-%E2%AD%95-250-enchantments-%E2%9C%85-create-custom-enchants-%E2%9C%A8-essentials-cmi-support.79573/) by Auxilor:
Need to use /ca reload or a server restart to add newly added enchantment. Need to use /anvilconfigreload or a server restart to add newly added enchantment.
Use EcoEnchant restriction system but new restriction can be added in custom anvil Use EcoEnchant restriction system but new restriction can be added in custom anvil
- [Enchantment²](https://www.spigotmc.org/resources/enchants-squared-the-enchantsplus-rewrite-custom-enchantments-that-act-like-vanilla-ones.86747/) by Athlaeos: - [Enchantment²](https://www.spigotmc.org/resources/enchants-squared-the-enchantsplus-rewrite-custom-enchantments-that-act-like-vanilla-ones.86747/) by Athlaeos:

View file

@ -39,8 +39,7 @@ ca.bypass.level: Allow player to bypass every level limit (no custom limit)
# Command permissions # Command permissions
ca.command.reload: Allow administrator to reload the plugin's configs ca.command.reload: Allow administrator to reload the plugin's configs
ca.command.diagnostic: Get debug information about the plugin and server ca.command.diagnostic: Allow adminastator to diagnistic some simple problem with the plugin
ca.command.enchantment: Allows to set enchantment to holden item
ca.config.edit: Allow administrator to edit the plugin's config in game ca.config.edit: Allow administrator to edit the plugin's config in game
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# What service of metric should custom anvil use # What service of metric should custom anvil use
@ -154,6 +154,7 @@ enchant_limits:
minecraft:knockback: 2 minecraft:knockback: 2
minecraft:fire_aspect: 2 minecraft:fire_aspect: 2
minecraft:looting: 3 minecraft:looting: 3
minecraft:sweeping: 3
minecraft:sweeping_edge: 3 minecraft:sweeping_edge: 3
minecraft:efficiency: 5 minecraft:efficiency: 5
minecraft:unbreaking: 3 minecraft:unbreaking: 3
@ -292,6 +293,9 @@ enchant_values:
minecraft:swift_sneak: minecraft:swift_sneak:
item: 8 item: 8
book: 4 book: 4
minecraft:sweeping:
item: 4
book: 2
minecraft:sweeping_edge: minecraft:sweeping_edge:
item: 4 item: 4
book: 2 book: 2
@ -485,5 +489,5 @@ debug_log_verbose: false
# Whether to show inside the console or require to run /ca debug get # Whether to show inside the console or require to run /ca debug get
display_debug_in_console: false display_debug_in_console: false
configVersion: 1.17.7 configVersion: 1.15.5
lowMinecraftVersion: 1.21.11 lowMinecraftVersion: 1.21.11

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# material conflicts # material conflicts
@ -270,6 +270,7 @@ restriction_soul_speed:
restriction_sweeping_edge: restriction_sweeping_edge:
enchantments: enchantments:
- minecraft:sweeping
- minecraft:sweeping_edge - minecraft:sweeping_edge
notAffectedGroups: notAffectedGroups:
- enchanted_book - enchanted_book

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Please note this config use spigot material names. # Please note this config use spigot material names.

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Unit repair configuration # Unit repair configuration
@ -104,7 +104,7 @@ leather:
phantom_membrane: phantom_membrane:
elytra: 0.25 elytra: 0.25
turtle_scute: scute:
turtle_helmet: 0.25 turtle_helmet: 0.25
oak_planks: oak_planks:

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# What service of metric should custom anvil use # What service of metric should custom anvil use
@ -152,6 +152,7 @@ enchant_limits:
minecraft:knockback: 2 minecraft:knockback: 2
minecraft:fire_aspect: 2 minecraft:fire_aspect: 2
minecraft:looting: 3 minecraft:looting: 3
minecraft:sweeping: 3
minecraft:sweeping_edge: 3 minecraft:sweeping_edge: 3
minecraft:efficiency: 5 minecraft:efficiency: 5
minecraft:unbreaking: 3 minecraft:unbreaking: 3
@ -289,6 +290,9 @@ enchant_values:
minecraft:swift_sneak: minecraft:swift_sneak:
item: 8 item: 8
book: 4 book: 4
minecraft:sweeping:
item: 4
book: 2
minecraft:sweeping_edge: minecraft:sweeping_edge:
item: 4 item: 4
book: 2 book: 2

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# material conflicts # material conflicts
@ -267,6 +267,7 @@ restriction_soul_speed:
restriction_sweeping_edge: restriction_sweeping_edge:
enchantments: enchantments:
- minecraft:sweeping
- minecraft:sweeping_edge - minecraft:sweeping_edge
notAffectedGroups: notAffectedGroups:
- enchanted_book - enchanted_book

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Please note this config use spigot material names. # Please note this config use spigot material names.

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Unit repair configuration # Unit repair configuration
@ -98,7 +98,7 @@ leather:
phantom_membrane: phantom_membrane:
elytra: 0.25 elytra: 0.25
turtle_scute: scute:
turtle_helmet: 0.25 turtle_helmet: 0.25
oak_planks: oak_planks:

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# What service of metric should custom anvil use # What service of metric should custom anvil use
@ -152,6 +152,7 @@ enchant_limits:
minecraft:knockback: 2 minecraft:knockback: 2
minecraft:fire_aspect: 2 minecraft:fire_aspect: 2
minecraft:looting: 3 minecraft:looting: 3
minecraft:sweeping: 3
minecraft:sweeping_edge: 3 minecraft:sweeping_edge: 3
minecraft:efficiency: 5 minecraft:efficiency: 5
minecraft:unbreaking: 3 minecraft:unbreaking: 3
@ -286,6 +287,9 @@ enchant_values:
minecraft:swift_sneak: minecraft:swift_sneak:
item: 8 item: 8
book: 4 book: 4
minecraft:sweeping:
item: 4
book: 2
minecraft:sweeping_edge: minecraft:sweeping_edge:
item: 4 item: 4
book: 2 book: 2

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# material conflicts # material conflicts
@ -157,10 +157,13 @@ restriction_soul_speed:
notAffectedGroups: [ enchanted_book, boots ] notAffectedGroups: [ enchanted_book, boots ]
restriction_sweeping_edge: restriction_sweeping_edge:
enchantments: [ minecraft:sweeping_edge ] enchantments: [ minecraft:sweeping, minecraft:sweeping_edge ]
notAffectedGroups: [ enchanted_book, swords ] notAffectedGroups: [ enchanted_book, swords ]
# Do not exist in 1.18, that mean useInFuture will be set to true
# useInFuture set to true also mean it will not warn if there is an issue
restriction_swift_sneak: restriction_swift_sneak:
useInFuture: true
enchantments: [ minecraft:swift_sneak ] enchantments: [ minecraft:swift_sneak ]
notAffectedGroups: [ enchanted_book, leggings ] notAffectedGroups: [ enchanted_book, leggings ]

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Please note this config use spigot material names. # Please note this config use spigot material names.

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Unit repair configuration # Unit repair configuration
@ -98,7 +98,7 @@ leather:
phantom_membrane: phantom_membrane:
elytra: 0.25 elytra: 0.25
turtle_scute: scute:
turtle_helmet: 0.25 turtle_helmet: 0.25
oak_planks: oak_planks:

View file

@ -3,16 +3,18 @@ package xyz.alexcrea.cuanvil.api;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import kotlin.Triple; import kotlin.Triple;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.dependency.DependencyManager; import xyz.alexcrea.cuanvil.dependency.DependencyManager;
import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui; import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui; import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui;
import java.util.*; import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** /**
* Custom Anvil api for unit repair. * Custom Anvil api for unit repair.
@ -20,8 +22,7 @@ import java.util.*;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class UnitRepairApi { public class UnitRepairApi {
private UnitRepairApi() { private UnitRepairApi(){}
}
private static Object saveChangeTask = null; private static Object saveChangeTask = null;
@ -34,20 +35,7 @@ public class UnitRepairApi {
* @param repairable The item to be repaired. * @param repairable The item to be repaired.
* @return true if successful. * @return true if successful.
*/ */
public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable) { public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable){
return addUnitRepair(unit, repairable, 0.25, false);
}
/**
* Write and add a custom anvil unit repair recipe.
* Will not write the recipe if it already exists or was deleted.
* Set the value to minecraft default value (0.25 = 25%)
*
* @param unit The unit material used to repair the bellow item.
* @param repairable The item to be repaired.
* @return true if successful.
*/
public static boolean addUnitRepair(@NotNull NamespacedKey unit, @NotNull NamespacedKey repairable) {
return addUnitRepair(unit, repairable, 0.25, false); return addUnitRepair(unit, repairable, 0.25, false);
} }
@ -60,7 +48,7 @@ public class UnitRepairApi {
* @param value The amount to be repaired by every unit. (1% = 0.01) * @param value The amount to be repaired by every unit. (1% = 0.01)
* @return true if successful. * @return true if successful.
*/ */
public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value) { public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value){
return addUnitRepair(unit, repairable, value, false); return addUnitRepair(unit, repairable, value, false);
} }
@ -74,26 +62,12 @@ public class UnitRepairApi {
* @param overrideDeleted If we should write even if the recipe was previously deleted. * @param overrideDeleted If we should write even if the recipe was previously deleted.
* @return true if successful. * @return true if successful.
*/ */
public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value, boolean overrideDeleted) { public static boolean addUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value, boolean overrideDeleted){
return addUnitRepair(unit.getKey(), repairable.getKey(), value, overrideDeleted);
}
/**
* Write and add a custom anvil unit repair recipe.
* Will not write the recipe if it already exists.
*
* @param unit The unit material used to repair the bellow item.
* @param repairable The item to be repaired.
* @param value The amount to be repaired by every unit. (1% = 0.01)
* @param overrideDeleted If we should write even if the recipe was previously deleted.
* @return true if successful.
*/
public static boolean addUnitRepair(@NotNull NamespacedKey unit, @NotNull NamespacedKey repairable, double value, boolean overrideDeleted) {
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
String path = unit.toString().toLowerCase() + "." + repairable.toString().toLowerCase(); String path = unit.name().toLowerCase() + "." + repairable.name().toLowerCase();
if (!overrideDeleted && ConfigHolder.UNIT_REPAIR_HOLDER.isDeleted(path)) return false; if(!overrideDeleted && ConfigHolder.UNIT_REPAIR_HOLDER.isDeleted(path)) return false;
if (config.contains(path)) return false; if(config.contains(path)) return false;
// Set unit repair // Set unit repair
return setUnitRepair(unit, repairable, value); return setUnitRepair(unit, repairable, value);
@ -108,24 +82,11 @@ public class UnitRepairApi {
* @param value The amount to be repaired by every unit. (1% = 0.01) * @param value The amount to be repaired by every unit. (1% = 0.01)
* @return true if successful. * @return true if successful.
*/ */
public static boolean setUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value) { public static boolean setUnitRepair(@NotNull Material unit, @NotNull Material repairable, double value){
return setUnitRepair(unit.getKey(), repairable.getKey(), value);
}
/**
* Write and add a custom anvil unit repair recipe.
* Do not check if it previously existed or exist.
*
* @param unit The unit material used to repair the bellow item.
* @param repairable The item to be repaired.
* @param value The amount to be repaired by every unit. (1% = 0.01)
* @return true if successful.
*/
public static boolean setUnitRepair(@NotNull NamespacedKey unit, @NotNull NamespacedKey repairable, double value) {
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
String repairableName = repairable.toString().toLowerCase(); String repairableName = repairable.name().toLowerCase();
String path = unit.toString().toLowerCase() + "." + repairableName; String path = unit.name().toLowerCase() + "." + repairableName;
// Add to config then prepare save // Add to config then prepare save
config.set(path, value); config.set(path, value);
@ -133,10 +94,10 @@ public class UnitRepairApi {
// Add to gui // Add to gui
UnitRepairConfigGui repairConfigGui = UnitRepairConfigGui.getCurrentInstance(); UnitRepairConfigGui repairConfigGui = UnitRepairConfigGui.getCurrentInstance();
if (repairConfigGui != null) { if(repairConfigGui != null) {
UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored(); UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored();
if (elementGui != null) elementGui.updateValueForGeneric(repairable, true); if(elementGui != null) elementGui.updateValueForGeneric(repairableName, true);
repairConfigGui.updateValueForGeneric(unit, true); repairConfigGui.updateValueForGeneric(unit, true);
} }
@ -150,56 +111,48 @@ public class UnitRepairApi {
* @param repairable The item used to be repaired. * @param repairable The item used to be repaired.
* @return true if successful. * @return true if successful.
*/ */
public static boolean removeUnitRepair(@NotNull Material unit, @NotNull Material repairable) { public static boolean removeUnitRepair(@NotNull Material unit, @NotNull Material repairable){
return removeUnitRepair(unit.getKey(), repairable.getKey());
}
/**
* Remove a custom anvil unit repair recipe.
*
* @param unit The unit material used to repair the bellow item.
* @param repairable The item used to be repaired.
* @return true if successful.
*/
public static boolean removeUnitRepair(@NotNull NamespacedKey unit, @NotNull NamespacedKey repairable) {
// Delete every possible variation and save to file // Delete every possible variation and save to file
String unitName = unit.name();
String repairableName = repairable.name();
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
config.set(unit.getKey() + "." + repairable.getKey(), null); config.set(unitName.toLowerCase() + "." + repairableName.toUpperCase(), null);
config.set(unit.getKey() + "." + repairable, null); config.set(unitName.toUpperCase() + "." + repairableName.toLowerCase(), null);
config.set(unit + "." + repairable.getKey(), null); config.set(unitName.toUpperCase() + "." + repairableName.toUpperCase(), null);
config.set(unit + "." + repairable, null); config.set(unitName.toLowerCase() + "." + repairableName.toLowerCase(), null);
// Test if it was the last value of this section // Test if it was the last value of this section
boolean lastValue = false; boolean lastValue = false;
if (config.isConfigurationSection(unit.toString())) { if(config.isConfigurationSection(unitName.toLowerCase())) {
ConfigurationSection section = config.getConfigurationSection(unit.toString()); ConfigurationSection section = config.getConfigurationSection(unitName.toLowerCase());
if (section != null && section.getKeys(false).isEmpty()) { if(section != null && section.getKeys(false).isEmpty()) {
lastValue = true; lastValue = true;
config.set(unit.toString(), null); config.set(unitName.toLowerCase(), null);
} }
} else if (config.isConfigurationSection(unit.getKey())) { } else if (config.isConfigurationSection(unitName.toUpperCase())) {
ConfigurationSection section = config.getConfigurationSection(unit.getKey()); ConfigurationSection section = config.getConfigurationSection(unitName.toUpperCase());
if (section != null && section.getKeys(false).isEmpty()) { if(section != null && section.getKeys(false).isEmpty()) {
lastValue = true; lastValue = true;
config.set(unit.getKey(), null); config.set(unitName.toUpperCase(), null);
} }
} else lastValue = true; } else lastValue = true;
ConfigHolder.UNIT_REPAIR_HOLDER.delete(unit.toString().toLowerCase() + "." + repairable.toString().toLowerCase()); // We only need to "delete" as the lower case to be counted as deleted
ConfigHolder.UNIT_REPAIR_HOLDER.delete(unitName.toLowerCase() + "." + repairableName.toLowerCase());
prepareSaveTask(); prepareSaveTask();
// Remove from gui // Remove from gui
UnitRepairConfigGui repairConfigGui = UnitRepairConfigGui.getCurrentInstance(); UnitRepairConfigGui repairConfigGui = UnitRepairConfigGui.getCurrentInstance();
if (repairConfigGui != null) { if(repairConfigGui != null) {
UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored(); UnitRepairElementListGui elementGui = repairConfigGui.getInstanceOrCreate(unit).getStored();
if (elementGui != null) elementGui.removeGeneric(repairable); if(elementGui != null) elementGui.removeGeneric(repairableName);
if (lastValue) { if(lastValue){
repairConfigGui.removeGeneric(unit); repairConfigGui.removeGeneric(unit);
} }
} }
@ -211,9 +164,9 @@ public class UnitRepairApi {
* Prepare a task to save custom unit repair recipe configuration. * Prepare a task to save custom unit repair recipe configuration.
*/ */
private static void prepareSaveTask() { private static void prepareSaveTask() {
if (saveChangeTask != null) return; if(saveChangeTask != null) return;
saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, () -> { saveChangeTask = DependencyManager.scheduler.scheduleGlobally(CustomAnvil.instance, ()->{
ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(true); ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(true);
saveChangeTask = null; saveChangeTask = null;
}); });
@ -221,7 +174,6 @@ public class UnitRepairApi {
/** /**
* Get every unit repair recipes. * Get every unit repair recipes.
*
* @return An immutable collection of unit repair recipes. * @return An immutable collection of unit repair recipes.
* <p> * <p>
* Each element of the provided triple represent a part of the recipe * Each element of the provided triple represent a part of the recipe
@ -230,32 +182,29 @@ public class UnitRepairApi {
* <li>Second object is the item to be repaired. * <li>Second object is the item to be repaired.
* <li>Last object is the amount to be repaired by every unit. (1% = 0.01) * <li>Last object is the amount to be repaired by every unit. (1% = 0.01)
* </ul> * </ul>
* @deprecated some may be missing. use {@link #getModernUnitRepairs()}
*
*/ */
@Deprecated
@NotNull @NotNull
public static List<Triple<Material, Material, Double>> getUnitRepairs() { public static List<Triple<Material, Material, Double>> getUnitRepairs(){
List<Triple<Material, Material, Double>> mutableList = new ArrayList<>(); List<Triple<Material, Material, Double>> mutableList = new ArrayList<>();
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
for (String unitKey : config.getKeys(false)) { for (String unitKey : config.getKeys(false)) {
// Test if config section exist // Test if config section exist
if (!config.isConfigurationSection(unitKey)) continue; if(!config.isConfigurationSection(unitKey)) continue;
// Test if unit is a material // Test if unit is a material
Material unit = Material.getMaterial(unitKey.toUpperCase()); Material unit = Material.getMaterial(unitKey.toUpperCase());
if (unit == null) continue; if(unit == null) continue;
// Iterate over reparable items // Iterate over reparable items
ConfigurationSection section = config.getConfigurationSection(unitKey); ConfigurationSection section = config.getConfigurationSection(unitKey);
for (String repairableKey : section.getKeys(false)) { for (String repairableKey : section.getKeys(false)) {
// Test if value section exist // Test if value section exist
if (!section.isDouble(repairableKey)) continue; if(!section.isDouble(repairableKey)) continue;
// Test if repairable is valid a material // Test if repairable is valid a material
Material repairable = Material.getMaterial(repairableKey.toUpperCase()); Material repairable = Material.getMaterial(repairableKey.toUpperCase());
if (repairable == null) continue; if(repairable == null) continue;
// Add the values // Add the values
mutableList.add(new Triple<>(unit, repairable, section.getDouble(repairableKey))); mutableList.add(new Triple<>(unit, repairable, section.getDouble(repairableKey)));
@ -266,53 +215,4 @@ public class UnitRepairApi {
return Collections.unmodifiableList(mutableList); return Collections.unmodifiableList(mutableList);
} }
/**
* Get every unit repair recipes.
*
* @return An immutable collection of unit repair recipes.
* <p>
* <li>First map contain a key the unit material used to repair the bellow item and value the second map
* <li>Second map contain as key the item to be repaired and as value the amount to be repaired by every unit. (1% = 0.01)
* </ul>
*/
@NotNull
public static Map<NamespacedKey, Map<NamespacedKey, Double>> getModernUnitRepairs() {
Map<NamespacedKey, Map<NamespacedKey, Double>> mutableList = new HashMap<>();
FileConfiguration config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
for (String unitKey : config.getKeys(false)) {
// Test if config section exist
if (!config.isConfigurationSection(unitKey)) continue;
// Test if unit is a material
NamespacedKey unit = NamespacedKey.fromString(unitKey.toLowerCase());
if (unit == null) continue;
Map<NamespacedKey, Double> map;
if (!mutableList.containsKey(unit)) {
map = new HashMap<>();
mutableList.put(unit, map);
} else {
map = mutableList.get(unit);
}
// Iterate over reparable items
ConfigurationSection section = config.getConfigurationSection(unitKey);
for (String repairableKey : section.getKeys(false)) {
// Test if value section exist
if (!section.isDouble(repairableKey)) continue;
// Test if repairable is valid a material
NamespacedKey repairable = NamespacedKey.fromString(repairableKey.toLowerCase());
if (repairable == null) continue;
// Add the values
map.put(repairable, section.getDouble(repairableKey));
}
}
return mutableList;
}
} }

View file

@ -9,7 +9,6 @@ import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.enchant.bulk.BulkCleanEnchantOperation; import xyz.alexcrea.cuanvil.enchant.bulk.BulkCleanEnchantOperation;
import xyz.alexcrea.cuanvil.enchant.bulk.BulkGetEnchantOperation; import xyz.alexcrea.cuanvil.enchant.bulk.BulkGetEnchantOperation;
import xyz.alexcrea.cuanvil.group.EnchantConflictGroup; import xyz.alexcrea.cuanvil.group.EnchantConflictGroup;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
@ -46,14 +45,6 @@ public interface CAEnchantment {
@NotNull @NotNull
String getName(); String getName();
/**
* Get the enchantment name prettified (upper spaced case)
* @return Prettier enchantment name
*/
default String getPrettyName() {
return CasedStringUtil.snakeToUpperSpacedCase(getName());
}
/** /**
* Get the default maximum level of this enchantment. * Get the default maximum level of this enchantment.
* @return The default maximum level of this enchantment. * @return The default maximum level of this enchantment.

View file

@ -2,7 +2,6 @@ package xyz.alexcrea.cuanvil.gui.config;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.ChestGui; import com.github.stefvanschie.inventoryframework.gui.type.ChestGui;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane; import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
@ -40,142 +39,116 @@ public class MainConfigGui extends ChestGui {
GuiGlobalItems.addBackgroundItem(pane); GuiGlobalItems.addBackgroundItem(pane);
// Basic config item // Basic config item
var basicConfigItem = basicConfigItem(new BasicConfigGui(packetManager)); ItemStack basicConfigItemstack = new ItemStack(Material.COMMAND_BLOCK);
ItemMeta basicConfigMeta = basicConfigItemstack.getItemMeta();
assert basicConfigMeta != null;
basicConfigMeta.setDisplayName("§aBasic Config Menu");
basicConfigMeta.setLore(Collections.singletonList("§7Click here to open basic config menu"));
basicConfigItemstack.setItemMeta(basicConfigMeta);
GuiItem basicConfigItem = GuiGlobalItems.goToGuiItem(basicConfigItemstack, new BasicConfigGui(packetManager));
pane.bindItem('1', basicConfigItem); pane.bindItem('1', basicConfigItem);
// enchant level limit item // enchant level limit item
var enchantLimitItem = enchantLimitItem(new EnchantLimitConfigGui()); ItemStack enchantLimitItemstack = new ItemStack(Material.ENCHANTED_BOOK);
ItemMeta enchantLimitMeta = enchantLimitItemstack.getItemMeta();
assert enchantLimitMeta != null;
enchantLimitMeta.setDisplayName("§aEnchantment Level Limit");
enchantLimitMeta.setLore(Collections.singletonList("§7Click here to open enchantment level limit menu"));
enchantLimitItemstack.setItemMeta(enchantLimitMeta);
GuiItem enchantLimitItem = GuiGlobalItems.goToGuiItem(enchantLimitItemstack, new EnchantLimitConfigGui());
pane.bindItem('2', enchantLimitItem); pane.bindItem('2', enchantLimitItem);
// enchant level limit item // enchant level limit item
var enchantMergeLimitItem = enchantMergeLimitItem(new EnchantMergeLimitConfigGui()); ItemStack enchantMergeLimitItemstack = new ItemStack(Material.ENCHANTED_BOOK);
ItemMeta enchantMergeLimitMeta = enchantMergeLimitItemstack.getItemMeta();
assert enchantMergeLimitMeta != null;
enchantMergeLimitMeta.setDisplayName("§aEnchantment Merge Limit");
enchantMergeLimitMeta.setLore(Collections.singletonList("§7Click here to open enchantment merge limit menu"));
enchantMergeLimitItemstack.setItemMeta(enchantMergeLimitMeta);
GuiItem enchantMergeLimitItem = GuiGlobalItems.goToGuiItem(enchantMergeLimitItemstack, new EnchantMergeLimitConfigGui());
pane.bindItem('3', enchantMergeLimitItem); pane.bindItem('3', enchantMergeLimitItem);
// enchant cost item // enchant cost item
var enchantCostItem = enchantCostItem(new EnchantCostConfigGui()); ItemStack enchantCostItemstack = new ItemStack(Material.EXPERIENCE_BOTTLE);
ItemMeta enchantCostMeta = enchantCostItemstack.getItemMeta();
assert enchantCostMeta != null;
enchantCostMeta.setDisplayName("§aEnchantment Cost");
enchantCostMeta.setLore(Collections.singletonList("§7Click here to open enchantment costs menu"));
enchantCostItemstack.setItemMeta(enchantCostMeta);
GuiItem enchantCostItem = GuiGlobalItems.goToGuiItem(enchantCostItemstack, new EnchantCostConfigGui());
pane.bindItem('4', enchantCostItem); pane.bindItem('4', enchantCostItem);
// Enchantment Conflicts item // Enchantment Conflicts item
var enchantConflictItem = enchantConflictItem(EnchantConflictGui.getInstance()); ItemStack enchantConflictItemstack = new ItemStack(Material.OAK_FENCE);
ItemMeta enchantConflictMeta = enchantConflictItemstack.getItemMeta();
assert enchantConflictMeta != null;
enchantConflictMeta.setDisplayName("§aEnchantment Conflict");
enchantConflictMeta.setLore(Collections.singletonList("§7Click here to open enchantment conflict menu"));
enchantConflictItemstack.setItemMeta(enchantConflictMeta);
GuiItem enchantConflictItem = GuiGlobalItems.goToGuiItem(enchantConflictItemstack, EnchantConflictGui.getInstance());
pane.bindItem('5', enchantConflictItem); pane.bindItem('5', enchantConflictItem);
// Group config items // Group config items
var groupConfigItem = groupConfigItem(GroupConfigGui.getInstance()); ItemStack groupItemstack = new ItemStack(Material.CHEST);
ItemMeta groupMeta = groupItemstack.getItemMeta();
assert groupMeta != null;
groupMeta.setDisplayName("§aItem Groups");
groupMeta.setLore(Collections.singletonList("§7Click here to open item group menu"));
groupItemstack.setItemMeta(groupMeta);
GuiItem groupConfigItem = GuiGlobalItems.goToGuiItem(groupItemstack, GroupConfigGui.getInstance());
pane.bindItem('6', groupConfigItem); pane.bindItem('6', groupConfigItem);
// Unit repair item // Unit repair item
var unitRepairItem = unitRepairItem(UnitRepairConfigGui.getInstance()); ItemStack unirRepairItemstack = new ItemStack(Material.DIAMOND);
ItemMeta unitRepairMeta = unirRepairItemstack.getItemMeta();
assert unitRepairMeta != null;
unitRepairMeta.setDisplayName("§aUnit Repair");
unitRepairMeta.setLore(Collections.singletonList("§7Click here to open anvil unit repair menu"));
unirRepairItemstack.setItemMeta(unitRepairMeta);
GuiItem unitRepairItem = GuiGlobalItems.goToGuiItem(unirRepairItemstack, UnitRepairConfigGui.getInstance());
pane.bindItem('7', unitRepairItem); pane.bindItem('7', unitRepairItem);
// Custom recipe item // Custom recipe item
var customRecipeItem = customRecipeItem(CustomRecipeConfigGui.getInstance()); ItemStack customRecipeItemstack = new ItemStack(Material.CRAFTING_TABLE);
ItemMeta customRecipeMeta = customRecipeItemstack.getItemMeta();
assert customRecipeMeta != null;
customRecipeMeta.setDisplayName("§aCustom recipes");
customRecipeMeta.setLore(Collections.singletonList("§7Click here to open anvil custom recipe menu"));
customRecipeItemstack.setItemMeta(customRecipeMeta);
GuiItem customRecipeItem = GuiGlobalItems.goToGuiItem(customRecipeItemstack, CustomRecipeConfigGui.getInstance());
pane.bindItem('8', customRecipeItem); pane.bindItem('8', customRecipeItem);
// quit item // quit item
pane.bindItem('Q', quitItem()); ItemStack quitItemstack = new ItemStack(Material.BARRIER);
} ItemMeta quitMeta = quitItemstack.getItemMeta();
assert quitMeta != null;
public static GuiItem basicConfigItem(Gui target) { quitMeta.setDisplayName("§cQuit");
var item = new ItemStack(Material.COMMAND_BLOCK); quitItemstack.setItemMeta(quitMeta);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aBasic Config Menu"); GuiItem quitItem = new GuiItem(quitItemstack, event -> {
meta.setLore(Collections.singletonList("§7Click here to open basic config menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem enchantLimitItem(Gui target) {
var item = new ItemStack(Material.ENCHANTED_BOOK);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aEnchantment Level Limit");
meta.setLore(Collections.singletonList("§7Click here to open enchantment level limit menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem enchantMergeLimitItem(Gui target) {
ItemStack item = new ItemStack(Material.ENCHANTED_BOOK);
ItemMeta meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aEnchantment Merge Limit");
meta.setLore(Collections.singletonList("§7Click here to open enchantment merge limit menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem enchantCostItem(Gui target) {
ItemStack item = new ItemStack(Material.EXPERIENCE_BOTTLE);
ItemMeta meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aEnchantment Cost");
meta.setLore(Collections.singletonList("§7Click here to open enchantment costs menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem enchantConflictItem(Gui target) {
var item = new ItemStack(Material.OAK_FENCE);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aEnchantment Conflict");
meta.setLore(Collections.singletonList("§7Click here to open enchantment conflict menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem groupConfigItem(Gui target) {
var item = new ItemStack(Material.CHEST);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aItem Groups");
meta.setLore(Collections.singletonList("§7Click here to open item group menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem unitRepairItem(Gui target) {
var item = new ItemStack(Material.DIAMOND);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aUnit Repair");
meta.setLore(Collections.singletonList("§7Click here to open anvil unit repair menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem customRecipeItem(Gui target) {
var item = new ItemStack(Material.CRAFTING_TABLE);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§aCustom recipes");
meta.setLore(Collections.singletonList("§7Click here to open anvil custom recipe menu"));
item.setItemMeta(meta);
return GuiGlobalItems.goToGuiItem(item, target);
}
public static GuiItem quitItem() {
var item = new ItemStack(Material.BARRIER);
var meta = item.getItemMeta();
assert meta != null;
meta.setDisplayName("§cQuit");
item.setItemMeta(meta);
return new GuiItem(item, event -> {
event.setCancelled(true); event.setCancelled(true);
event.getWhoClicked().closeInventory(); event.getWhoClicked().closeInventory();
}, CustomAnvil.instance); }, CustomAnvil.instance);
pane.bindItem('Q', quitItem);
} }
} }

View file

@ -1,11 +1,11 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern; import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry; import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.config.list.SettingGuiListConfigGui; import xyz.alexcrea.cuanvil.gui.config.list.SettingGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.settings.SettingGui; import xyz.alexcrea.cuanvil.gui.config.settings.SettingGui;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant; import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
@ -31,17 +31,13 @@ public abstract class AbstractEnchantConfigGui<T extends SettingGui.SettingGuiFa
super(title); super(title);
} }
protected AbstractEnchantConfigGui(String title, Gui parent) {
super(title, parent);
}
@Override @Override
public void updateGuiValues() { //TODO maybe optimise it. public void updateGuiValues() { //TODO maybe optimise it.
reloadValues(); reloadValues();
} }
@Override @Override
protected Collection<CAEnchantment> getEveryInstanceOfGeneric() { protected Collection<CAEnchantment> getEveryDisplayableInstanceOfGeneric() {
return CAEnchantmentRegistry.getInstance().getNameSortedEnchantments(); return CAEnchantmentRegistry.getInstance().getNameSortedEnchantments();
} }
@ -77,7 +73,7 @@ public abstract class AbstractEnchantConfigGui<T extends SettingGui.SettingGuiFa
this.pages.clear(); this.pages.clear();
this.pages.add(this.firstPage); this.pages.add(this.firstPage);
for (CAEnchantment enchantment : getDisplayableInstanceOfGeneric()) { for (CAEnchantment enchantment : getEveryDisplayableInstanceOfGeneric()) {
GuiItem item = this.guiItemMap.get(enchantment); GuiItem item = this.guiItemMap.get(enchantment);
if(item == null) { if(item == null) {

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -41,10 +40,6 @@ public class CustomRecipeConfigGui extends MappedGuiListConfigGui<AnvilCustomRec
init(); init();
} }
public CustomRecipeConfigGui(Gui parent) {
super("Custom Recipe Config", parent);
}
@Override @Override
protected ItemStack createItemForGeneric(AnvilCustomRecipe recipe) { protected ItemStack createItemForGeneric(AnvilCustomRecipe recipe) {
// Get base item to display // Get base item to display
@ -118,7 +113,7 @@ public class CustomRecipeConfigGui extends MappedGuiListConfigGui<AnvilCustomRec
@Override @Override
protected Collection<AnvilCustomRecipe> getEveryInstanceOfGeneric() { protected Collection<AnvilCustomRecipe> getEveryDisplayableInstanceOfGeneric() {
return ConfigHolder.CUSTOM_RECIPE_HOLDER.getRecipeManager().getRecipeList(); return ConfigHolder.CUSTOM_RECIPE_HOLDER.getRecipeManager().getRecipeList();
} }
} }

View file

@ -1,196 +0,0 @@
package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.ChestGui;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.api.EnchantmentApi;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.group.EnchantConflictGroup;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import java.util.HashMap;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class EnchantConfigGui extends ChestGui implements ValueUpdatableGui {
private final Set<CAEnchantment> enchantments;
private final PatternPane pane;
private EnchantLimitConfigGui enchantLimitConfigGui;
private EnchantMergeLimitConfigGui enchantMergeLimitConfigGui;
private EnchantCostConfigGui enchantCostConfigGui;
private EnchantConflictGui enchantConflictGui;
private GroupConfigGui groupConfigGui;
public EnchantConfigGui(@NotNull Set<CAEnchantment> enchantments) {
super(3,
"Configuring Enchantments",
CustomAnvil.instance);
this.enchantments = enchantments;
Pattern pattern = new Pattern(
"0000D0000",
"023405600",
"Q00000000"
);
pane = new PatternPane(0, 0, 9, 3, pattern);
addPane(pane);
GuiGlobalItems.addBackgroundItem(pane);
ItemStack displayItemstack = new ItemStack(Material.ENCHANTED_BOOK);
ItemMeta displayMeta = displayItemstack.getItemMeta();
assert displayMeta != null;
displayMeta.setDisplayName("§aConfiguring Enchantments:");
displayItemstack.setItemMeta(displayMeta);
// Set enchantments
HashMap<CAEnchantment, Integer> enchantmentMap = new HashMap<>();
for (CAEnchantment enchantment : enchantments) {
enchantmentMap.put(enchantment, 1);
}
EnchantmentApi.setEnchantments(displayItemstack, enchantmentMap);
pane.bindItem('D', new GuiItem(displayItemstack, GuiGlobalActions.stayInPlace, CustomAnvil.instance));
updateGuiValues();
// Enchantment Conflicts item
var enchantConflictItem = MainConfigGui.enchantConflictItem(getEnchantConflictGui());
pane.bindItem('5', enchantConflictItem);
// Group config items
var groupConfigItem = MainConfigGui.groupConfigItem(getGroupConfigGui());
pane.bindItem('6', groupConfigItem);
// quit item
pane.bindItem('Q', MainConfigGui.quitItem());
}
private GuiItem enchantLimitConfigGui() {
if (enchantLimitConfigGui == null) {
enchantLimitConfigGui = new EnchantLimitConfigGui(this);
enchantLimitConfigGui.setFilter(enchantments::contains);
enchantLimitConfigGui.init();
}
// Bypass
if(enchantments.size() == 1) {
var enchant = enchantments.iterator().next();
var factory = EnchantLimitConfigGui.createFactory(enchant, this);
return enchantLimitConfigGui.itemFromFactory(enchant, factory);
}
return MainConfigGui.enchantLimitItem(enchantLimitConfigGui);
}
private GuiItem enchantMergeLimitConfigGui() {
if (enchantMergeLimitConfigGui == null) {
enchantMergeLimitConfigGui = new EnchantMergeLimitConfigGui(this);
enchantMergeLimitConfigGui.setFilter(enchantments::contains);
enchantMergeLimitConfigGui.init();
}
// Bypass
if(enchantments.size() == 1) {
var enchant = enchantments.iterator().next();
var factory = EnchantMergeLimitConfigGui.createFactory(enchant, this);
return enchantMergeLimitConfigGui.itemFromFactory(enchant, factory);
}
return MainConfigGui.enchantMergeLimitItem(enchantMergeLimitConfigGui);
}
private GuiItem enchantCostConfigGui() {
if (enchantCostConfigGui == null) {
enchantCostConfigGui = new EnchantCostConfigGui(this);
enchantCostConfigGui.setFilter(enchantments::contains);
enchantCostConfigGui.init();
}
// Bypass
if(enchantments.size() == 1) {
var enchant = enchantments.iterator().next();
var factory = EnchantCostConfigGui.createFactory(enchant, this);
return enchantCostConfigGui.itemFromFactory(enchant, factory);
}
return MainConfigGui.enchantCostItem(enchantCostConfigGui);
}
@NotNull
@Contract(pure = true)
private Predicate<EnchantConflictGroup> getGroupFilter() {
return group -> group.getEnchants()
.stream()
.anyMatch(enchantments::contains);
}
private EnchantConflictGui getEnchantConflictGui() {
if (enchantConflictGui == null) {
enchantConflictGui = new EnchantConflictGui(this);
enchantConflictGui.setFilter(getGroupFilter());
enchantConflictGui.init();
}
return enchantConflictGui;
}
private GroupConfigGui getGroupConfigGui() {
if (groupConfigGui == null) {
groupConfigGui = new GroupConfigGui(this);
// Get all the conflict related to this enchantment
var groups = ConfigHolder.CONFLICT_HOLDER
.getConflictManager()
.getConflictList()
.stream()
.filter(getGroupFilter())
.map(EnchantConflictGroup::getCantConflictGroup)
.collect(Collectors.toSet());
groupConfigGui.setFilter(group ->
groups.stream().anyMatch(other -> other.isReferencing(group))
);
groupConfigGui.init();
}
return groupConfigGui;
}
@Override
public void updateGuiValues() {
// enchant level limit item
pane.bindItem('2', enchantLimitConfigGui());
// enchant level limit item
pane.bindItem('3', enchantMergeLimitConfigGui());
// enchant cost item
pane.bindItem('4', enchantCostConfigGui());
}
@Override
public Gui getConnectedGui() {
return this;
}
}

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -25,30 +24,26 @@ public class EnchantConflictGui extends MappedGuiListConfigGui<EnchantConflictGr
private static EnchantConflictGui INSTANCE; private static EnchantConflictGui INSTANCE;
@Nullable @Nullable
public static EnchantConflictGui getCurrentInstance() { public static EnchantConflictGui getCurrentInstance(){
return INSTANCE; return INSTANCE;
} }
@NotNull @NotNull
public static EnchantConflictGui getInstance() { public static EnchantConflictGui getInstance(){
if (INSTANCE == null) INSTANCE = new EnchantConflictGui(); if(INSTANCE == null) INSTANCE = new EnchantConflictGui();
return INSTANCE; return INSTANCE;
} }
// Need to init myself
public EnchantConflictGui(Gui parent) {
super("Conflict Config", parent);
}
private EnchantConflictGui() { private EnchantConflictGui() {
super("Conflict Config"); super( "Conflict Config");
init(); init();
} }
@Override @Override
protected EnchantConflictGroup createAndSaveNewEmptyGeneric(String name) { protected EnchantConflictGroup createAndSaveNewEmptyGeneric(String name){
// Create new empty conflict and display it to the admin // Create new empty conflict and display it to the admin
EnchantConflictGroup conflict = new EnchantConflictGroup( EnchantConflictGroup conflict = new EnchantConflictGroup(
name, name,
@ -102,7 +97,7 @@ public class EnchantConflictGui extends MappedGuiListConfigGui<EnchantConflictGr
} }
@Override @Override
protected Collection<EnchantConflictGroup> getEveryInstanceOfGeneric() { protected Collection<EnchantConflictGroup> getEveryDisplayableInstanceOfGeneric() {
return ConfigHolder.CONFLICT_HOLDER.getConflictManager().getConflictList(); return ConfigHolder.CONFLICT_HOLDER.getConflictManager().getConflictList();
} }

View file

@ -1,14 +1,14 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui; import xyz.alexcrea.cuanvil.enchant.EnchantmentProperties;
import xyz.alexcrea.cuanvil.enchant.EnchantmentRarity;
import xyz.alexcrea.cuanvil.gui.config.settings.EnchantCostSettingsGui; import xyz.alexcrea.cuanvil.gui.config.settings.EnchantCostSettingsGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems; import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
@ -18,13 +18,13 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static io.delilaheve.util.ConfigOptions.ENCHANT_VALUES_ROOT;
/** /**
* Global Config gui for enchantment cost settings. * Global Config gui for enchantment cost settings.
*/ */
public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSettingsGui.EnchantCostSettingFactory> { public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSettingsGui.EnchantCostSettingFactory> {
private static final String SECTION_NAME = "enchant_values";
private static EnchantCostConfigGui INSTANCE = null; private static EnchantCostConfigGui INSTANCE = null;
@Nullable @Nullable
@ -37,29 +37,18 @@ public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSe
*/ */
public EnchantCostConfigGui() { public EnchantCostConfigGui() {
super("§8Enchantment Level Cost"); super("§8Enchantment Level Cost");
if (INSTANCE == null) INSTANCE = this; if(INSTANCE == null) INSTANCE = this;
init(); init();
} }
/**
* Constructor of this Global gui for enchantment cost settings.
*/
public EnchantCostConfigGui(Gui parent) {
super("§8Enchantment Level Cost", parent);
}
@Override @Override
public EnchantCostSettingsGui.EnchantCostSettingFactory createFactory(CAEnchantment enchant) { public EnchantCostSettingsGui.EnchantCostSettingFactory createFactory(CAEnchantment enchant) {
return createFactory(enchant, this);
}
public static EnchantCostSettingsGui.EnchantCostSettingFactory createFactory(CAEnchantment enchant, ValueUpdatableGui parent) {
String key = enchant.getKey().toString().toLowerCase(Locale.ENGLISH); String key = enchant.getKey().toString().toLowerCase(Locale.ENGLISH);
String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_")); String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_"));
return new EnchantCostSettingsGui.EnchantCostSettingFactory(prettyKey + " Cost", parent, return new EnchantCostSettingsGui.EnchantCostSettingFactory(prettyKey + " Cost", this,
ENCHANT_VALUES_ROOT + '.' + key, ConfigHolder.DEFAULT_CONFIG, SECTION_NAME + '.' + key, ConfigHolder.DEFAULT_CONFIG,
Arrays.asList( Arrays.asList(
"§7How many level should " + prettyKey, "§7How many level should " + prettyKey,
"§7cost when applied by book or by another item." "§7cost when applied by book or by another item."
@ -85,7 +74,7 @@ public class EnchantCostConfigGui extends AbstractEnchantConfigGui<EnchantCostSe
lore.add("§7Book Cost: §e" + bookCost); lore.add("§7Book Cost: §e" + bookCost);
List<String> displayLore = factory.getDisplayLore(); List<String> displayLore = factory.getDisplayLore();
if (!displayLore.isEmpty()) { if(!displayLore.isEmpty()){
lore.add(""); lore.add("");
lore.addAll(displayLore); lore.addAll(displayLore);
} }

View file

@ -1,13 +1,11 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material; import org.bukkit.Material;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.config.settings.IntSettingsGui; import xyz.alexcrea.cuanvil.gui.config.settings.IntSettingsGui;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
@ -38,22 +36,14 @@ public class EnchantLimitConfigGui extends AbstractEnchantConfigGui<IntSettingsG
init(); init();
} }
public EnchantLimitConfigGui(Gui parent) {
super("§8Enchantment Level Limit", parent);
}
@Override @Override
public IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant) { public IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant) {
return createFactory(enchant, this);
}
public static IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant, ValueUpdatableGui parent) {
String key = enchant.getKey().toString().toLowerCase(Locale.ROOT); String key = enchant.getKey().toString().toLowerCase(Locale.ROOT);
String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_")); String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_"));
var defaultValue = enchant.defaultMaxLevel(); var defaultValue = enchant.defaultMaxLevel();
return new IntSettingsGui.IntSettingFactory(prettyKey + " Limit", parent, return new IntSettingsGui.IntSettingFactory(prettyKey + " Limit", this,
SECTION_NAME + '.' + key, ConfigHolder.DEFAULT_CONFIG, SECTION_NAME + '.' + key, ConfigHolder.DEFAULT_CONFIG,
Collections.singletonList( Collections.singletonList(
"§7Maximum applied level of " + prettyKey "§7Maximum applied level of " + prettyKey

View file

@ -1,13 +1,11 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.util.ConfigOptions; import io.delilaheve.util.ConfigOptions;
import org.bukkit.Material; import org.bukkit.Material;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.enchant.CAEnchantment; import xyz.alexcrea.cuanvil.enchant.CAEnchantment;
import xyz.alexcrea.cuanvil.gui.ValueUpdatableGui;
import xyz.alexcrea.cuanvil.gui.config.settings.IntSettingsGui; import xyz.alexcrea.cuanvil.gui.config.settings.IntSettingsGui;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
@ -35,24 +33,12 @@ public class EnchantMergeLimitConfigGui extends AbstractEnchantConfigGui<IntSett
init(); init();
} }
/**
* Constructor of this Global gui for enchantment level limit settings.
*/
public EnchantMergeLimitConfigGui(Gui parent) {
super("§8Enchantment Maximum Merge Level", parent);
}
@Override @Override
public IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant) { public IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant) {
return createFactory(enchant, this);
}
public static IntSettingsGui.IntSettingFactory createFactory(CAEnchantment enchant, ValueUpdatableGui parent) {
String key = enchant.getKey().toString().toLowerCase(Locale.ROOT); String key = enchant.getKey().toString().toLowerCase(Locale.ROOT);
String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_")); String prettyKey = CasedStringUtil.snakeToUpperSpacedCase(key.replace(":", "_"));
return new IntSettingsGui.IntSettingFactory(prettyKey + " Merge Limit", parent, return new IntSettingsGui.IntSettingFactory(prettyKey + " Merge Limit", this,
SECTION_NAME + '.' + key, ConfigHolder.DEFAULT_CONFIG, SECTION_NAME + '.' + key, ConfigHolder.DEFAULT_CONFIG,
Arrays.asList( Arrays.asList(
"§7Maximum merge level for for " + prettyKey, "§7Maximum merge level for for " + prettyKey,

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -44,10 +43,6 @@ public class GroupConfigGui extends MappedGuiListConfigGui<IncludeGroup, MappedG
init(); init();
} }
public GroupConfigGui(Gui parent) {
super("Group Config", parent);
}
@Override @Override
protected ItemStack createItemForGeneric(IncludeGroup group) { protected ItemStack createItemForGeneric(IncludeGroup group) {
ItemStack item = new ItemStack(group.getRepresentativeMaterial()); ItemStack item = new ItemStack(group.getRepresentativeMaterial());
@ -67,7 +62,7 @@ public class GroupConfigGui extends MappedGuiListConfigGui<IncludeGroup, MappedG
} }
@Override @Override
protected Collection<IncludeGroup> getEveryInstanceOfGeneric() { protected Collection<IncludeGroup> getEveryDisplayableInstanceOfGeneric() {
ArrayList<IncludeGroup> includeGroups = new ArrayList<>(); ArrayList<IncludeGroup> includeGroups = new ArrayList<>();
for (AbstractMaterialGroup group : ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager().getGroupMap().values()) { for (AbstractMaterialGroup group : ConfigHolder.ITEM_GROUP_HOLDER.getItemGroupsManager().getGroupMap().values()) {

View file

@ -1,132 +0,0 @@
package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.ChestGui;
import com.github.stefvanschie.inventoryframework.pane.PatternPane;
import com.github.stefvanschie.inventoryframework.pane.util.Pattern;
import io.delilaheve.CustomAnvil;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import xyz.alexcrea.cuanvil.util.MaterialUtil;
import xyz.alexcrea.cuanvil.util.UnitRepairUtil;
public class ItemConfigGui extends ChestGui {
private EnchantConflictGui enchantConflictGui;
private GroupConfigGui groupConfigGui;
private UnitRepairConfigGui unitRepairConfigGui;
private CustomRecipeConfigGui customRecipeConfigGui;
public ItemConfigGui(@NotNull Material display, @NotNull NamespacedKey material) {
super(3,
CasedStringUtil.snakeToUpperSpacedCase(
material.getKey().toLowerCase()
) + " Config",
CustomAnvil.instance);
Pattern pattern = new Pattern(
"0000D0000",
"056000780",
"Q00000000"
);
PatternPane pane = new PatternPane(0, 0, 9, 3, pattern);
addPane(pane);
GuiGlobalItems.addBackgroundItem(pane);
ItemStack displayItemstack = new ItemStack(display);
ItemMeta displayMeta = displayItemstack.getItemMeta();
assert displayMeta != null;
displayMeta.setDisplayName("§aConfiguring " + material);
displayItemstack.setItemMeta(displayMeta);
pane.bindItem('D', new GuiItem(displayItemstack, GuiGlobalActions.stayInPlace, CustomAnvil.instance));
// Enchantment Conflicts item
GuiItem enchantConflictItem = MainConfigGui.enchantConflictItem(getEnchantConflictGui(material));
pane.bindItem('5', enchantConflictItem);
// Group config items
GuiItem groupConfigItem = MainConfigGui.groupConfigItem(getGroupConfigGui(material));
pane.bindItem('6', groupConfigItem);
// Unit repair item
GuiItem unitRepairItem = MainConfigGui.unitRepairItem(getUnitRepairConfigGui(material));
pane.bindItem('7', unitRepairItem);
// Custom recipe item
GuiItem customRecipeItem = MainConfigGui.customRecipeItem(getCustomRecipeConfigGui(material));
pane.bindItem('8', customRecipeItem);
// quit item
pane.bindItem('Q', MainConfigGui.quitItem());
}
private EnchantConflictGui getEnchantConflictGui(@NotNull NamespacedKey material) {
if (enchantConflictGui == null) {
enchantConflictGui = new EnchantConflictGui(this);
enchantConflictGui.setFilter(group ->
group.getCantConflictGroup().contain(material)
);
enchantConflictGui.init();
}
return enchantConflictGui;
}
private GroupConfigGui getGroupConfigGui(@NotNull NamespacedKey material) {
if (groupConfigGui == null) {
groupConfigGui = new GroupConfigGui(this);
groupConfigGui.setFilter(group ->
group.contain(material)
);
groupConfigGui.init();
}
return groupConfigGui;
}
private UnitRepairConfigGui getUnitRepairConfigGui(@NotNull NamespacedKey material) {
if (unitRepairConfigGui == null) {
unitRepairConfigGui = new UnitRepairConfigGui(this);
unitRepairConfigGui.setFilter(otherMat ->
otherMat.equals(material) || UnitRepairUtil.INSTANCE.findRawRepairValue(
material, otherMat, ConfigHolder.UNIT_REPAIR_HOLDER.getConfig()) != null
);
unitRepairConfigGui.init();
}
return unitRepairConfigGui;
}
private CustomRecipeConfigGui getCustomRecipeConfigGui(@NotNull NamespacedKey material) {
if (customRecipeConfigGui == null) {
customRecipeConfigGui = new CustomRecipeConfigGui(this);
customRecipeConfigGui.setFilter(recipe -> {
if (isMaterial(recipe.getLeftItem(), material)) return true;
if (isMaterial(recipe.getRightItem(), material)) return true;
return isMaterial(recipe.getResultItem(), material);
}
);
customRecipeConfigGui.init();
}
return customRecipeConfigGui;
}
private boolean isMaterial(@Nullable ItemStack item, @NotNull NamespacedKey material) {
if (item == null) return false;
return material.equals(MaterialUtil.INSTANCE.getCustomType(item));
}
}

View file

@ -1,10 +1,9 @@
package xyz.alexcrea.cuanvil.gui.config.global; package xyz.alexcrea.cuanvil.gui.config.global;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -14,25 +13,24 @@ import xyz.alexcrea.cuanvil.gui.config.ask.SelectItemTypeGui;
import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui; import xyz.alexcrea.cuanvil.gui.config.list.MappedGuiListConfigGui;
import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui; import xyz.alexcrea.cuanvil.gui.config.list.UnitRepairElementListGui;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import xyz.alexcrea.cuanvil.util.MaterialUtil;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
public class UnitRepairConfigGui extends public class UnitRepairConfigGui extends
MappedGuiListConfigGui<NamespacedKey, MappedGuiListConfigGui.LazyElement<UnitRepairElementListGui>> { MappedGuiListConfigGui<Material, MappedGuiListConfigGui.LazyElement<UnitRepairElementListGui>> {
private static UnitRepairConfigGui INSTANCE; private static UnitRepairConfigGui INSTANCE;
@Nullable @Nullable
public static UnitRepairConfigGui getCurrentInstance() { public static UnitRepairConfigGui getCurrentInstance(){
return INSTANCE; return INSTANCE;
} }
@NotNull @NotNull
public static UnitRepairConfigGui getInstance() { public static UnitRepairConfigGui getInstance(){
if (INSTANCE == null) INSTANCE = new UnitRepairConfigGui(); if(INSTANCE == null) INSTANCE = new UnitRepairConfigGui();
return INSTANCE; return INSTANCE;
} }
@ -43,12 +41,8 @@ public class UnitRepairConfigGui extends
init(); init();
} }
public UnitRepairConfigGui(Gui parent) {
super("Unit Repair Config", parent);
}
@Override @Override
protected LazyElement<UnitRepairElementListGui> newInstanceOfGui(NamespacedKey material, GuiItem item) { protected LazyElement<UnitRepairElementListGui> newInstanceOfGui(Material material, GuiItem item) {
return new LazyElement<>(item, () -> { return new LazyElement<>(item, () -> {
UnitRepairElementListGui element = new UnitRepairElementListGui(material, this); UnitRepairElementListGui element = new UnitRepairElementListGui(material, this);
element.init(); element.init();
@ -57,34 +51,23 @@ public class UnitRepairConfigGui extends
} }
@Override @Override
protected ItemStack createItemForGeneric(@NotNull NamespacedKey material) { protected ItemStack createItemForGeneric(Material material) {
var unitConfig = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig(); ConfigurationSection materialSection = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(material.name().toLowerCase());
var section = unitConfig.getConfigurationSection(material.toString().toLowerCase()); String materialName = CasedStringUtil.snakeToUpperSpacedCase(material.name().toLowerCase());
var legacySection = unitConfig.getConfigurationSection(material.getKey().toLowerCase());
String materialName = CasedStringUtil.snakeToUpperSpacedCase(material.getKey().toLowerCase()); if(material.isAir()){
material = Material.BARRIER;
var display = MaterialUtil.INSTANCE.getMatFromKey(material);
if (display == null || display.isAir()) {
display = Material.BARRIER;
} }
var reparable = new HashSet<String>(); int reparableItemCount = materialSection == null ? 0 : materialSection.getKeys(false).size(); // Probably an expensive call but... why not
if (section != null)
reparable.addAll(section.getKeys(false));
if (legacySection != null)
reparable.addAll(legacySection.getKeys(false));
var reparableItemCount = reparable.size(); ItemStack item = new ItemStack(material);
ItemStack item = new ItemStack(display);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
assert meta != null; assert meta != null;
meta.setDisplayName("§eRepaired by " + materialName); meta.setDisplayName("§eRepaired by " +materialName);
meta.setLore(Arrays.asList( meta.setLore(Arrays.asList(
"§7There is currently §e" + reparableItemCount + " §7reparable item with " + materialName, "§7There is currently §e" +reparableItemCount+ " §7reparable item with "+materialName,
"§7Click here to open the menu to edit reparable item by " + materialName "§7Click here to open the menu to edit reparable item by " + materialName
)); ));
@ -94,16 +77,13 @@ public class UnitRepairConfigGui extends
} }
@Override @Override
protected Collection<NamespacedKey> getEveryInstanceOfGeneric() { protected Collection<Material> getEveryDisplayableInstanceOfGeneric() {
var materials = new HashSet<NamespacedKey>(); ArrayList<Material> materials = new ArrayList<>();
var config = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
for (String matName : config.getKeys(false)) { for (String matName : ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getKeys(false)) {
if(!config.isConfigurationSection(matName)) continue; Material mat = Material.getMaterial(matName.toUpperCase());
if(mat != null){
NamespacedKey material = NamespacedKey.fromString(matName.toLowerCase()); materials.add(mat);
if (material != null) {
materials.add(material);
} }
} }
return materials; return materials;
@ -133,7 +113,7 @@ public class UnitRepairConfigGui extends
"§7You like to be an unit repair item", "§7You like to be an unit repair item",
this, this,
(itemStack, player) -> { (itemStack, player) -> {
NamespacedKey type = MaterialUtil.INSTANCE.getCustomType(itemStack); Material type = itemStack.getType();
// Add new material // Add new material
updateValueForGeneric(type, true); updateValueForGeneric(type, true);
@ -146,9 +126,9 @@ public class UnitRepairConfigGui extends
} }
@NotNull @NotNull
public LazyElement<UnitRepairElementListGui> getInstanceOrCreate(NamespacedKey mat) { public LazyElement<UnitRepairElementListGui> getInstanceOrCreate(Material mat){
LazyElement<UnitRepairElementListGui> element = this.elementGuiMap.get(mat); LazyElement<UnitRepairElementListGui> element = this.elementGuiMap.get(mat);
if (element == null) { if(element == null){
updateValueForGeneric(mat, false); updateValueForGeneric(mat, false);
element = this.elementGuiMap.get(mat); element = this.elementGuiMap.get(mat);
@ -161,10 +141,8 @@ public class UnitRepairConfigGui extends
protected String genericDisplayedName() { protected String genericDisplayedName() {
return "this function Should not be used."; return "this function Should not be used.";
} }
@Override // Not used in this implementation. @Override // Not used in this implementation.
protected NamespacedKey createAndSaveNewEmptyGeneric(String name) { protected Material createAndSaveNewEmptyGeneric(String name) {
return null; return null;
} }
} }

View file

@ -23,21 +23,17 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
import java.util.function.Predicate;
public abstract class ElementListConfigGui<T> extends ChestGui implements ValueUpdatableGui { public abstract class ElementListConfigGui< T > extends ChestGui implements ValueUpdatableGui {
public static final int LIST_FILLER_START_X = 1;
public static final int LIST_FILLER_START_Y = 1;
public static final int LIST_FILLER_LENGTH = 7;
public static final int LIST_FILLER_HEIGHT = 4;
private final String namePrefix; private final String namePrefix;
protected PatternPane backgroundPane; protected PatternPane backgroundPane;
private Predicate<T> filter = (t) -> true; public static final int LIST_FILLER_START_X = 1;
private boolean hasDefaultFilter = true; public static final int LIST_FILLER_START_Y = 1;
public static final int LIST_FILLER_LENGTH = 7;
public static final int LIST_FILLER_HEIGHT = 4;
protected ElementListConfigGui(@NotNull String title, Gui parent) { protected ElementListConfigGui(@NotNull String title, Gui parent) {
super(6, title, CustomAnvil.instance); super(6, title, CustomAnvil.instance);
@ -50,12 +46,7 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
} }
public void setFilter(Predicate<T> filter) { protected Pattern getBackgroundPattern(){
this.filter = filter;
this.hasDefaultFilter = false;
}
protected Pattern getBackgroundPattern() {
return new Pattern( return new Pattern(
GuiSharedConstant.UPPER_FILLER_FULL_PLANE, GuiSharedConstant.UPPER_FILLER_FULL_PLANE,
GuiSharedConstant.EMPTY_FILLER_FULL_LINE, GuiSharedConstant.EMPTY_FILLER_FULL_LINE,
@ -70,7 +61,7 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
protected ArrayList<OutlinePane> pages; protected ArrayList<OutlinePane> pages;
protected HashMap<UUID, Integer> pageMap; protected HashMap<UUID, Integer> pageMap;
public void init() { public void init() { // Why I'm using an init function ? //TODO determine why is it using a init function and not used on constructor.
GuiGlobalItems.addBackgroundItem(this.backgroundPane); GuiGlobalItems.addBackgroundItem(this.backgroundPane);
this.backgroundPane.bindItem('1', GuiSharedConstant.SECONDARY_BACKGROUND_ITEM); this.backgroundPane.bindItem('1', GuiSharedConstant.SECONDARY_BACKGROUND_ITEM);
addPane(this.backgroundPane); addPane(this.backgroundPane);
@ -90,7 +81,7 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
protected GuiItem goLeftItem; protected GuiItem goLeftItem;
protected GuiItem goRightItem; protected GuiItem goRightItem;
protected void prepareStaticValues() { protected void prepareStaticValues(){
// Left item creation for consumer & bind // Left item creation for consumer & bind
this.goLeftItem = new GuiItem(new ItemStack(Material.RED_STAINED_GLASS_PANE), event -> { this.goLeftItem = new GuiItem(new ItemStack(Material.RED_STAINED_GLASS_PANE), event -> {
HumanEntity viewer = event.getWhoClicked(); HumanEntity viewer = event.getWhoClicked();
@ -121,23 +112,17 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
viewer.setItemOnCursor(cursor); viewer.setItemOnCursor(cursor);
}, CustomAnvil.instance); }, CustomAnvil.instance);
GuiItem createNew; GuiItem createNew = prepareCreateNewItem();
if(hasDefaultFilter) if(createNew != null){
createNew = prepareCreateNewItem();
else
createNew = GuiSharedConstant.SECONDARY_BACKGROUND_ITEM;
if (createNew != null) {
this.backgroundPane.bindItem('C', createNew); this.backgroundPane.bindItem('C', createNew);
} }
} }
protected void reloadValues(){
protected void reloadValues() {
this.firstPage.clear(); this.firstPage.clear();
this.pages.clear(); this.pages.clear();
this.pages.add(this.firstPage); this.pages.add(this.firstPage);
for (T generic : getDisplayableInstanceOfGeneric()) { for (T generic : getEveryDisplayableInstanceOfGeneric()) {
updateValueForGeneric(generic, false); updateValueForGeneric(generic, false);
} }
@ -262,7 +247,7 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
// set title // set title
StringBuilder title = new StringBuilder(this.namePrefix); StringBuilder title = new StringBuilder(this.namePrefix);
int pagesSize = this.pages.size(); int pagesSize = this.pages.size();
if (pagesSize > 1) { if(pagesSize > 1){
title.append(" (").append(pageID + 1).append('/').append(pagesSize).append(')'); title.append(" (").append(pageID + 1).append('/').append(pagesSize).append(')');
} }
setTitle(title.toString()); setTitle(title.toString());
@ -303,7 +288,7 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
public void removeGeneric(T generic) { public void removeGeneric(T generic) {
GuiItem item = findGuiItemForRemoval(generic); GuiItem item = findGuiItemForRemoval(generic);
if (item == null) return; if(item == null) return;
removeFromPage(item); removeFromPage(item);
update(); update();
@ -315,11 +300,7 @@ public abstract class ElementListConfigGui<T> extends ChestGui implements ValueU
protected abstract void updateGeneric(T generic, ItemStack usedItem); protected abstract void updateGeneric(T generic, ItemStack usedItem);
protected abstract Collection<T> getEveryInstanceOfGeneric(); protected abstract Collection<T> getEveryDisplayableInstanceOfGeneric();
protected Collection<T> getDisplayableInstanceOfGeneric() {
return getEveryInstanceOfGeneric().stream().filter(filter).toList();
}
@Override @Override
public void updateGuiValues() { public void updateGuiValues() {

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.gui.config.list; package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
@ -15,32 +14,27 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.function.Consumer; import java.util.function.Consumer;
public abstract class MappedElementListConfigGui<T, S> extends ElementListConfigGui<T> { public abstract class MappedElementListConfigGui< T, S > extends ElementListConfigGui< T > {
protected final HashMap<T, S> elementGuiMap; protected final HashMap<T, S> elementGuiMap;
protected MappedElementListConfigGui(@NotNull String title) {
protected MappedElementListConfigGui(@NotNull String title, @NotNull Gui parent) { super(title, MainConfigGui.getInstance());
super(title, parent);
this.elementGuiMap = new HashMap<>(); this.elementGuiMap = new HashMap<>();
} }
protected MappedElementListConfigGui(@NotNull String title) {
this(title, MainConfigGui.getInstance());
}
@Override @Override
protected GuiItem prepareCreateNewItem() { protected GuiItem prepareCreateNewItem(){
// Create new conflict item // Create new conflict item
ItemStack createItem = new ItemStack(Material.PAPER); ItemStack createItem = new ItemStack(Material.PAPER);
ItemMeta createMeta = createItem.getItemMeta(); ItemMeta createMeta = createItem.getItemMeta();
assert createMeta != null; assert createMeta != null;
createMeta.setDisplayName("§aCreate new " + genericDisplayedName()); createMeta.setDisplayName("§aCreate new "+genericDisplayedName());
createMeta.setLore(Arrays.asList( createMeta.setLore(Arrays.asList(
"§7Create a new " + genericDisplayedName() + ".", "§7Create a new "+genericDisplayedName()+".",
"§7You will be asked to name the " + genericDisplayedName() + " in chat.", "§7You will be asked to name the "+genericDisplayedName()+" in chat.",
"§7Then, you should edit the " + genericDisplayedName() + " config as you need" "§7Then, you should edit the "+genericDisplayedName()+" config as you need"
)); ));
createItem.setItemMeta(createMeta); createItem.setItemMeta(createMeta);
@ -57,8 +51,8 @@ public abstract class MappedElementListConfigGui<T, S> extends ElementListConfig
} }
player.closeInventory(); player.closeInventory();
player.sendMessage("§eWrite the " + genericDisplayedName() + " name you want to create in the chat.\n" + player.sendMessage("§eWrite the "+genericDisplayedName()+" name you want to create in the chat.\n" +
"§eOr write §ccancel §eto go back to " + genericDisplayedName() + " config menu"); "§eOr write §ccancel §eto go back to "+genericDisplayedName()+" config menu");
CustomAnvil.Companion.getChatListener().setListenedCallback(player, prepareCreateItemConsumer(player)); CustomAnvil.Companion.getChatListener().setListenedCallback(player, prepareCreateItemConsumer(player));

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.gui.config.list; package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
@ -15,22 +14,19 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui.LazyElement<?>> public abstract class MappedGuiListConfigGui< T, S extends MappedGuiListConfigGui.LazyElement<?>>
extends MappedElementListConfigGui<T, S> { extends MappedElementListConfigGui< T, S > {
protected MappedGuiListConfigGui(@NotNull String title) { protected MappedGuiListConfigGui(@NotNull String title) {
super(title); super(title);
}
protected MappedGuiListConfigGui(@NotNull String title, @NotNull Gui parent) {
super(title, parent);
} }
@Override @Override
public void reloadValues() { public void reloadValues() {
this.elementGuiMap.forEach((conflict, element) -> { this.elementGuiMap.forEach((conflict, element) -> {
ElementMappedToListGui gui = element.getStored(); ElementMappedToListGui gui = element.getStored();
if (gui != null) gui.cleanAndBeUnusable(); if(gui != null) gui.cleanAndBeUnusable();
}); });
this.elementGuiMap.clear(); this.elementGuiMap.clear();
@ -53,7 +49,7 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
@Override @Override
protected void updateElement(T generic, S element) { protected void updateElement(T generic, S element) {
ElementMappedToListGui gui = element.getStored(); ElementMappedToListGui gui = element.getStored();
if (gui != null) gui.updateLocal(); if(gui != null) gui.updateLocal();
} }
@Override @Override
@ -62,7 +58,7 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
} }
@Override @Override
protected Consumer<String> prepareCreateItemConsumer(HumanEntity player) { protected Consumer<String> prepareCreateItemConsumer(HumanEntity player){
AtomicReference<Consumer<String>> selfRef = new AtomicReference<>(); AtomicReference<Consumer<String>> selfRef = new AtomicReference<>();
Consumer<String> selfCallback = (message) -> { Consumer<String> selfCallback = (message) -> {
if (message == null) return; if (message == null) return;
@ -75,7 +71,7 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
message = message.toLowerCase(Locale.ROOT); message = message.toLowerCase(Locale.ROOT);
if ("cancel".equalsIgnoreCase(message)) { if ("cancel".equalsIgnoreCase(message)) {
player.sendMessage(genericDisplayedName() + " creation cancelled..."); player.sendMessage(genericDisplayedName()+" creation cancelled...");
show(player); show(player);
return; return;
} }
@ -84,9 +80,9 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
// Try to find if it already exists in a for loop // Try to find if it already exists in a for loop
// Not the most efficient on large number of conflict, but it should not run often. // Not the most efficient on large number of conflict, but it should not run often.
for (T generic : getDisplayableInstanceOfGeneric()) { for (T generic : getEveryDisplayableInstanceOfGeneric()) {
if (generic.toString().equalsIgnoreCase(message)) { if (generic.toString().equalsIgnoreCase(message)) {
player.sendMessage("§cPlease enter a " + genericDisplayedName() + " name that do not already exist..."); player.sendMessage("§cPlease enter a "+genericDisplayedName()+" name that do not already exist...");
// wait next message. // wait next message.
CustomAnvil.Companion.getChatListener().setListenedCallback(player, selfRef.get()); CustomAnvil.Companion.getChatListener().setListenedCallback(player, selfRef.get());
return; return;
@ -94,7 +90,7 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
} }
T generic = createAndSaveNewEmptyGeneric(message); T generic = createAndSaveNewEmptyGeneric(message);
if (generic == null) {// we don't know what to do. so we back up by opening this gui. if(generic == null) {// we don't know what to do. so we back up by opening this gui.
this.show(player); this.show(player);
return; return;
} }
@ -121,7 +117,6 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
private final GuiItem parentItem; private final GuiItem parentItem;
private final LazyValue<Consumer<InventoryClickEvent>> lazyOpenConsumer; private final LazyValue<Consumer<InventoryClickEvent>> lazyOpenConsumer;
public LazyElement(GuiItem parentItem, Supplier<T> valueSupplier) { public LazyElement(GuiItem parentItem, Supplier<T> valueSupplier) {
super(valueSupplier); super(valueSupplier);
this.parentItem = parentItem; this.parentItem = parentItem;
@ -136,7 +131,7 @@ public abstract class MappedGuiListConfigGui<T, S extends MappedGuiListConfigGui
} }
@NotNull @NotNull
public Consumer<InventoryClickEvent> openAction() { public Consumer<InventoryClickEvent> openAction(){
return event -> lazyOpenConsumer.get().accept(event); return event -> lazyOpenConsumer.get().accept(event);
} }

View file

@ -15,11 +15,10 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
public abstract class SettingGuiListConfigGui<T, S extends SettingGui.SettingGuiFactory> extends ElementListConfigGui<T> { public abstract class SettingGuiListConfigGui< T, S extends SettingGui.SettingGuiFactory> extends ElementListConfigGui< T >{
protected HashMap<T, GuiItem> guiItemMap; protected HashMap<T, GuiItem> guiItemMap;
protected HashMap<T, S> factoryMap; protected HashMap<T, S> factoryMap;
protected SettingGuiListConfigGui(@NotNull String title, Gui parent) { protected SettingGuiListConfigGui(@NotNull String title, Gui parent) {
super(title, parent); super(title, parent);
this.guiItemMap = new HashMap<>(); this.guiItemMap = new HashMap<>();
@ -45,7 +44,7 @@ public abstract class SettingGuiListConfigGui<T, S extends SettingGui.SettingGui
@Override @Override
public void updateValueForGeneric(T generic, boolean shouldUpdate) { public void updateValueForGeneric(T generic, boolean shouldUpdate) {
if (!this.factoryMap.containsKey(generic)) { if(!this.factoryMap.containsKey(generic)){
// Create new item & factory // Create new item & factory
S factory = createFactory(generic); S factory = createFactory(generic);
GuiItem newItem = itemFromFactory(generic, factory); GuiItem newItem = itemFromFactory(generic, factory);
@ -53,7 +52,7 @@ public abstract class SettingGuiListConfigGui<T, S extends SettingGui.SettingGui
addToPage(newItem); addToPage(newItem);
this.guiItemMap.put(generic, newItem); this.guiItemMap.put(generic, newItem);
this.factoryMap.put(generic, factory); this.factoryMap.put(generic, factory);
} else { }else{
S factory = this.factoryMap.get(generic); S factory = this.factoryMap.get(generic);
// Update old item // Update old item
GuiItem oldItem = this.guiItemMap.get(generic); GuiItem oldItem = this.guiItemMap.get(generic);
@ -62,7 +61,7 @@ public abstract class SettingGuiListConfigGui<T, S extends SettingGui.SettingGui
updateGuiItem(oldItem, newItem); updateGuiItem(oldItem, newItem);
} }
if (shouldUpdate) { if(shouldUpdate){
update(); update();
} }
} }
@ -75,7 +74,7 @@ public abstract class SettingGuiListConfigGui<T, S extends SettingGui.SettingGui
super.reloadValues(); super.reloadValues();
} }
private void updateGuiItem(GuiItem oldITem, GuiItem newItem) { private void updateGuiItem(GuiItem oldITem, GuiItem newItem){
oldITem.setItem(newItem.getItem()); oldITem.setItem(newItem.getItem());
oldITem.setProperties(newItem.getProperties()); oldITem.setProperties(newItem.getProperties());
oldITem.setVisible(newItem.isVisible()); oldITem.setVisible(newItem.isVisible());
@ -87,22 +86,17 @@ public abstract class SettingGuiListConfigGui<T, S extends SettingGui.SettingGui
} }
@Override // Not used @Override // Not used
protected void updateGeneric(T generic, ItemStack usedItem) { protected void updateGeneric(T generic, ItemStack usedItem) {}
}
@Override // Not used @Override // Not used
protected ItemStack createItemForGeneric(T generic) { protected ItemStack createItemForGeneric(T generic) {
return null; return null;
} }
protected abstract List<String> getCreateItemLore(); protected abstract List<String> getCreateItemLore();
protected abstract Consumer<InventoryClickEvent> getCreateClickConsumer(); protected abstract Consumer<InventoryClickEvent> getCreateClickConsumer();
protected abstract String createItemName(); protected abstract String createItemName();
protected abstract S createFactory(T generic); protected abstract S createFactory(T generic);
protected abstract GuiItem itemFromFactory(T generic, S factory); protected abstract GuiItem itemFromFactory(T generic, S factory);

View file

@ -3,14 +3,12 @@ package xyz.alexcrea.cuanvil.gui.config.list;
import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.util.Gui; import com.github.stefvanschie.inventoryframework.gui.type.util.Gui;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.gui.config.ask.SelectItemTypeGui; import xyz.alexcrea.cuanvil.gui.config.ask.SelectItemTypeGui;
import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui; import xyz.alexcrea.cuanvil.gui.config.global.UnitRepairConfigGui;
@ -19,25 +17,26 @@ import xyz.alexcrea.cuanvil.gui.config.settings.DoubleSettingGui;
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems; import xyz.alexcrea.cuanvil.gui.util.GuiGlobalItems;
import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant; import xyz.alexcrea.cuanvil.gui.util.GuiSharedConstant;
import xyz.alexcrea.cuanvil.util.CasedStringUtil; import xyz.alexcrea.cuanvil.util.CasedStringUtil;
import xyz.alexcrea.cuanvil.util.MaterialUtil;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
public class UnitRepairElementListGui extends SettingGuiListConfigGui<NamespacedKey, DoubleSettingGui.DoubleSettingFactory> implements ElementMappedToListGui { public class UnitRepairElementListGui extends SettingGuiListConfigGui<String, DoubleSettingGui.DoubleSettingFactory> implements ElementMappedToListGui {
private final NamespacedKey parentMaterial; private final Material parentMaterial;
private final UnitRepairConfigGui parentGui; private final UnitRepairConfigGui parentGui;
private final String materialName; private final String materialName;
private boolean shouldWork = true; private boolean shouldWork = true;
public UnitRepairElementListGui(@NotNull Material parentMaterial,
public UnitRepairElementListGui(@NotNull NamespacedKey parentMaterial,
@NotNull UnitRepairConfigGui parentGui) { @NotNull UnitRepairConfigGui parentGui) {
super("§e" + CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.getKey().toLowerCase()) + " §rUnit repair"); super("§e" + CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase()) + " §rUnit repair");
this.parentMaterial = parentMaterial; this.parentMaterial = parentMaterial;
this.parentGui = parentGui; this.parentGui = parentGui;
this.materialName = CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.getKey().toLowerCase()); this.materialName = CasedStringUtil.snakeToUpperSpacedCase(parentMaterial.name().toLowerCase());
GuiGlobalItems.addBackItem(this.backgroundPane, parentGui); GuiGlobalItems.addBackItem(this.backgroundPane, parentGui);
} }
@ -55,7 +54,7 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<Namespaced
protected Consumer<InventoryClickEvent> getCreateClickConsumer() { protected Consumer<InventoryClickEvent> getCreateClickConsumer() {
return event -> { return event -> {
event.setCancelled(true); event.setCancelled(true);
if (!this.shouldWork) { if(!this.shouldWork){
return; return;
} }
event.setCancelled(true); event.setCancelled(true);
@ -67,28 +66,28 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<Namespaced
this, this,
(itemStack, player) -> { (itemStack, player) -> {
ItemMeta meta = itemStack.getItemMeta(); ItemMeta meta = itemStack.getItemMeta();
NamespacedKey type = MaterialUtil.INSTANCE.getCustomType(itemStack); Material type = itemStack.getType();
if (!(meta instanceof Damageable)) { if(!(meta instanceof Damageable) || (type.getMaxDurability() <= 0)) {
player.sendMessage("§cThis item can't be damaged, so it can't be repaired."); player.sendMessage("§cThis item can't be damaged, so it can't be repaired.");
return; return;
} }
if (type.equals(this.parentMaterial)) { if(type == this.parentMaterial){
player.sendMessage("§cItem can't repair something of the same type."); player.sendMessage("§cItem can't repair something of the same type.");
return; return;
} }
String materialName = type.toString(); String materialName = type.name().toLowerCase();
// Add new material // Add new material
ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().set(parentMaterial.toString().toLowerCase() + "." + materialName, 0.25); ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().set(parentMaterial.name().toLowerCase() + "." + materialName,0.25);
if (GuiSharedConstant.TEMPORARY_DO_SAVE_TO_DISK_EVERY_CHANGE) { if (GuiSharedConstant.TEMPORARY_DO_SAVE_TO_DISK_EVERY_CHANGE) {
ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(GuiSharedConstant.TEMPORARY_DO_BACKUP_EVERY_SAVE); ConfigHolder.UNIT_REPAIR_HOLDER.saveToDisk(GuiSharedConstant.TEMPORARY_DO_BACKUP_EVERY_SAVE);
} }
// Update gui // Update gui
updateValueForGeneric(type, true); updateValueForGeneric(materialName, true);
this.parentGui.updateValueForGeneric(this.parentMaterial, true); this.parentGui.updateValueForGeneric(this.parentMaterial, true);
@ -107,17 +106,17 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<Namespaced
} }
@Override @Override
protected DoubleSettingGui.DoubleSettingFactory createFactory(NamespacedKey materialName) { protected DoubleSettingGui.DoubleSettingFactory createFactory(String materialName) {
String materialDisplayName = CasedStringUtil.snakeToUpperSpacedCase(materialName.getKey()); String materialDisplayName = CasedStringUtil.snakeToUpperSpacedCase(materialName);
return new DoubleSettingGui.DoubleSettingFactory( return new DoubleSettingGui.DoubleSettingFactory(
"§0%§8" + materialDisplayName + " Repair", "§0%§8" + materialDisplayName +" Repair",
this, this,
ConfigHolder.UNIT_REPAIR_HOLDER, ConfigHolder.UNIT_REPAIR_HOLDER,
this.parentMaterial.toString().toLowerCase() + "." + materialName, this.parentMaterial.name().toLowerCase()+"."+materialName,
Arrays.asList( Arrays.asList(
"§7Click here to change how many §e% §7of §a" + materialDisplayName, "§7Click here to change how many §e% §7of §a" + materialDisplayName,
"§7Should get repaired by §e" + this.materialName "§7Should get repaired by §e"+this.materialName
), ),
2, 2,
true, true, true, true,
@ -129,40 +128,29 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<Namespaced
} }
@Override @Override
protected GuiItem itemFromFactory(NamespacedKey materialName, DoubleSettingGui.DoubleSettingFactory factory) { protected GuiItem itemFromFactory(String materialName, DoubleSettingGui.DoubleSettingFactory factory) {
return factory.getItem(materialFromName(materialName), return factory.getItem(materialFromName(materialName),
"§7%§a" + CasedStringUtil.snakeToUpperSpacedCase(materialName.getKey()) + " §erepaired by §a" + this.materialName); "§7%§a" + CasedStringUtil.snakeToUpperSpacedCase(materialName)+ " §erepaired by §a" + this.materialName);
} }
@Override @Override
protected Collection<NamespacedKey> getEveryInstanceOfGeneric() { protected Collection<String> getEveryDisplayableInstanceOfGeneric() {
Set<NamespacedKey> keys = new HashSet<>(); ArrayList<String> keys = new ArrayList<>();
if (!this.shouldWork) { if(!this.shouldWork){
return keys; return keys;
} }
ConfigurationSection legacySection = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(parentMaterial.getKey().toLowerCase()); ConfigurationSection materialSection = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(parentMaterial.name().toLowerCase());
ConfigurationSection materialSection = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig().getConfigurationSection(parentMaterial.toString().toLowerCase()); if(materialSection == null){
return keys;
addAllKeys(legacySection, keys); }
addAllKeys(materialSection, keys); keys.addAll(materialSection.getKeys(false));
return keys; return keys;
} }
private void addAllKeys(@Nullable ConfigurationSection section, @NotNull Set<NamespacedKey> keys) { private Material materialFromName(String materialName){
if (section == null) return; Material mat = Material.getMaterial(materialName.toUpperCase());
for (var key : section.getKeys(false)) { if(mat == null || mat.isAir()) return Material.BARRIER;
var material = NamespacedKey.fromString(key);
if (material == null) continue;
keys.add(material);
}
}
private Material materialFromName(NamespacedKey material) {
Material mat = MaterialUtil.INSTANCE.getMatFromKey(material);
if (mat == null || mat.isAir()) return Material.BARRIER;
return mat; return mat;
} }
@ -175,8 +163,7 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<Namespaced
// ElementMappedToListGui methods // ElementMappedToListGui methods
@Override // Not used in this implementation @Override // Not used in this implementation
public void updateLocal() { public void updateLocal() {}
}
@Override @Override
public void cleanAndBeUnusable() { public void cleanAndBeUnusable() {
@ -198,7 +185,7 @@ public class UnitRepairElementListGui extends SettingGuiListConfigGui<Namespaced
@Override @Override
public void show(@NotNull HumanEntity humanEntity) { public void show(@NotNull HumanEntity humanEntity) {
if (!this.shouldWork) { if(!this.shouldWork){
humanEntity.closeInventory(); humanEntity.closeInventory();
return; return;
} }

View file

@ -183,7 +183,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
assert nowMeta != null; assert nowMeta != null;
nowMeta.setDisplayName("§fValue: §e" + nowBook); nowMeta.setDisplayName("§fValue: §e" + nowBook);
if (!holder.displayLore.isEmpty()) { if(!holder.displayLore.isEmpty()){
nowMeta.setLore(holder.displayLore); nowMeta.setLore(holder.displayLore);
} }
@ -202,6 +202,7 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
} }
pane.bindItem('D', returnToDefault); pane.bindItem('D', returnToDefault);
} }
/** /**
@ -284,14 +285,14 @@ public class EnchantCostSettingsGui extends IntSettingsGui {
*/ */
@Override @Override
public int getConfiguredValue() { public int getConfiguredValue() {
return ConfigOptions.INSTANCE.enchantmentValue(enchantment, false, false); return ConfigOptions.INSTANCE.enchantmentValue(enchantment, false);
} }
/** /**
* @return The configured value for the enchant setting book value. * @return The configured value for the enchant setting book value.
*/ */
public int getConfiguredBookValue() { public int getConfiguredBookValue() {
return ConfigOptions.INSTANCE.enchantmentValue(enchantment, false, true); return ConfigOptions.INSTANCE.enchantmentValue(enchantment, true);
} }
@Override @Override

View file

@ -63,7 +63,7 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui<CAEnchantme
} }
@Override @Override
protected Collection<CAEnchantment> getEveryInstanceOfGeneric() { protected Collection<CAEnchantment> getEveryDisplayableInstanceOfGeneric() {
Stream<CAEnchantment> toDisplayStream; Stream<CAEnchantment> toDisplayStream;
if(this.displayUnselected){ if(this.displayUnselected){
toDisplayStream = CAEnchantmentRegistry.getInstance().getNameSortedEnchantments().stream(); toDisplayStream = CAEnchantmentRegistry.getInstance().getNameSortedEnchantments().stream();

View file

@ -318,9 +318,9 @@ public class IntSettingsGui extends AbstractSettingGui {
this.defaultVal = defaultVal; this.defaultVal = defaultVal;
this.steps = steps; this.steps = steps;
if (displayLore == null) { if(displayLore == null){
this.displayLore = Collections.emptyList(); this.displayLore = Collections.emptyList();
} else { }else {
this.displayLore = displayLore; this.displayLore = displayLore;
} }
} }
@ -392,7 +392,7 @@ public class IntSettingsGui extends AbstractSettingGui {
protected String deltaDisplay(ValueDisplayType type, int now, int planned) { protected String deltaDisplay(ValueDisplayType type, int now, int planned) {
var delta = planned - now; var delta = planned - now;
if (delta < 0) return "§c" + delta; if(delta < 0) return "§c" + delta;
else return "§a+" + delta; else return "§a+" + delta;
} }

View file

@ -217,7 +217,7 @@ public class MaterialSelectSettingGui extends MappedElementListConfigGui<Namespa
} }
@Override @Override
protected Collection<NamespacedKey> getEveryInstanceOfGeneric() { protected Collection<NamespacedKey> getEveryDisplayableInstanceOfGeneric() {
return this.defaultMaterials; return this.defaultMaterials;
} }

View file

@ -2,7 +2,10 @@ package xyz.alexcrea.cuanvil.update;
import io.delilaheve.CustomAnvil; import io.delilaheve.CustomAnvil;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.update.minecraft.*; import xyz.alexcrea.cuanvil.update.minecraft.MCUpdate;
import xyz.alexcrea.cuanvil.update.minecraft.Update_1_21;
import xyz.alexcrea.cuanvil.update.minecraft.Update_1_21_11;
import xyz.alexcrea.cuanvil.update.minecraft.Update_1_21_9;
import xyz.alexcrea.cuanvil.update.plugin.*; import xyz.alexcrea.cuanvil.update.plugin.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -29,12 +32,10 @@ public class UpdateHandler {
new Version(1, 8, 0), PUpdate_1_8_0::handleUpdate, new Version(1, 8, 0), PUpdate_1_8_0::handleUpdate,
new Version(1, 11, 0), PUpdate_1_11_0::handleUpdate, new Version(1, 11, 0), PUpdate_1_11_0::handleUpdate,
new Version(1, 15, 5), PUpdate_1_15_5::handleUpdate, new Version(1, 15, 5), PUpdate_1_15_5::handleUpdate,
new Version(1, 15, 6), PUpdate_1_15_6::handleUpdate, new Version(1, 15, 6), PUpdate_1_15_6::handleUpdate
new Version(1, 17, 7), PUpdate_1_17_7::handleUpdate
); );
private static final List<MCUpdate> mcUpdateMap = List.of( private static final List<MCUpdate> mcUpdateMap = List.of(
new Update_1_20_5(),
new Update_1_21(), new Update_1_21(),
new Update_1_21_9(), new Update_1_21_9(),
new Update_1_21_11() new Update_1_21_11()

View file

@ -1,7 +1,6 @@
package xyz.alexcrea.cuanvil.update; package xyz.alexcrea.cuanvil.update;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import java.util.ArrayList; import java.util.ArrayList;
@ -34,20 +33,4 @@ public class UpdateUtils {
} }
public static boolean removeFromList(FileConfiguration config, String path, String toRemove) {
List<String> groups = new ArrayList<>(config.getStringList(path));
if (!groups.remove(toRemove)) return false;
config.set(path, groups);
return true;
}
public static void mergeSections(ConfigurationSection source, ConfigurationSection target) {
for (String key : source.getKeys(false)) {
if(target.contains(key)) continue;
target.set(key, source.get(key));
}
}
} }

View file

@ -1,98 +0,0 @@
package xyz.alexcrea.cuanvil.update.minecraft;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.update.Version;
import java.util.HashSet;
import java.util.Set;
import static xyz.alexcrea.cuanvil.update.UpdateUtils.*;
public class Update_1_20_5 extends MCUpdate {
public Update_1_20_5() {
super(new Version(1, 20, 5));
}
@Override
protected void doUpdate() {
var tosave = new HashSet<ConfigHolder>();
updateName(tosave);
for (ConfigHolder holder : tosave) {
holder.saveToDisk(true);
}
}
private static String SWEEPING_ENCHANTS = "restriction_sweeping_edge.enchantments";
public static void updateName(@NotNull Set<ConfigHolder> tosave) {
var config = ConfigHolder.DEFAULT_CONFIG.getConfig();
var unitConfig = ConfigHolder.UNIT_REPAIR_HOLDER.getConfig();
var conflict = ConfigHolder.CONFLICT_HOLDER.getConfig();
// Rename sweeping to sweeping_edge
migrateEnchantLimit(config, "minecraft:sweeping");
migrateEnchantLimit(config, "sweeping");
migrateEnchantValues(config, "minecraft:sweeping");
migrateEnchantValues(config, "sweeping");
if (removeFromList(conflict, SWEEPING_ENCHANTS, "minecraft:sweeping"))
addAbsentToList(conflict, SWEEPING_ENCHANTS, "minecraft:sweeping_edge");
if (removeFromList(conflict, SWEEPING_ENCHANTS, "sweeping"))
addAbsentToList(conflict, SWEEPING_ENCHANTS, "minecraft:sweeping_edge");
// Rename scute to turtle_scute
migrateUnitRepair(unitConfig, "minecraft:scute");
migrateUnitRepair(unitConfig, "scute");
ConfigHolder.ITEM_GROUP_HOLDER.reload();
tosave.add(ConfigHolder.DEFAULT_CONFIG);
tosave.add(ConfigHolder.UNIT_REPAIR_HOLDER);
tosave.add(ConfigHolder.CONFLICT_HOLDER);
}
private static void migrateEnchantLimit(FileConfiguration config, String path) {
var finalPath = "enchant_limits." + path;
if (!config.isInt(finalPath)) return;
var value = config.getInt(finalPath);
config.set(finalPath, null);
if (!config.contains("enchant_limits.minecraft:sweeping_edge")) return;
if (!config.contains("enchant_limits.sweeping_edge")) return;
config.set("enchant_limits.minecraft:sweeping_edge", value);
}
private static void migrateEnchantValues(FileConfiguration config, String path) {
migrateEnchantValues(config, path, "item");
migrateEnchantValues(config, path, "book");
}
private static void migrateEnchantValues(FileConfiguration config, String path, String child) {
var finalPath = "enchant_values." + path + "." + child;
if (config.isInt(finalPath)) return;
var value = config.getInt(finalPath);
config.set(finalPath, null);
if (!config.contains("enchant_values.minecraft:sweeping_edge." + child)) return;
if (!config.contains("enchant_values.sweeping_edge." + child)) return;
config.set("enchant_values.minecraft:sweeping_edge." + child, value);
}
private static void migrateUnitRepair(FileConfiguration config, String path) {
var section = config.getConfigurationSection(path);
if (section == null) return;
config.set(path, null);
var turtle_scute = config.getConfigurationSection("minecraft:turtle_scute");
if (turtle_scute == null) config.set("minecraft:turtle_scute", section);
else mergeSections(section, turtle_scute);
}
}

View file

@ -1,5 +1,6 @@
package xyz.alexcrea.cuanvil.update.minecraft; package xyz.alexcrea.cuanvil.update.minecraft;
import io.delilaheve.CustomAnvil;
import xyz.alexcrea.cuanvil.config.ConfigHolder; import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.update.UpdateUtils; import xyz.alexcrea.cuanvil.update.UpdateUtils;
import xyz.alexcrea.cuanvil.update.Version; import xyz.alexcrea.cuanvil.update.Version;

View file

@ -38,26 +38,26 @@ public class Update_1_21_11 extends MCUpdate{
addAbsentToList(conflictConfig, "restriction_fire_aspect.notAffectedGroups", "spears"); addAbsentToList(conflictConfig, "restriction_fire_aspect.notAffectedGroups", "spears");
// Unit repair for spears // Unit repair for spears
unitConfig.set("minecraft:gold_ingot.minecraft:golden_spear", 0.25); unitConfig.set("gold_ingot.golden_spear", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_spear", 0.25); unitConfig.set("copper_ingot.copper_spear", 0.25);
unitConfig.set("minecraft:iron_ingot.minecraft:iron_spear", 0.25); unitConfig.set("iron_ingot.iron_spear", 0.25);
unitConfig.set("minecraft:diamond.minecraft:diamond_spear", 0.25); unitConfig.set("diamond.diamond_spear", 0.25);
unitConfig.set("minecraft:netherite_ingot.minecraft:netherite_spear", 0.25); unitConfig.set("netherite_ingot.netherite_spear", 0.25);
unitConfig.set("minecraft:cobblestone.stone_spear", 0.25); unitConfig.set("cobblestone.stone_spear", 0.25);
unitConfig.set("minecraft:cobbled_deepslate.stone_spear", 0.25); unitConfig.set("cobbled_deepslate.stone_spear", 0.25);
unitConfig.set("minecraft:oak_planks.minecraft:wooden_spear", 0.25); unitConfig.set("oak_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:spruce_planks.minecraft:wooden_spear", 0.25); unitConfig.set("spruce_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:birch_planks.minecraft:wooden_spear", 0.25); unitConfig.set("birch_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:jungle_planks.minecraft:wooden_spear", 0.25); unitConfig.set("jungle_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:acacia_planks.minecraft:wooden_spear", 0.25); unitConfig.set("acacia_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:dark_oak_planks.minecraft:wooden_spear", 0.25); unitConfig.set("dark_oak_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:mangrove_planks.minecraft:wooden_spear", 0.25); unitConfig.set("mangrove_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:cherry_planks.minecraft:wooden_spear", 0.25); unitConfig.set("cherry_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:bamboo_planks.minecraft:wooden_spear", 0.25); unitConfig.set("bamboo_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:crimson_planks.minecraft:wooden_spear", 0.25); unitConfig.set("crimson_planks.wooden_spear", 0.25);
unitConfig.set("minecraft:warped_planks.minecraft:wooden_spear", 0.25); unitConfig.set("warped_planks.wooden_spear", 0.25);
// Create lunge enchant value and group // Create lunge enchant value and group
baseConfig.set("enchant_limits.minecraft:lunge", 3); baseConfig.set("enchant_limits.minecraft:lunge", 3);

View file

@ -49,16 +49,16 @@ public class Update_1_21_9 extends MCUpdate{
public static void addCopperUnitRepair(FileConfiguration unitConfig) { public static void addCopperUnitRepair(FileConfiguration unitConfig) {
// Add unit repair // Add unit repair
unitConfig.set("minecraft:copper_ingot.minecraft:copper_helmet", 0.25); unitConfig.set("copper_ingot.copper_helmet", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_chestplate", 0.25); unitConfig.set("copper_ingot.copper_chestplate", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_leggings", 0.25); unitConfig.set("copper_ingot.copper_leggings", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_boots", 0.25); unitConfig.set("copper_ingot.copper_boots", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_pickaxe", 0.25); unitConfig.set("copper_ingot.copper_pickaxe", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_shovel", 0.25); unitConfig.set("copper_ingot.copper_shovel", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_hoe", 0.25); unitConfig.set("copper_ingot.copper_hoe", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_axe", 0.25); unitConfig.set("copper_ingot.copper_axe", 0.25);
unitConfig.set("minecraft:copper_ingot.minecraft:copper_sword", 0.25); unitConfig.set("copper_ingot.copper_sword", 0.25);
} }
} }

View file

@ -1,21 +0,0 @@
package xyz.alexcrea.cuanvil.update.plugin;
import xyz.alexcrea.cuanvil.config.ConfigHolder;
import xyz.alexcrea.cuanvil.update.UpdateUtils;
import xyz.alexcrea.cuanvil.update.Version;
import xyz.alexcrea.cuanvil.update.minecraft.Update_1_20_5;
import javax.annotation.Nonnull;
import java.util.Set;
public class PUpdate_1_17_7 {
public static void handleUpdate(@Nonnull Set<ConfigHolder> toSave) {
// fix only needed for 1.20.5 and above
Version current = UpdateUtils.currentMinecraftVersion();
if (new Version(1, 20, 5).greaterThan(current)) return;
Update_1_20_5.updateName(toSave);
}
}

View file

@ -24,7 +24,6 @@ import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener
import xyz.alexcrea.cuanvil.update.ModrinthUpdateChecker import xyz.alexcrea.cuanvil.update.ModrinthUpdateChecker
import xyz.alexcrea.cuanvil.update.PluginSetDefault import xyz.alexcrea.cuanvil.update.PluginSetDefault
import xyz.alexcrea.cuanvil.update.UpdateHandler import xyz.alexcrea.cuanvil.update.UpdateHandler
import xyz.alexcrea.cuanvil.update.UpdateUtils
import xyz.alexcrea.cuanvil.util.MetricsUtil import xyz.alexcrea.cuanvil.util.MetricsUtil
import java.io.File import java.io.File
import java.io.FileReader import java.io.FileReader
@ -57,8 +56,6 @@ open class CustomAnvil : JavaPlugin() {
// Permission string required to edit the plugin's config // Permission string required to edit the plugin's config
const val editConfigPermission = "ca.config.edit" const val editConfigPermission = "ca.config.edit"
// Permission string required to edit the plugin's config
const val giveEnchantmentPermission = "ca.command.enchantment"
// Command Name to reload the config // Command Name to reload the config
const val commandReloadName = "anvilconfigreload" const val commandReloadName = "anvilconfigreload"
@ -226,8 +223,7 @@ open class CustomAnvil : JavaPlugin() {
val version = description.version val version = description.version
val featured = if(version.contains("dev")) null else true val featured = if(version.contains("dev")) null else true
ModrinthUpdateChecker(modrinthPluginID, loader, ModrinthUpdateChecker(modrinthPluginID, loader, null)
UpdateUtils.currentMinecraftVersion().toString())
.setFeatured(featured) .setFeatured(featured)
.setOnError { .setOnError {
logger.log(Level.WARNING, "error trying to fetch latest update", it) logger.log(Level.WARNING, "error trying to fetch latest update", it)

View file

@ -86,7 +86,6 @@ object ConfigOptions {
// Keys for specific enchantment values // Keys for specific enchantment values
private const val KEY_BOOK = "book" private const val KEY_BOOK = "book"
private const val KEY_BOOK_ON_BOOK = "book_on_book"
private const val KEY_ITEM = "item" private const val KEY_ITEM = "item"
// Debug flag // Debug flag
@ -579,15 +578,14 @@ object ConfigOptions {
*/ */
fun enchantmentValue( fun enchantmentValue(
enchantment: CAEnchantment, enchantment: CAEnchantment,
isToBook: Boolean, isFromBook: Boolean
isFromBook: Boolean,
): Int { ): Int {
// Test namespace // Test namespace
var limit = enchantmentValue(enchantment.key.toString(), isToBook, isFromBook) var limit = enchantmentValue(enchantment.key.toString(), isFromBook)
if (limit != null) return limit if (limit != null) return limit
// Test legacy (name only) // Test legacy (name only)
limit = enchantmentValue(enchantment.enchantmentName, isToBook, isFromBook) limit = enchantmentValue(enchantment.enchantmentName, isFromBook)
if (limit != null) return limit if (limit != null) return limit
// get default (and test old legacy if present) // get default (and test old legacy if present)
@ -601,22 +599,13 @@ object ConfigOptions {
*/ */
private fun enchantmentValue( private fun enchantmentValue(
enchantmentName: String, enchantmentName: String,
isToBook: Boolean, isFromBook: Boolean
isFromBook: Boolean,
): Int? { ): Int? {
val typeKey = if (isFromBook) KEY_BOOK else KEY_ITEM val typeKey = if (isFromBook) KEY_BOOK else KEY_ITEM
val path = "${ENCHANT_VALUES_ROOT}.${enchantmentName}.$typeKey" val path = "${ENCHANT_VALUES_ROOT}.${enchantmentName}.$typeKey"
return CustomAnvil.instance
val config = ConfigHolder.DEFAULT_CONFIG.config .config
if(isFromBook && isToBook) { .getInt(path, DEFAULT_ENCHANT_VALUE - 1)
val specialPath = "${ENCHANT_VALUES_ROOT}.${enchantmentName}.$KEY_BOOK_ON_BOOK"
if(config.isInt(specialPath))
return config.getInt(specialPath)
.takeIf { it >= DEFAULT_ENCHANT_VALUE }
}
return config.getInt(path, DEFAULT_ENCHANT_VALUE - 1)
.takeIf { it >= DEFAULT_ENCHANT_VALUE } .takeIf { it >= DEFAULT_ENCHANT_VALUE }
} }
@ -624,9 +613,20 @@ object ConfigOptions {
* Get default value if enchantment do not exist on config * Get default value if enchantment do not exist on config
*/ */
private fun getDefaultValue( private fun getDefaultValue(
enchantment: CAEnchantment, enchantment: CAEnchantment, // compatibility with 1.20.5. TODO better update system
isFromBook: Boolean isFromBook: Boolean
): Int { ): Int {
val enchantmentName = enchantment.key.toString()
if (enchantmentName == "minecraft:sweeping_edge") {
var limit = enchantmentValue("minecraft:sweeping", isFromBook)
if (limit != null) return limit
// legacy name
limit = enchantmentValue("sweeping", isFromBook)
if (limit != null) return limit
}
val rarity = enchantment.defaultRarity() val rarity = enchantment.defaultRarity()
return if (isFromBook) return if (isFromBook)
rarity.bookValue rarity.bookValue
@ -648,6 +648,15 @@ object ConfigOptions {
value = maxBeforeMergeDisabled(legacy) value = maxBeforeMergeDisabled(legacy)
if (value >= 0) return value if (value >= 0) return value
if (key == "minecraft:sweeping_edge") {
value = maxBeforeMergeDisabled("minecraft:sweeping")
if (value >= 0) return value
// legacy name of legacy enchantment name
value = maxBeforeMergeDisabled("sweeping")
if (value >= 0) return value
}
return DEFAULT_MAX_BEFORE_MERGE_DISABLED return DEFAULT_MAX_BEFORE_MERGE_DISABLED
} }

View file

@ -2,7 +2,6 @@ package xyz.alexcrea.cuanvil.command
import org.bukkit.command.Command import org.bukkit.command.Command
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry
interface CASubCommand { interface CASubCommand {
@ -23,14 +22,4 @@ interface CASubCommand {
fun description(): String fun description(): String
fun allEnchantmentsByName(): Collection<String> {
val names = mutableSetOf<String>()
for (enchantment in CAEnchantmentRegistry.getInstance().values()) {
names.add(enchantment.name)
names.add(enchantment.key.toString())
}
return names
}
} }

View file

@ -17,14 +17,12 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
private val editConfigCommand = EditConfigExecutor() private val editConfigCommand = EditConfigExecutor()
private val helpCommand = HelpExecutor() private val helpCommand = HelpExecutor()
private val commands: ImmutableMap<String, CASubCommand> = ImmutableMap.of( private val commands = ImmutableMap.of(
"gui", editConfigCommand, "gui", editConfigCommand,
"config", editConfigCommand,
"reload", ReloadExecutor(), "reload", ReloadExecutor(),
"diagnostic", DiagnosticExecutor(), "diagnostic", DiagnosticExecutor(),
"debug", DebugToggleExecutor(), "debug", DebugToggleExecutor(),
"help", helpCommand, "help", helpCommand,
"enchant", EnchantExecutor(),
) )
init { init {
@ -43,16 +41,12 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
): Boolean { ): Boolean {
// Find sub command to execute based on the provided command name // Find sub command to execute based on the provided command name
val subcmd: CASubCommand? val subcmd: CASubCommand?
val subcmdStr: String
val newargs: Array<out String> val newargs: Array<out String>
if (args.isEmpty()) { if (args.isEmpty()) {
subcmdStr = "config"
subcmd = editConfigCommand subcmd = editConfigCommand
newargs = args newargs = args
} else { } else {
subcmdStr = args[0].lowercase() subcmd = commands[args[0].lowercase()]
subcmd = commands[subcmdStr]
newargs = args.copyOfRange(1, args.size) newargs = args.copyOfRange(1, args.size)
} }
@ -62,7 +56,7 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
} }
try { try {
return subcmd.executeCommand(sender, cmd, subcmdStr, newargs) return subcmd.executeCommand(sender, cmd, cmdstr, newargs)
} catch (e: Throwable) { } catch (e: Throwable) {
MetricsUtil.trackError(e) MetricsUtil.trackError(e)
sender.sendMessage("§cError running this command") sender.sendMessage("§cError running this command")
@ -80,8 +74,7 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
if (args.size < 2) { if (args.size < 2) {
for ((key, cmd) in commands) { for ((key, cmd) in commands) {
if (!cmd.allowed(sender)) continue if (!cmd.allowed(sender)) continue
if("gui".contentEquals(key)) continue result.add(key)
result.add(key)
} }
} else { } else {
val subcmd = commands[args[0].lowercase()] val subcmd = commands[args[0].lowercase()]
@ -95,11 +88,9 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter {
} }
//assumed all provided tab completed string are lowercase //assumed all provided tab completed string are lowercase
val prefix = args[args.size - 1]
return result.stream() return result.stream()
.filter { it.startsWith(prefix) } .filter { it.startsWith(args[args.size - 1]) }
.sorted() .sorted()
.toList() .toList()
} }
} }

View file

@ -4,26 +4,12 @@ import io.delilaheve.CustomAnvil
import org.bukkit.command.Command import org.bukkit.command.Command
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import org.bukkit.entity.HumanEntity import org.bukkit.entity.HumanEntity
import xyz.alexcrea.cuanvil.api.EnchantmentApi
import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil
import xyz.alexcrea.cuanvil.enchant.CAEnchantment
import xyz.alexcrea.cuanvil.gui.config.MainConfigGui import xyz.alexcrea.cuanvil.gui.config.MainConfigGui
import xyz.alexcrea.cuanvil.gui.config.global.EnchantConfigGui
import xyz.alexcrea.cuanvil.gui.config.global.ItemConfigGui
import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions
import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir
class EditConfigExecutor : CASubCommand { class EditConfigExecutor : CASubCommand {
override fun allowed(sender: CommandSender): Boolean {
return sender.hasPermission(CustomAnvil.editConfigPermission)
}
override fun description(): String {
return "Gui to edit the plugin's config"
}
override fun executeCommand( override fun executeCommand(
sender: CommandSender, sender: CommandSender,
cmd: Command, cmd: Command,
@ -41,81 +27,28 @@ class EditConfigExecutor : CASubCommand {
sender.sendMessage("§eIt is may come in a future version.") sender.sendMessage("§eIt is may come in a future version.")
sender.sendMessage("") sender.sendMessage("")
sender.sendMessage("§eCurrently you need to edit manually the config or copy from another server (spigot or better)") sender.sendMessage("§eCurrently you need to edit manually the config or copy from another server (spigot or better)")
sender.sendMessage("§eThen /ca reload after config file is edited") sender.sendMessage("§eThen /anvilconfigreload after config file is edited")
return false return false
} }
if ("gui".equals(cmdstr, ignoreCase = true)) { MainConfigGui.getInstance().show(sender)
sender.sendMessage("§c/ca gui has been moved to /ca config")
}
if (args.isEmpty())
processOpen(sender)
else when (args[0].lowercase()) {
"open" -> processOpen(sender)
"enchant" -> processEnchant(sender, args)
"item" -> processItem(sender)
else -> sender.sendMessage("Unknown subcommand \"${args[0]}\"")
}
return true return true
} }
private fun processEnchant(sender: HumanEntity, args: Array<out String>) { override fun allowed(sender: CommandSender): Boolean {
val enchantToFilter: Set<CAEnchantment> return sender.hasPermission(CustomAnvil.editConfigPermission)
if (args.size <= 1) {
val item = sender.inventory.itemInMainHand
enchantToFilter = EnchantmentApi.getEnchantments(item).keys
if (enchantToFilter.isEmpty()) {
sender.sendMessage("No enchantment found in the item you are holding")
return
}
} else {
enchantToFilter = HashSet(EnchantmentApi.getByName(args[1].lowercase()))
if (enchantToFilter.isEmpty()) {
sender.sendMessage("No enchantment found with the name \"${args[1]}\"")
return
}
}
EnchantConfigGui(enchantToFilter).show(sender)
} }
private fun processItem(sender: HumanEntity) { override fun tabCompleter(
val item = sender.inventory.itemInMainHand sender: CommandSender,
if (item.isAir) { args: Array<out String>,
sender.sendMessage("Cannot configure the item in hand") list: MutableList<String>
return ) {
}
ItemConfigGui(item.type, item.customType).show(sender)
} }
private fun processOpen(sender: HumanEntity) { override fun description(): String {
MainConfigGui.getInstance().show(sender) return "Gui to edit the plugin's config"
}
// ---------------
// Tab completer
// ---------------
override fun tabCompleter(sender: CommandSender, args: Array<out String>, list: MutableList<String>) {
list.addAll(
when (args.size) {
1 -> listOf("item", "enchant", "open")
2 -> {
when (args[0].lowercase()) {
"enchant" -> allEnchantmentsByName()
else -> listOf()
}
}
else -> listOf()
}
)
} }
} }

View file

@ -1,113 +0,0 @@
package xyz.alexcrea.cuanvil.command
import io.delilaheve.CustomAnvil
import io.delilaheve.util.ConfigOptions
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
import org.bukkit.entity.HumanEntity
import xyz.alexcrea.cuanvil.api.EnchantmentApi
import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir
class EnchantExecutor : CASubCommand {
override fun allowed(sender: CommandSender): Boolean {
return sender.hasPermission(CustomAnvil.giveEnchantmentPermission)
}
override fun description(): String {
return "Allows to set enchantment to holden item"
}
override fun executeCommand(
sender: CommandSender,
cmd: Command,
cmdstr: String,
args: Array<out String>
): Boolean {
if (sender !is HumanEntity) return true
if (!allowed(sender)) {
sender.sendMessage("No permission to execute this command")
return true
}
when (args.size) {
0 -> {
sender.sendMessage("Missing enchantment parameter")
return true
}
1 -> {
sender.sendMessage("Missing level parameter")
return true
}
}
val enchants = EnchantmentApi.getByName(args[0].lowercase())
if (enchants.isEmpty()) {
sender.sendMessage("Enchantment not found: ${args[0]}")
return true
}
val enchant = enchants.iterator().next()
val level = args[1].toIntOrNull()?.coerceIn(0, ConfigOptions.ENCHANT_LIMIT)
if (level == null) {
sender.sendMessage("Invalid number: ${args[1]}")
return true
}
val inHand = sender.inventory.itemInMainHand
if (inHand.isAir) {
sender.sendMessage("Cannot enchant this item")
return true
}
if (level == 0) {
enchant.removeFrom(inHand)
sender.sendMessage("${enchant.prettyName} removed")
} else {
enchant.addEnchantmentUnsafe(inHand, level)
sender.sendMessage("${enchant.prettyName} set to level $level")
}
return true
}
override fun tabCompleter(sender: CommandSender, args: Array<out String>, list: MutableList<String>) {
if (sender !is HumanEntity) return
list.addAll(
when (args.size) {
1 -> allEnchantmentsByName()
2 -> findEnchantmentLevels(sender, args[0])
else -> listOf()
}
)
}
private fun findEnchantmentLevels(
sender: HumanEntity,
name: String
): Collection<String> {
val enchants = EnchantmentApi.getByName(name.lowercase())
if (enchants.isEmpty()) return listOf()
val enchant = enchants.iterator().next()
val limit = ConfigOptions.enchantLimit(enchant)
val result = mutableListOf<String>()
for (i in 1 until limit + 1) {
result.add(i.toString())
}
val inHand = sender.inventory.itemInMainHand
if (enchant.isEnchantmentPresent(inHand))
result.add("0")
return result
}
}

View file

@ -38,6 +38,13 @@ class EnchantConflictManager {
// Default name for a joining group // Default name for a joining group
const val DEFAULT_GROUP_NAME = "joinedGroup" const val DEFAULT_GROUP_NAME = "joinedGroup"
// 1.20.5 compatibility TODO better update system
private val SWEEPING_EDGE_ENCHANT = Collections.singletonList<CAEnchantment>(
CAEnchantment.getByKey(NamespacedKey.minecraft("sweeping_edge"))
?: CAEnchantment.getByKey(Enchantment.SWEEPING_EDGE.key)
)
} }
lateinit var conflictList: ArrayList<EnchantConflictGroup> lateinit var conflictList: ArrayList<EnchantConflictGroup>
@ -164,6 +171,14 @@ class EnchantConflictManager {
} }
// Temporary solution for 1.20.5
when (enchantName) {
"minecraft:sweeping", "sweeping",
"minecraft:sweeping_edge", "sweeping_edge" -> {
return SWEEPING_EDGE_ENCHANT
}
}
return CAEnchantment.getByName(enchantName) return CAEnchantment.getByName(enchantName)
} }

View file

@ -5,7 +5,6 @@ import org.bukkit.NamespacedKey
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.DependencyManager
import xyz.alexcrea.cuanvil.dependency.plugins.EcoItemDependencyUtil import xyz.alexcrea.cuanvil.dependency.plugins.EcoItemDependencyUtil
import javax.annotation.Nullable
object MaterialUtil { object MaterialUtil {
@ -35,13 +34,11 @@ object MaterialUtil {
return this.type.key return this.type.key
} }
@Nullable
private fun bukkitMaterialFromKey(key: NamespacedKey): Material? { private fun bukkitMaterialFromKey(key: NamespacedKey): Material? {
//TODO on paper only transition Registry.MATERIAL.get(key) //TODO on paper only transition Registry.MATERIAL.get(key)
return Material.matchMaterial(key.toString()) return Material.matchMaterial(key.toString())
} }
@Nullable
fun getMatFromKey(key: NamespacedKey): Material? { fun getMatFromKey(key: NamespacedKey): Material? {
if(DependencyManager.ecoEnchantCompatibility != null) { if(DependencyManager.ecoEnchantCompatibility != null) {
val result = EcoItemDependencyUtil.ecoItemMaterialFromKey(key) val result = EcoItemDependencyUtil.ecoItemMaterialFromKey(key)

View file

@ -1,8 +1,6 @@
package xyz.alexcrea.cuanvil.util package xyz.alexcrea.cuanvil.util
import org.bukkit.NamespacedKey
import org.bukkit.configuration.ConfigurationSection import org.bukkit.configuration.ConfigurationSection
import org.bukkit.configuration.file.FileConfiguration
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.config.ConfigHolder
import xyz.alexcrea.cuanvil.util.MaterialUtil.customType import xyz.alexcrea.cuanvil.util.MaterialUtil.customType
@ -13,7 +11,7 @@ object UnitRepairUtil {
private const val DEFAULT_DEFAULT_UNIT_REPAIR = 0.25 private const val DEFAULT_DEFAULT_UNIT_REPAIR = 0.25
// Path to user default unit repair value // Path to user default unit repair value
public const val UNIT_REPAIR_DEFAULT_PATH = "default_repair_amount" private const val UNIT_REPAIR_DEFAULT_PATH = "default_repair_amount"
/** /**
* Get the % of repair by unit [other] will do to this [ItemStack]. * Get the % of repair by unit [other] will do to this [ItemStack].
@ -24,56 +22,40 @@ object UnitRepairUtil {
): Double? { ): Double? {
if (other == null) return null if (other == null) return null
val config = ConfigHolder.UNIT_REPAIR_HOLDER.config val config = ConfigHolder.UNIT_REPAIR_HOLDER.config
// Get configuration section if exist
val otherName = other.customType.key.lowercase()
var section = config.getConfigurationSection(otherName)
if (section == null) {
section = config.getConfigurationSection(otherName.uppercase())
if (section == null) return null
val result = findRawRepairValue(this, other, config) ?: return null }
// Get repair amount
var userDefault = config.getDouble(UNIT_REPAIR_DEFAULT_PATH, DEFAULT_DEFAULT_UNIT_REPAIR)
if (userDefault <= 0) {
userDefault = DEFAULT_DEFAULT_UNIT_REPAIR
}
if(result > 0) return result return getRepairAmount(this, section, userDefault)
// Get default
val userDefault = config.getDouble(UNIT_REPAIR_DEFAULT_PATH, DEFAULT_DEFAULT_UNIT_REPAIR)
if (userDefault <= 0)
return DEFAULT_DEFAULT_UNIT_REPAIR
return userDefault
} }
private fun findRawRepairValue( /**
self: ItemStack, * Get the item % repaired by this configuration section of a unit repair.
other: ItemStack, * null if not found.
config: FileConfiguration * If value is set to less than or equal to 0 then it will be set to default
): Double? { */
val material = other.customType private fun getRepairAmount(item: ItemStack, section: ConfigurationSection, default: Double): Double? {
val selfType = self.customType val itemName = item.customType.key.lowercase()
val repairValue = if (section.isDouble(itemName)) {
val result = checkSection(config, material.toString(), selfType) section.getDouble(itemName)
if (result != null) return result } else if (section.isDouble(itemName.uppercase())) {
section.getDouble(itemName.uppercase())
return checkSection(config, material.key, selfType) } else {
} return null
}
fun findRawRepairValue( if (repairValue <= 0)
self: NamespacedKey, return default
other: NamespacedKey, return repairValue
config: FileConfiguration
): Double? {
val result = checkSection(config, other.toString(), self)
if (result != null) return result
return checkSection(config, other.key, self)
}
fun checkSection(
config: FileConfiguration,
path: String,
material: NamespacedKey
): Double? {
val section = config.getConfigurationSection(path) ?: return null
if (section.isDouble(material.toString()))
return section.getDouble(material.toString())
if (section.isDouble(material.key))
return section.getDouble(material.key)
return null
} }
} }

View file

@ -5,11 +5,16 @@ import io.delilaheve.util.ConfigOptions
object AnvilUseTypeUtil { object AnvilUseTypeUtil {
/* /*
By kotlin not having static function outside of companion object I need to do another util class only for 1 function: By stupidity of kotlin not allowing static function outside of companion object I need to do another util class only for 1 function:
Companion object on enum class seems to get initialized AFTER the enum itself Companion object on enum class seems to get initialized AFTER the enum itself
that mean. if you want to call a static function on enum construction YOU CAN'T. you need to do this stupid thing, that mean. if you want to call a static function on the enum class itself YOU CAN'T. you need to do this stupid thing
or you can make a stupid top level function or object that at least as bad as this or you can make a stupid top level function OR object that even worse because of global scope pollution
I mean, this is still an unnecessary class that should not exist but as a class is better than a random function in my opinion (btw was gpt ""solution"". fortunately I do not "vibe code" so I do what I know instead of stupid AI solution & code)
I mean, this is still global scope pollution bc of a USELESS class that SHOULD not exist but as a class is better than a random *ss function
sorry for the rent but this made me frustrated
Note: I still like a lot of part of kotlin compared to java but this part is one that I hate
*/ */
/** /**
* Get config path for normal anvil use * Get config path for normal anvil use

View file

@ -22,7 +22,6 @@ import xyz.alexcrea.cuanvil.dependency.economy.EconomyManager
import xyz.alexcrea.cuanvil.group.ConflictType import xyz.alexcrea.cuanvil.group.ConflictType
import xyz.alexcrea.cuanvil.util.AnvilTitleUtil import xyz.alexcrea.cuanvil.util.AnvilTitleUtil
import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil
import kotlin.math.sqrt
@Suppress("UnstableApiUsage") @Suppress("UnstableApiUsage")
object AnvilXpUtil { object AnvilXpUtil {
@ -35,9 +34,8 @@ object AnvilXpUtil {
fun setAnvilResult( fun setAnvilResult(
view: AnvilView, view: AnvilView,
player: Player, player: Player,
result: AnvilResult result: AnvilResult) {
) { if(result.item == null) {
if (result.item == null) {
onNoResult(player, view) onNoResult(player, view)
return return
} }
@ -240,8 +238,7 @@ object AnvilXpUtil {
fun getRightValues(left: ItemStack, right: ItemStack, result: ItemStack, cost: AnvilCost) { fun getRightValues(left: ItemStack, right: ItemStack, result: ItemStack, cost: AnvilCost) {
// Calculate right value and illegal enchant penalty // Calculate right value and illegal enchant penalty
val isToBook = left.isEnchantedBook() val rightIsFormBook = right.isEnchantedBook()
val isFromBook = right.isEnchantedBook()
val rightEnchs = EnchantmentApi.getEnchantments(right) val rightEnchs = EnchantmentApi.getEnchantments(right)
val resultEnchs = EnchantmentApi.getEnchantments(result) val resultEnchs = EnchantmentApi.getEnchantments(result)
val resultEnchsKeys = HashMap(resultEnchs) val resultEnchsKeys = HashMap(resultEnchs)
@ -269,21 +266,22 @@ object AnvilXpUtil {
// We know "enchantment.key in resultEnchs" true // We know "enchantment.key in resultEnchs" true
val resultLevel = resultEnchs[enchantment.key]!! val resultLevel = resultEnchs[enchantment.key]!!
val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, isFromBook, isToBook) val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, rightIsFormBook)
val value = resultLevel * enchantmentMultiplier val value = resultLevel * enchantmentMultiplier
CustomAnvil.log("Value for sacrifice item ${enchantment.key.enchantmentName} level ${enchantment.value} is $value ($resultLevel * $enchantmentMultiplier)") CustomAnvil.log("Value for sacrifice item ${enchantment.key.enchantmentName} level ${enchantment.value} is $value ($resultLevel * $enchantmentMultiplier)")
rightValue += value rightValue += value
} }
if (ConfigOptions.includeLeftEnchantmentForCost) { if(ConfigOptions.includeLeftEnchantmentForCost) {
val leftIsFormBook = left.isEnchantedBook()
val leftEnchs = EnchantmentApi.getEnchantments(left) val leftEnchs = EnchantmentApi.getEnchantments(left)
for (enchantment in leftEnchs) { for (enchantment in leftEnchs) {
// Do not process enchantment that are present on the sacrifice // Do not process enchantment that are present on the sacrifice
if (rightEnchs.contains(enchantment.key)) continue if(rightEnchs.contains(enchantment.key)) continue
val resultLevel = resultEnchs.getOrDefault(enchantment.key, 0) val resultLevel = resultEnchs.getOrDefault(enchantment.key, 0)
val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, isFromBook, isToBook) val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, leftIsFormBook)
val value = resultLevel * enchantmentMultiplier val value = resultLevel * enchantmentMultiplier
CustomAnvil.log("Value for left item ${enchantment.key.enchantmentName} level ${enchantment.value} is $value ($resultLevel * $enchantmentMultiplier)") CustomAnvil.log("Value for left item ${enchantment.key.enchantmentName} level ${enchantment.value} is $value ($resultLevel * $enchantmentMultiplier)")
leftValue += value leftValue += value
@ -306,15 +304,15 @@ object AnvilXpUtil {
*/ */
fun calculateLevelForXp(xp: Int): Int { fun calculateLevelForXp(xp: Int): Int {
return when { return when {
xp <= 352 -> (sqrt((xp + 9).toDouble()) - 3).toInt() xp <= 352 -> (Math.sqrt((xp + 9).toDouble()) - 3).toInt()
xp <= 1507 -> { xp <= 1507 -> {
val inner = (2.0 / 5.0) * (xp - 7839.0 / 40.0) val inner = (2.0 / 5.0) * (xp - 7839.0 / 40.0)
(81.0 / 10.0 + sqrt(inner)).toInt() (81.0 / 10.0 + Math.sqrt(inner)).toInt()
} }
else -> { else -> {
val inner = (2.0 / 9.0) * (xp - 54215.0 / 72.0) val inner = (2.0 / 9.0) * (xp - 54215.0 / 72.0)
(325.0 / 18.0 + sqrt(inner)).toInt() (325.0 / 18.0 + Math.sqrt(inner)).toInt()
} }
} }
} }

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit most of these config. # It is recommended that you use /configanvil to edit most of these config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# What service of metric should custom anvil use # What service of metric should custom anvil use

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# material conflicts # material conflicts

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Please note this config use spigot material names. # Please note this config use spigot material names.

View file

@ -31,9 +31,6 @@ permissions:
ca.command.diagnostic: ca.command.diagnostic:
default: op default: op
description: Get debug information about the plugin and server description: Get debug information about the plugin and server
ca.command.enchantment:
default: op
description: Allows to set enchantment to holden item
ca.config.edit: ca.config.edit:
default: op default: op
description: Allow administrator to edit the plugin's config in game description: Allow administrator to edit the plugin's config in game

View file

@ -1,6 +1,6 @@
# #
# It is recommended that you use /configanvil to edit theses config. # It is recommended that you use /configanvil to edit theses config.
# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! # You can still manually edit here if you like to. but if you do, don't forget to /anvilconfigreload after you changes !
# #
# Unit repair configuration # Unit repair configuration

View file

@ -49,8 +49,8 @@ public class DefaultConfigTests extends SharedCustomAnvilTest {
CAEnchantment enchantment = CAEnchantmentRegistry.getInstance().getByKey(key); CAEnchantment enchantment = CAEnchantmentRegistry.getInstance().getByKey(key);
Assertions.assertNotNull(enchantment, "Enchantment was somehow not found"); Assertions.assertNotNull(enchantment, "Enchantment was somehow not found");
int itemValue = ConfigOptions.INSTANCE.enchantmentValue(enchantment, false, false); int itemValue = ConfigOptions.INSTANCE.enchantmentValue(enchantment, false);
int bookValue = ConfigOptions.INSTANCE.enchantmentValue(enchantment, false, true); int bookValue = ConfigOptions.INSTANCE.enchantmentValue(enchantment, true);
EnchantmentRarity rarity = enchantment.defaultRarity(); EnchantmentRarity rarity = enchantment.defaultRarity();