Added a GenerateLore event, which fires when lore is being generated for an item

This commit is contained in:
ASangarin 2022-06-13 22:48:21 +02:00
parent b077bdcd58
commit 2b0388adcf
3 changed files with 267 additions and 191 deletions

View File

@ -0,0 +1,72 @@
package net.Indyuce.mmoitems.api.event;
import net.Indyuce.mmoitems.api.item.build.LoreBuilder;
import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.util.List;
public class GenerateLoreEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final MMOItem item;
private final List<String> lore, parsed;
private final LoreBuilder builder;
public GenerateLoreEvent(MMOItem item, LoreBuilder builder, List<String> lore, List<String> parsed) {
this.item = item;
this.lore = lore;
this.parsed = parsed;
this.builder = builder;
}
/**
* @return The MMOItem the lore is being generated for
*/
public MMOItem getItem() {
return item;
}
/**
* @return The LoreBuilder used to build this lore.
*/
public LoreBuilder getBuilder() {
return builder;
}
/**
* @return The list of pre-placeholder lore (before any placeholders have been parsed)
*/
public List<String> getLore() {
return lore;
}
/**
* @return The list of parsed lore (after all placeholders have been parsed)
*/
public List<String> getParsedLore() {
return parsed;
}
/**
* Sets the final lore of the item.
* <p>
* This sets the parsed lore, so any future calls of
* getParsedLore() will return the new list.
*
* @param lore The new lore of the item
*/
public void setFinalLore(List<String> lore) {
this.parsed.clear();
this.parsed.addAll(lore);
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -4,15 +4,14 @@ import com.google.gson.JsonArray;
import io.lumine.mythic.lib.api.item.ItemTag;
import io.lumine.mythic.lib.api.item.NBTItem;
import io.lumine.mythic.lib.api.util.LegacyComponent;
import io.lumine.mythic.lib.api.util.ui.FriendlyFeedbackProvider;
import io.lumine.mythic.utils.adventure.text.Component;
import net.Indyuce.mmoitems.ItemStats;
import net.Indyuce.mmoitems.MMOItems;
import net.Indyuce.mmoitems.api.Type;
import net.Indyuce.mmoitems.api.event.GenerateLoreEvent;
import net.Indyuce.mmoitems.api.event.ItemBuildEvent;
import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem;
import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate;
import net.Indyuce.mmoitems.api.util.message.FFPMMOItems;
import net.Indyuce.mmoitems.stat.DisplayName;
import net.Indyuce.mmoitems.stat.Enchants;
import net.Indyuce.mmoitems.stat.data.MaterialData;
@ -39,240 +38,241 @@ import java.util.UUID;
import java.util.logging.Level;
public class ItemStackBuilder {
@NotNull
private final MMOItem mmoitem;
@NotNull
private final MMOItem mmoitem;
private final ItemStack item;
private final ItemMeta meta;
private final LoreBuilder lore;
private final List<ItemTag> tags = new ArrayList<>();
private final ItemStack item;
private final ItemMeta meta;
private final LoreBuilder lore;
private final List<ItemTag> tags = new ArrayList<>();
private static final AttributeModifier fakeModifier = new AttributeModifier(
UUID.fromString("87851e28-af12-43f6-898e-c62bde6bd0ec"), "mmoitemsDecoy", 0, Operation.ADD_NUMBER);
private static final AttributeModifier fakeModifier = new AttributeModifier(UUID.fromString("87851e28-af12-43f6-898e-c62bde6bd0ec"),
"mmoitemsDecoy", 0, Operation.ADD_NUMBER);
/**
* Used to build an MMOItem into an ItemStack.
*
* @param mmoitem The mmoitem you want to build
*/
public ItemStackBuilder(@NotNull MMOItem mmoitem) {
/**
* Used to build an MMOItem into an ItemStack.
*
* @param mmoitem The mmoitem you want to build
*/
public ItemStackBuilder(@NotNull MMOItem mmoitem) {
// Reference to source MMOItem
this.mmoitem = mmoitem;
// Reference to source MMOItem
this.mmoitem = mmoitem;
// Generates a new ItemStack of the specified material (Specified in the Material stat, or a DIAMOND_SWORD if missing).
item = new ItemStack(mmoitem.hasData(ItemStats.MATERIAL) ?
((MaterialData) mmoitem.getData(ItemStats.MATERIAL)).getMaterial()
: Material.DIAMOND_SWORD);
// Generates a new ItemStack of the specified material (Specified in the Material stat, or a DIAMOND_SWORD if missing).
item = new ItemStack(
mmoitem.hasData(ItemStats.MATERIAL) ? ((MaterialData) mmoitem.getData(ItemStats.MATERIAL)).getMaterial() : Material.DIAMOND_SWORD);
// Gets a lore builder, which will be used to apply the chosen lore format (Choose with the lore format stat, or the default one if unspecified)
lore = new LoreBuilder(mmoitem.hasData(ItemStats.LORE_FORMAT)
? MMOItems.plugin.getFormats().getFormat(mmoitem.getData(ItemStats.LORE_FORMAT).toString(), mmoitem.getType().getLoreFormat())
: MMOItems.plugin.getFormats().getFormat(mmoitem.getType().getLoreFormat()));
// Gets a lore builder, which will be used to apply the chosen lore format (Choose with the lore format stat, or the default one if unspecified)
lore = new LoreBuilder(mmoitem.hasData(ItemStats.LORE_FORMAT) ? MMOItems.plugin.getFormats()
.getFormat(mmoitem.getData(ItemStats.LORE_FORMAT).toString(), mmoitem.getType().getLoreFormat()) : MMOItems.plugin.getFormats()
.getFormat(mmoitem.getType().getLoreFormat()));
// Gets the meta, and hides attributes
meta = item.getItemMeta();
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
// Gets the meta, and hides attributes
meta = item.getItemMeta();
//noinspection ConstantConditions
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
// Store the internal TYPE-ID Information (not stats, so it must be done manually here)
tags.add(new ItemTag("MMOITEMS_ITEM_TYPE", mmoitem.getType().getId()));
tags.add(new ItemTag("MMOITEMS_ITEM_ID", mmoitem.getId()));
// Store the internal TYPE-ID Information (not stats, so it must be done manually here)
tags.add(new ItemTag("MMOITEMS_ITEM_TYPE", mmoitem.getType().getId()));
tags.add(new ItemTag("MMOITEMS_ITEM_ID", mmoitem.getId()));
// And a last technical tag for updating items
if (MMOItems.INTERNAL_REVISION_ID > 1)
tags.add(new ItemTag("MMOITEMS_INTERNAL_REVISION_ID", MMOItems.INTERNAL_REVISION_ID));
}
// And a last technical tag for updating items
if (MMOItems.INTERNAL_REVISION_ID > 1) tags.add(new ItemTag("MMOITEMS_INTERNAL_REVISION_ID", MMOItems.INTERNAL_REVISION_ID));
}
public LoreBuilder getLore() {
return lore;
}
public LoreBuilder getLore() {
return lore;
}
@NotNull
public MMOItem getMMOItem() {
return mmoitem;
}
@NotNull
public MMOItem getMMOItem() {
return mmoitem;
}
/**
* @return Does NOT return the built item stack. It returns only returns the
* default item stack with material applied. Built item stack is given
* by build(). This method should only be used to check if the item is
* of a specific material (like the Shield Pattern stat which checks if
* the item is a shield)
*/
public ItemStack getItemStack() {
return item;
}
/**
* @return Does NOT return the built item stack. It returns only returns the
* default item stack with material applied. Built item stack is given
* by build(). This method should only be used to check if the item is
* of a specific material (like the Shield Pattern stat which checks if
* the item is a shield)
*/
public ItemStack getItemStack() {
return item;
}
public ItemMeta getMeta() {
return meta;
}
public ItemMeta getMeta() {
return meta;
}
public void addItemTag(List<ItemTag> newTags) {
tags.addAll(newTags);
}
public void addItemTag(List<ItemTag> newTags) {
tags.addAll(newTags);
}
public void addItemTag(ItemTag... itemTags) {
tags.addAll(Arrays.asList(itemTags));
}
public void addItemTag(ItemTag... itemTags) {
tags.addAll(Arrays.asList(itemTags));
}
public static final String history_keyword = "HSTRY_";
public static final String history_keyword = "HSTRY_";
/**
* @return Returns built NBTItem with applied tags and lore
*/
public NBTItem buildNBT() {
return buildNBT(false);
}
/**
* @return Returns built NBTItem with applied tags and lore
*/
public NBTItem buildNBT() {
return buildNBT(false);
}
/**
* @param forDisplay Should this item's lore display potential stats
* (like RNG ranges before rolling) rather than the
* stats it will have?
* @return Returns built NBTItem with applied tags and lore
*/
public NBTItem buildNBT(boolean forDisplay) {
// Clone as to not conflict in any way
MMOItem builtMMOItem = mmoitem.clone();
//GEM//MMOItems.log("\u00a7e+ \u00a77Building \u00a7c" + mmoitem.getType().getName() + " " + mmoitem.getId() + "\u00a77 (Size \u00a7e" + mmoitem.getStatHistories().size() + "\u00a77 Historic)");
/**
* @param forDisplay Should this item's lore display potential stats
* (like RNG ranges before rolling) rather than the
* stats it will have?
* @return Returns built NBTItem with applied tags and lore
*/
public NBTItem buildNBT(boolean forDisplay) {
// Clone as to not conflict in any way
MMOItem builtMMOItem = mmoitem.clone();
//GEM//MMOItems.log("\u00a7e+ \u00a77Building \u00a7c" + mmoitem.getType().getName() + " " + mmoitem.getId() + "\u00a77 (Size \u00a7e" + mmoitem.getStatHistories().size() + "\u00a77 Historic)");
/*
* As an assumption for several enchantment recognition operations,
* Enchantment data must never be clear and lack history. This is
* the basis for when an item is 'old'
*/
if (!builtMMOItem.hasData(ItemStats.ENCHANTS)) {
builtMMOItem.setData(ItemStats.ENCHANTS, ItemStats.ENCHANTS.getClearStatData());
}
//GEM// else {MMOItems.log("\u00a73 -?- \u00a77Apparently found enchantment data \u00a7b" + (mmoitem.getData(ItemStats.ENCHANTS) == null ? "null" : ((EnchantListData) mmoitem.getData(ItemStats.ENCHANTS)).getEnchants().size())); }
/*
* As an assumption for several enchantment recognition operations,
* Enchantment data must never be clear and lack history. This is
* the basis for when an item is 'old'
*/
if (!builtMMOItem.hasData(ItemStats.ENCHANTS)) {
builtMMOItem.setData(ItemStats.ENCHANTS, ItemStats.ENCHANTS.getClearStatData());
}
//GEM// else {MMOItems.log("\u00a73 -?- \u00a77Apparently found enchantment data \u00a7b" + (mmoitem.getData(ItemStats.ENCHANTS) == null ? "null" : ((EnchantListData) mmoitem.getData(ItemStats.ENCHANTS)).getEnchants().size())); }
// For every stat within this item
for (ItemStat stat : builtMMOItem.getStats())
// For every stat within this item
for (ItemStat stat : builtMMOItem.getStats())
// Attempt to add
try {
// Attempt to add
try {
//GEM//MMOItems.log("\u00a7e -+- \u00a77Applying \u00a76" + stat.getNBTPath());
//GEM//MMOItems.log("\u00a7e -+- \u00a77Applying \u00a76" + stat.getNBTPath());
// Does the item have any stat history regarding thay?
StatHistory s = builtMMOItem.getStatHistory(stat);
int l = mmoitem.getUpgradeLevel();
// Does the item have any stat history regarding thay?
StatHistory s = builtMMOItem.getStatHistory(stat);
int l = mmoitem.getUpgradeLevel();
// Found it?
if (s != null) {
//GEM//MMOItems.log("\u00a7a -+- \u00a77History exists...");
//GEM//s.log();
// Found it?
if (s != null) {
//GEM//MMOItems.log("\u00a7a -+- \u00a77History exists...");
//GEM//s.log();
// Recalculate
//HSY//MMOItems.log(" \u00a73-\u00a7a- \u00a77ItemStack Building Recalculation \u00a73-\u00a7a-\u00a73-\u00a7a-\u00a73-\u00a7a-\u00a73-\u00a7a-");
builtMMOItem.setData(stat, s.recalculate(l));
// Recalculate
//HSY//MMOItems.log(" \u00a73-\u00a7a- \u00a77ItemStack Building Recalculation \u00a73-\u00a7a-\u00a73-\u00a7a-\u00a73-\u00a7a-\u00a73-\u00a7a-");
builtMMOItem.setData(stat, s.recalculate(l));
// Add to NBT, if the gemstones were not purged
if ((!s.isClear() || stat instanceof Enchants || stat instanceof DisplayName)) {
// Add to NBT, if the gemstones were not purged
if ((!s.isClear() || stat instanceof Enchants || stat instanceof DisplayName)) {
//GEM//MMOItems.log("\u00a7a -+- \u00a77Recording History");
addItemTag(new ItemTag(history_keyword + stat.getId(), s.toNBTString()));
}
}
//GEM//MMOItems.log("\u00a7a -+- \u00a77Recording History");
addItemTag(new ItemTag(history_keyword + stat.getId(), s.toNBTString()));
}
}
if (forDisplay && stat instanceof Previewable) {
if (forDisplay && stat instanceof Previewable) {
// Get Template
MMOItemTemplate template = MMOItems.plugin.getTemplates().getTemplate(builtMMOItem.getType(), builtMMOItem.getId());
if (template == null) { throw new IllegalArgumentException("MMOItem $r" + builtMMOItem.getType().getId() + " " + builtMMOItem.getId() + "$b doesn't exist."); }
// Get Template
MMOItemTemplate template = MMOItems.plugin.getTemplates().getTemplate(builtMMOItem.getType(), builtMMOItem.getId());
if (template == null) {
throw new IllegalArgumentException(
"MMOItem $r" + builtMMOItem.getType().getId() + " " + builtMMOItem.getId() + "$b doesn't exist.");
}
// Make necessary lore changes
((Previewable) stat).whenPreviewed(this, builtMMOItem.getData(stat), template.getBaseItemData().get(stat));
// Make necessary lore changes
((Previewable) stat).whenPreviewed(this, builtMMOItem.getData(stat), template.getBaseItemData().get(stat));
} else {
} else {
// Make necessary lore changes
stat.whenApplied(this, builtMMOItem.getData(stat));
}
// Make necessary lore changes
stat.whenApplied(this, builtMMOItem.getData(stat));
}
// Something went wrong...
} catch (IllegalArgumentException | NullPointerException exception) {
// Something went wrong...
} catch (IllegalArgumentException | NullPointerException exception) {
// That
MMOItems.print(Level.WARNING, "An error occurred while trying to generate item '$f{0}$b' with stat '$f{1}$b': {2}",
"ItemStackBuilder", builtMMOItem.getId(), stat.getId(), exception.getMessage());
}
// That
MMOItems.print(Level.WARNING, "An error occurred while trying to generate item '$f{0}$b' with stat '$f{1}$b': {2}",
"ItemStackBuilder", builtMMOItem.getId(), stat.getId(), exception.getMessage());
}
// Display gem stone lore hint thing
if (builtMMOItem.getType() == Type.GEM_STONE)
lore.insert("gem-stone-lore", ItemStat.translate("gem-stone-lore"));
// Display gem stone lore hint thing
if (builtMMOItem.getType() == Type.GEM_STONE) lore.insert("gem-stone-lore", ItemStat.translate("gem-stone-lore"));
// Display item type
lore.insert("item-type",
ItemStat.translate("item-type").replace("#",
builtMMOItem.getStats().contains(ItemStats.DISPLAYED_TYPE)
? builtMMOItem.getData(ItemStats.DISPLAYED_TYPE).toString()
: builtMMOItem.getType().getName()));
// Display item type
lore.insert("item-type", ItemStat.translate("item-type").replace("#",
builtMMOItem.getStats().contains(ItemStats.DISPLAYED_TYPE) ? builtMMOItem.getData(ItemStats.DISPLAYED_TYPE)
.toString() : builtMMOItem.getType().getName()));
// Calculate extra item lore with placeholders
if (builtMMOItem.hasData(ItemStats.LORE)) {
List<String> parsed = new ArrayList<>();
((StringListData) builtMMOItem.getData(ItemStats.LORE)).getList()
.forEach(str -> parsed.add(lore.applySpecialPlaceholders(str)));
lore.insert("lore", parsed);
}
// Calculate extra item lore with placeholders
if (builtMMOItem.hasData(ItemStats.LORE)) {
List<String> parsed = new ArrayList<>();
((StringListData) builtMMOItem.getData(ItemStats.LORE)).getList().forEach(str -> parsed.add(lore.applySpecialPlaceholders(str)));
lore.insert("lore", parsed);
}
// Calculate and apply item lore
List<String> builtLore = lore.build();
meta.setLore(builtLore);
// Calculate and apply item lore
List<String> unparsedLore = lore.getLore();
List<String> parsedLore = lore.build();
/*
* Save dynamic lore for later calculations. Not used anymore, but
* kept in case we need to roll back the lore update change.
*/
JsonArray array = new JsonArray();
builtLore.forEach(str -> array.add(str));
if (array.size() != 0)
tags.add(new ItemTag("MMOITEMS_DYNAMIC_LORE", array.toString()));
GenerateLoreEvent event = new GenerateLoreEvent(builtMMOItem, lore, parsedLore, unparsedLore);
Bukkit.getPluginManager().callEvent(event);
meta.setLore(event.getParsedLore());
/*
* This tag is added to entirely override default vanilla item attribute
* modifiers, this way armor gives no ARMOR or ARMOR TOUGHNESS to the holder.
* Since 4.7 attributes are handled via custom calculations
*/
meta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, fakeModifier);
/*
* Save dynamic lore for later calculations. Not used anymore, but
* kept in case we need to roll back the lore update change.
*/
JsonArray array = new JsonArray();
event.getParsedLore().forEach(array::add);
if (array.size() != 0) tags.add(new ItemTag("MMOITEMS_DYNAMIC_LORE", array.toString()));
item.setItemMeta(meta);
NBTItem nbtItem = NBTItem.get(item);
/*
* This tag is added to entirely override default vanilla item attribute
* modifiers, this way armor gives no ARMOR or ARMOR TOUGHNESS to the holder.
* Since 4.7 attributes are handled via custom calculations
*/
meta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, fakeModifier);
// Apply item display name using Components for colors
if (mmoitem.hasData(ItemStats.NAME) && meta.hasDisplayName())
nbtItem.setDisplayNameComponent(LegacyComponent.parse(meta.getDisplayName()));
item.setItemMeta(meta);
NBTItem nbtItem = NBTItem.get(item);
if (meta.hasLore()) {
List<Component> componentLore = new LinkedList<>();
meta.getLore().forEach(line -> componentLore.add(LegacyComponent.simpleParse(line)));
nbtItem.setLoreComponents(componentLore);
}
// Apply item display name using Components for colors
if (mmoitem.hasData(ItemStats.NAME) && meta.hasDisplayName()) nbtItem.setDisplayNameComponent(LegacyComponent.parse(meta.getDisplayName()));
return nbtItem.addTag(tags);
}
if (meta.hasLore()) {
List<Component> componentLore = new LinkedList<>();
//noinspection ConstantConditions
meta.getLore().forEach(line -> componentLore.add(LegacyComponent.simpleParse(line)));
nbtItem.setLoreComponents(componentLore);
}
/**
* @return Builds the item
*/
@Nullable
public ItemStack build() {
ItemBuildEvent event = new ItemBuildEvent(buildNBT().toItem());
Bukkit.getServer().getPluginManager().callEvent(event);
return event.getItemStack();
}
return nbtItem.addTag(tags);
}
/**
* Builds the item without calling a build event
*/
public ItemStack buildSilently() {
return buildNBT().toItem();
}
/**
* @return Builds the item
*/
@Nullable
public ItemStack build() {
ItemBuildEvent event = new ItemBuildEvent(buildNBT().toItem());
Bukkit.getServer().getPluginManager().callEvent(event);
return event.getItemStack();
}
/**
* @return Builds the item
*/
public ItemStack build(boolean forDisplay) {
return buildNBT(forDisplay).toItem();
}
/**
* Builds the item without calling a build event
*/
public ItemStack buildSilently() {
return buildNBT().toItem();
}
/**
* @return Builds the item
*/
public ItemStack build(boolean forDisplay) {
return buildNBT(forDisplay).toItem();
}
}

View File

@ -202,4 +202,8 @@ public class LoreBuilder {
private boolean isBar(String str) {
return str.startsWith("{bar}") || str.startsWith("{sbar}");
}
public List<String> getLore() {
return lore;
}
}