From d9b63038ddfc5efe9a005556aa25df46dda30ebc Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 19 Feb 2026 23:32:50 -0300 Subject: [PATCH 01/51] Ability Conditions overhaul WIP --- .../npcs/controllers/AbilityController.java | 43 ++-- .../data/ability/ConditionField.java | 196 ++++++++++++++++++ .../data/ability/IAbilityCondition.java | 94 +++++++++ 3 files changed, 315 insertions(+), 18 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 87b4c235f..f706ff585 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -1,15 +1,6 @@ package kamkeel.npcs.controllers; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityPhase; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; -import kamkeel.npcs.controllers.data.ability.ChainedAbility; -import kamkeel.npcs.controllers.data.ability.IAbilityAction; -import kamkeel.npcs.controllers.data.ability.IAbilityExtender; -import kamkeel.npcs.controllers.data.ability.IAbilityFieldProvider; -import kamkeel.npcs.controllers.data.ability.IEffectAction; -import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; -import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.*; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; @@ -43,14 +34,7 @@ import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.util.NBTJsonUtil; import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -70,6 +54,7 @@ public class AbilityController implements IAbilityHandler { private final List fieldProviders = new ArrayList<>(); private final List chainedFieldProviders = new ArrayList<>(); private final List extenders = new ArrayList<>(); + private final Map> conditionTypes = new HashMap<>(); private final List> flightCheckers = new ArrayList<>(); // ── Legacy Migration ───────────────────────────────────────────────────── @@ -90,6 +75,7 @@ public class AbilityController implements IAbilityHandler { public AbilityController() { registerBuiltinTypes(); + registerBuiltinConditionTypes(); } // ═══════════════════════════════════════════════════════════════════════════ @@ -160,6 +146,10 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:slicer", AbilitySlicer::new); } + private void registerBuiltinConditionTypes() { + registerCondition(IAbilityCondition.ConditionHPAbove::new); + } + // ═══════════════════════════════════════════════════════════════════════════ // BUILT-IN ABILITIES // ═══════════════════════════════════════════════════════════════════════════ @@ -890,6 +880,23 @@ public class AbilityController implements IAbilityHandler { return extenders; } + public void registerCondition(Supplier conditionFactory) { + IAbilityCondition temp = conditionFactory.get(); + String typeId = temp.getTypeId(); + if (conditionTypes.containsKey(typeId)) { + LogWriter.info("AbilityController: Overwriting Condition type: " + typeId); + } + conditionTypes.put(typeId, conditionFactory); + } + + public Supplier getConditionType(String key) { + return conditionTypes.get(key); + } + + public String[] getConditionTypes() { + return conditionTypes.keySet().toArray(new String[0]); + } + public void registerFlightChecker(Predicate checker) { flightCheckers.add(checker); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java new file mode 100644 index 000000000..cf4d2ad8f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java @@ -0,0 +1,196 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.nbt.NBTTagCompound; + +public abstract class ConditionField { + protected final String key; + protected final String label; + protected final Class type; // Float.class, Integer.class, etc + protected T value; + + public ConditionField(String key, String label, Class type, T defaultValue) { + this.key = key; + this.label = label; + this.type = type; + this.value = defaultValue; + } + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } + + public String getKey() { + return key; + } + + public String getLabel() { + return label; + } + + public Class getType() { + return type; + } + + public abstract void writeNBT(NBTTagCompound nbt); + + public abstract void readNBT(NBTTagCompound nbt); + + public static ConditionField intField(String key, String label, int defaultValue) { + return intField(key, label, defaultValue, 0, Integer.MAX_VALUE); + } + + public static ConditionField intField(String key, String label, int defaultValue, int min, int max) { + return new NumberField<>(key, label, Integer.class, defaultValue, min, max); + } + + public static ConditionField doubleField(String key, String label, double defaultValue) { + return doubleField(key, label, defaultValue, 0, Double.MAX_VALUE); + } + + public static ConditionField doubleField(String key, String label, double defaultValue, double min, double max) { + return new NumberField<>(key, label, Double.class, defaultValue, min, max); + } + + public static ConditionField floatField(String key, String label, float defaultValue) { + return floatField(key, label, defaultValue, 0, Float.MAX_VALUE); + } + + public static ConditionField floatField(String key, String label, float defaultValue, float min, float max) { + return new NumberField<>(key, label, Float.class, defaultValue, min, max); + } + + public static ConditionField stringField(String key, String label) { + return new StringField(key, label, ""); + } + + public static ConditionField stringField(String key, String label, String defaultValue) { + return new StringField(key, label, defaultValue); + } + + public static ConditionField booleanField(String key, String label, boolean defaultValue) { + return new BoolField(key, label, defaultValue); + } + + public static > ConditionField enumField(String key, String label, E defaultValue, Class enumClass) { + return new EnumField<>(key, label, defaultValue, enumClass); + } + + public static > ConditionField enumField(String key, String label, E defaultValue) { + return new EnumField<>(key, label, defaultValue, defaultValue.getDeclaringClass()); + } + + private static class NumberField> extends ConditionField { + private T min; + private T max; + + public NumberField(String key, String label, Class type, T defaultValue, T min, T max) { + super(key, label, type, defaultValue); + this.min = min; + this.max = max; + } + + @Override + public void setValue(T value) { + if (value.compareTo(min) < 0) { + this.value = min; + } else if (value.compareTo(max) > 0) { + this.value = max; + } else { + this.value = value; + } + } + + public NumberField min(T value) { + this.min = value; + return this; + } + + public NumberField max(T value) { + this.max = value; + return this; + } + + @Override + public void writeNBT(NBTTagCompound nbt) { + if (value instanceof Integer) nbt.setInteger(key, (Integer) value); + else if (value instanceof Float) nbt.setFloat(key, (Float) value); + else if (value instanceof Double) nbt.setDouble(key, (Double) value); + else if (value instanceof Long) nbt.setLong(key, (Long) value); + } + + @Override + @SuppressWarnings("unchecked") + public void readNBT(NBTTagCompound nbt) { + if (!nbt.hasKey(key)) return; + T v; + if (type == Integer.class) v = (T) (Integer) nbt.getInteger(key); + else if (type == Float.class) v = (T) (Float) nbt.getFloat(key); + else if (type == Double.class) v = (T) (Double) nbt.getDouble(key); + else if (type == Long.class) v = (T) (Long) nbt.getLong(key); + else return; + setValue(v); + } + } + + private static class StringField extends ConditionField { + public StringField(String key, String label, String defaultValue) { + super(key, label, String.class, defaultValue); + } + + @Override + public void writeNBT(NBTTagCompound nbt) { + nbt.setString(key, value); + } + + @Override + public void readNBT(NBTTagCompound nbt) { + setValue(nbt.getString(key)); + } + } + + private static class BoolField extends ConditionField { + public BoolField(String key, String label, boolean defaultValue) { + super(key, label, Boolean.class, defaultValue); + } + + @Override + public void writeNBT(NBTTagCompound nbt) { + nbt.setBoolean(key, value); + } + + @Override + public void readNBT(NBTTagCompound nbt) { + setValue(nbt.getBoolean(key)); + } + } + + private static class EnumField> extends ConditionField { + private final E[] options; + + public EnumField(String key, String label, E defaultValue, Class enumClass) { + super(key, label, enumClass, defaultValue); + this.options = enumClass.getEnumConstants(); + } + + public E[] getOptions() { + return options; + } + + @Override + public void writeNBT(NBTTagCompound nbt) { + nbt.setString(key, value.name()); + } + + @Override + public void readNBT(NBTTagCompound nbt) { + if (!nbt.hasKey(key)) return; + try { + setValue(Enum.valueOf(type, nbt.getString(key))); + } catch (IllegalArgumentException ignored) {} + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java new file mode 100644 index 000000000..2c1b7e670 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java @@ -0,0 +1,94 @@ +package kamkeel.npcs.controllers.data.ability; + +import kamkeel.npcs.controllers.AbilityController; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.LogWriter; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +public interface IAbilityCondition { + /** + * Check if this condition is met. + * + * @param caster The entity that would use the ability (NPC or Player) + * @param target The current target (may be null for self-targeting abilities or players) + * @return true if the condition is satisfied + */ + boolean check(EntityLivingBase caster, EntityLivingBase target); + + UserType getUserType(); + + String getTypeId(); + + List> getFields(); + + default NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("userType", getUserType().ordinal()); + nbt.setString("type", getTypeId()); + for (ConditionField field : getFields()) { + field.writeNBT(nbt); + } + return nbt; + } + + default void readNBT(NBTTagCompound nbt) { + for (ConditionField field : getFields()) { + field.readNBT(nbt); + } + } + + static IAbilityCondition fromNBT(NBTTagCompound nbt) { + String typeId = nbt.getString("type"); + Supplier factory = AbilityController.Instance.getConditionType(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown condition type: " + typeId); + return null; + } + IAbilityCondition condition = factory.get(); + condition.readNBT(nbt); + + return condition; + } + + class ConditionHPAbove implements IAbilityCondition { + ConditionField threshold = ConditionField.floatField("threshold", "threshold", 0.5f); + + public ConditionHPAbove() { + } + + @Override + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + return caster.getHealth() / caster.getMaxHealth() > threshold.getValue(); + } + + @Override + public UserType getUserType() { + return UserType.BOTH; + } + + @Override + public String getTypeId() { + return "hp_above"; + } + + public float getThreshold() { + return threshold.getValue(); + } + + public void setThreshold(float threshold) { + this.threshold.setValue(threshold); + } + + @Override + public List> getFields() { + return Arrays.asList( + threshold + ); + } + } +} From fc8e2e9e7f7c0e8f39c084d27b02f516f2c49687 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 01:59:01 -0500 Subject: [PATCH 02/51] Create Ability Hud Editor and Remove Ability Wheel. --- .../controllers/data/ability/Ability.java | 19 + .../data/ability/AbilityIconData.java | 202 ++++ .../kamkeel/npcs/network/PacketHandler.java | 10 + .../npcs/network/enums/EnumDataPacket.java | 1 + .../npcs/network/enums/EnumPlayerPacket.java | 5 + .../data/ability/AbilityHotbarSyncPacket.java | 101 ++ .../ability/AbilityHotbarSavePacket.java | 86 ++ .../ability/AbilityHotbarSelectPacket.java | 63 ++ .../player/ability/AbilityTogglePacket.java | 72 ++ .../npcs/client/ClientEventHandler.java | 20 + .../java/noppes/npcs/client/ClientProxy.java | 6 +- .../advanced/SubGuiChainedAbilityConfig.java | 14 +- .../client/gui/hud/CompassHudComponent.java | 4 +- .../npcs/client/gui/hud/EnumHudComponent.java | 3 +- .../npcs/client/gui/hud/GuiHudEditor.java | 21 +- .../npcs/client/gui/hud/HudComponent.java | 3 +- .../gui/hud/QuestTrackingComponent.java | 8 +- .../hud/ability/AbilityHotbarComponent.java | 637 ++++++++++++ .../ability/AbilityHotbarSlotRenderer.java | 262 +++++ .../client/gui/hud/ability/AbilityIcon.java | 140 +++ .../gui/player/inventory/GuiAbilities.java | 984 ++++++++++++++++++ .../player/inventory/GuiCNPCInventory.java | 12 + .../inventory/SubGuiSelectAbilityForSlot.java | 155 +++ .../client/gui/util/GuiMenuTopButton.java | 11 + .../java/noppes/npcs/config/ConfigClient.java | 90 +- .../controllers/data/AbilityHotbarData.java | 47 + .../controllers/data/PlayerAbilityData.java | 16 +- .../data/PlayerAbilityHotbarData.java | 84 ++ .../npcs/controllers/data/PlayerData.java | 6 + .../client/tabs/InventoryTabCustomNpc.java | 4 + .../assets/customnpcs/lang/en_US.lang | 11 + .../textures/gui/ability_fallback.png | Bin 0 -> 203 bytes 32 files changed, 3057 insertions(+), 40 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java create mode 100644 src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java create mode 100644 src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java create mode 100644 src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java create mode 100644 src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java create mode 100644 src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java create mode 100644 src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java create mode 100644 src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java create mode 100644 src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java create mode 100644 src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java create mode 100644 src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java create mode 100644 src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java create mode 100644 src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 89e059967..ee4bb5090 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -734,6 +734,25 @@ public abstract class Ability implements IAbility, IAbilityAction { } } + // ── Icon tab (native) ───────────────────────────────────── + if (!isNpcInlineEdit()) { + AbilityIconData icon = AbilityIconData.fromAbility(this); + defs.add(FieldDef.stringField("gui.texture", icon::getTexture, icon::setTexture) + .tab("Icon")); + defs.add(FieldDef.section("ability.icon.section.uv").tab("Icon")); + defs.add(FieldDef.intField("ability.icon.x", icon::getIconX, icon::setIconX) + .tab("Icon").range(0, 4096)); + defs.add(FieldDef.intField("ability.icon.y", icon::getIconY, icon::setIconY) + .tab("Icon").range(0, 4096)); + defs.add(FieldDef.section("gui.size").tab("Icon")); + defs.add(FieldDef.intField("gui.width", icon::getWidth, icon::setWidth) + .tab("Icon").range(1, 256)); + defs.add(FieldDef.intField("gui.height", icon::getHeight, icon::setHeight) + .tab("Icon").range(1, 256)); + defs.add(FieldDef.floatField("gui.scale", icon::getScale, icon::setScale) + .tab("Icon").range(0.1f, 10.0f)); + } + // External field providers (e.g., DBC Addon injecting a "DBC" tab) for (IAbilityFieldProvider provider : AbilityController.Instance.getFieldProviders()) { provider.addFieldDefinitions(this, defs); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java new file mode 100644 index 000000000..2120e9ca6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java @@ -0,0 +1,202 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +/** + * Icon data for abilities, stored in the ability's customData NBT under "AbilityIcon". + * Used to render ability icons in the Ability Hotbar, Wheel, and Abilities Tab. + */ +public class AbilityIconData { + public static final String NBT_KEY = "AbilityIcon"; + + private final NBTTagCompound customData; + + // Icon properties + public String texture = ""; + public int iconX = 0; + public int iconY = 0; + public int width = 32; + public int height = 32; + public float scale = 1.0f; + + /** Per-state icon UV overrides (0-indexed, maps to toggle states 1, 2, ...). */ + private int[][] stateIcons = null; + + private AbilityIconData(NBTTagCompound customData) { + this.customData = customData; + } + + /** + * Create an AbilityIconData instance from a raw customData compound. + * Reads existing values if present, otherwise uses defaults. + */ + public static AbilityIconData fromCustomData(NBTTagCompound customData) { + AbilityIconData icon = new AbilityIconData(customData); + if (customData.hasKey(NBT_KEY)) { + icon.readFromNBT(customData.getCompoundTag(NBT_KEY)); + } + return icon; + } + + /** + * Create an AbilityIconData instance from an ability's customData. + */ + public static AbilityIconData fromAbility(Ability ability) { + return fromCustomData(ability.getCustomData()); + } + + /** + * Create an AbilityIconData instance from a chained ability's customData. + */ + public static AbilityIconData fromChainedAbility(ChainedAbility chain) { + return fromCustomData(chain.getCustomData()); + } + + /** + * Write current state back to the customData NBT. + */ + public void save() { + NBTTagCompound tag = new NBTTagCompound(); + writeToNBT(tag); + customData.setTag(NBT_KEY, tag); + } + + public void writeToNBT(NBTTagCompound nbt) { + nbt.setString("Texture", texture); + nbt.setInteger("IconX", iconX); + nbt.setInteger("IconY", iconY); + nbt.setInteger("Width", width); + nbt.setInteger("Height", height); + nbt.setFloat("Scale", scale); + if (stateIcons != null && stateIcons.length > 0) { + NBTTagList list = new NBTTagList(); + for (int[] pair : stateIcons) { + NBTTagCompound comp = new NBTTagCompound(); + comp.setInteger("IconX", pair[0]); + comp.setInteger("IconY", pair[1]); + list.appendTag(comp); + } + nbt.setTag("StateIcons", list); + } + } + + public void readFromNBT(NBTTagCompound nbt) { + texture = nbt.getString("Texture"); + iconX = nbt.getInteger("IconX"); + iconY = nbt.getInteger("IconY"); + width = nbt.getInteger("Width"); + if (width <= 0) width = 32; + height = nbt.getInteger("Height"); + if (height <= 0) height = 32; + scale = nbt.getFloat("Scale"); + if (scale <= 0) scale = 1.0f; + if (nbt.hasKey("StateIcons")) { + NBTTagList list = nbt.getTagList("StateIcons", 10); + stateIcons = new int[list.tagCount()][2]; + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound comp = list.getCompoundTagAt(i); + stateIcons[i][0] = comp.getInteger("IconX"); + stateIcons[i][1] = comp.getInteger("IconY"); + } + } + } + + /** + * Check if this icon has a valid texture configured. + */ + public boolean hasTexture() { + return texture != null && !texture.isEmpty(); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS AND SETTERS (with auto-save) + // ═══════════════════════════════════════════════════════════════════ + + public String getTexture() { + return texture; + } + + public void setTexture(String texture) { + this.texture = texture != null ? texture : ""; + save(); + } + + public int getIconX() { + return iconX; + } + + public void setIconX(int iconX) { + this.iconX = Math.max(0, iconX); + save(); + } + + public int getIconY() { + return iconY; + } + + public void setIconY(int iconY) { + this.iconY = Math.max(0, iconY); + save(); + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = Math.max(1, width); + save(); + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = Math.max(1, height); + save(); + } + + public float getScale() { + return scale; + } + + public void setScale(float scale) { + this.scale = Math.max(0.1f, scale); + save(); + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-STATE ICON OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + public void setStateIcons(int[][] stateIcons) { + this.stateIcons = stateIcons; + save(); + } + + /** + * Get iconX for a specific toggle state. + * Falls back to default iconX if no state override exists. + * @param state 1-indexed toggle state (0 = off/default) + */ + public int getIconXForState(int state) { + if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { + return stateIcons[state - 1][0]; + } + return iconX; + } + + /** + * Get iconY for a specific toggle state. + * Falls back to default iconY if no state override exists. + * @param state 1-indexed toggle state (0 = off/default) + */ + public int getIconYForState(int state) { + if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { + return stateIcons[state - 1][1]; + } + return iconY; + } +} diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index c3c555d48..ca172edc3 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -26,6 +26,7 @@ import kamkeel.npcs.network.packets.data.SoundManagementPacket; import kamkeel.npcs.network.packets.data.SwingPlayerArmPacket; import kamkeel.npcs.network.packets.data.UpdateAnimationsPacket; import kamkeel.npcs.network.packets.data.VillagerListPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.gui.GuiClosePacket; @@ -54,6 +55,9 @@ import kamkeel.npcs.network.packets.data.script.ScriptedParticlePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityTogglePacket; import kamkeel.npcs.network.packets.player.BankActionPacket; import kamkeel.npcs.network.packets.player.CheckPlayerValue; import kamkeel.npcs.network.packets.player.CompanionActionPacket; @@ -598,6 +602,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new TelegraphRemovePacket()); DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); + DATA_PACKET.registerPacket(new AbilityHotbarSyncPacket()); } public void registerPlayerPackets() { @@ -663,6 +668,11 @@ public class PacketHandler { PLAYER_PACKET.registerPacket(new PartyAcceptInvitePacket()); PLAYER_PACKET.registerPacket(new PartyIgnoreInvitePacket()); PLAYER_PACKET.registerPacket(new PartyLogToServerPacket()); + + // Ability Hotbar Packets + PLAYER_PACKET.registerPacket(new AbilityHotbarSavePacket()); + PLAYER_PACKET.registerPacket(new AbilityHotbarSelectPacket()); + PLAYER_PACKET.registerPacket(new AbilityTogglePacket()); } public void registerChannels() { diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index 8362cb3c5..e72cd2810 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -64,6 +64,7 @@ public enum EnumDataPacket { TELEGRAPH_REMOVE, PLAYER_ABILITY_SYNC, PLAYER_ABILITY_STATE, + ABILITY_HOTBAR_SYNC, // Auction System AUCTION_DATA, diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java index 48f400fb2..e1587467b 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java @@ -37,4 +37,9 @@ public enum EnumPlayerPacket { // Auction AuctionAction, + + // Ability Hotbar + AbilityHotbarSave, + AbilityHotbarSelect, + AbilityToggle, } diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java new file mode 100644 index 000000000..a30682ecc --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java @@ -0,0 +1,101 @@ +package kamkeel.npcs.network.packets.data.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerAbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSyncPacket extends AbstractPacket { + public static final String packetName = "Data|AbilityHotbarSync"; + + private NBTTagCompound hotbarNBT; + + public AbilityHotbarSyncPacket() { + } + + public AbilityHotbarSyncPacket(NBTTagCompound hotbarNBT) { + this.hotbarNBT = hotbarNBT; + } + + @Override + public Enum getType() { + return EnumDataPacket.ABILITY_HOTBAR_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, hotbarNBT); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt == null) return; + + PlayerData data = ClientCacheHandler.playerData; + if (data != null) { + data.hotbarData.readFromNBT(nbt); + } + } + + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + PlayerAbilityHotbarData hotbarData = data.hotbarData; + boolean anyCleared = false; + + // Validate all slots before sending + if (AbilityController.Instance != null) { + for (int i = 0; i < hotbarData.slots.length; i++) { + AbilityHotbarData slot = hotbarData.slots[i]; + if (slot.isEmpty()) continue; + + boolean valid; + if (slot.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slot.abilityKey); + } + + if (valid && data.abilityData != null) { + valid = data.abilityData.hasUnlockedAbility(slot.abilityKey); + } + + if (!valid) { + slot.reset(); + anyCleared = true; + } + } + } + + NBTTagCompound nbt = new NBTTagCompound(); + hotbarData.writeToNBT(nbt); + PacketHandler.Instance.sendToPlayer(new AbilityHotbarSyncPacket(nbt), player); + + if (anyCleared) { + data.save(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java new file mode 100644 index 000000000..1522763fc --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSavePacket extends AbstractPacket { + public static final String packetName = "Player|AbilityHotbarSave"; + + private int slotIndex; + private NBTTagCompound slotData; + + public AbilityHotbarSavePacket() { + } + + public AbilityHotbarSavePacket(int slotIndex, NBTTagCompound slotData) { + this.slotIndex = slotIndex; + this.slotData = slotData; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityHotbarSave; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(slotIndex); + ByteBufUtils.writeNBT(out, slotData); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + int slot = in.readInt(); + NBTTagCompound compound = ByteBufUtils.readNBT(in); + + if (slot < 0 || slot >= AbilityHotbarData.TOTAL_SLOTS) return; + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + AbilityHotbarData slotData = data.hotbarData.getSlot(slot); + if (slotData == null) return; + + slotData.readFromNBT(compound.getCompoundTag("AbilityHotbar" + slot)); + + // Validate the ability key + boolean valid = true; + if (!slotData.isEmpty() && AbilityController.Instance != null) { + if (slotData.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slotData.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slotData.abilityKey); + } + + if (valid && data.abilityData != null) { + valid = data.abilityData.hasUnlockedAbility(slotData.abilityKey); + } + } + + if (!valid) { + slotData.reset(); + } + + data.save(); + AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java new file mode 100644 index 000000000..7a4e183a2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java @@ -0,0 +1,63 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSelectPacket extends AbstractPacket { + public static final String packetName = "Player|AbilityHotbarSelect"; + + private String abilityKey; + + public AbilityHotbarSelectPacket() { + } + + public AbilityHotbarSelectPacket(String abilityKey) { + this.abilityKey = abilityKey; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityHotbarSelect; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityKey != null ? abilityKey : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String key = ByteBufUtils.readString(in); + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null || data.abilityData == null) return; + + if (key == null || key.isEmpty()) { + // Deselect + data.abilityData.setSelectedIndex(-1); + } else { + int index = data.abilityData.getUnlockedAbilityList().indexOf(key); + if (index >= 0) { + data.abilityData.setSelectedIndex(index); + } + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java new file mode 100644 index 000000000..f9f402c5e --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java @@ -0,0 +1,72 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.StatCollector; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityTogglePacket extends AbstractPacket { + public static final String packetName = "Player|AbilityToggle"; + private String abilityKey; + + public AbilityTogglePacket() { + } + + public AbilityTogglePacket(String abilityKey) { + this.abilityKey = abilityKey; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityToggle; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityKey != null ? abilityKey : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String key = ByteBufUtils.readString(in); + if (key == null || key.isEmpty()) return; + if (AbilityController.Instance == null) return; + + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null || !ability.isToggleable() || !ability.getAllowedBy().allowsPlayer()) return; + + PlayerData playerData = PlayerData.get(player); + if (playerData == null || playerData.abilityData == null) return; + + int newState = playerData.abilityData.toggleAbility(key); + + String displayName = ability.getDisplayName(); + if (newState > 0) { + String stateLabel = ability.getToggleStateLabel(newState); + if (stateLabel != null) { + player.addChatMessage(new ChatComponentText("\u00A7a" + displayName + " " + stateLabel)); + } else { + String enabled = StatCollector.translateToLocal("gui.enabled"); + player.addChatMessage(new ChatComponentText("\u00A7a" + displayName + " " + enabled)); + } + } else { + String disabled = StatCollector.translateToLocal("gui.disabled"); + player.addChatMessage(new ChatComponentText("\u00A7c" + displayName + " " + disabled)); + } + } +} diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index a73ccf707..6eebfd5d5 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -25,6 +25,7 @@ import noppes.npcs.client.gui.hud.ClientHudManager; import noppes.npcs.client.gui.hud.CompassHudComponent; import noppes.npcs.client.gui.hud.EnumHudComponent; import noppes.npcs.client.gui.hud.QuestTrackingComponent; +import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent; import noppes.npcs.client.gui.player.AuctionTooltipHandler; import noppes.npcs.client.renderer.MarkRenderer; import noppes.npcs.client.renderer.RenderCNPCPlayer; @@ -98,6 +99,24 @@ public class ClientEventHandler { return; } + // Ability Hotbar: Hold HUD key + scroll wheel to cycle + if (event.dwheel != 0 && ClientProxy.AbilityHudKey != null) { + int hudKeyCode = ClientProxy.AbilityHudKey.getKeyCode(); + if (hudKeyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode)) { + AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance() + .getHudComponents().get(EnumHudComponent.AbilityHotbar); + if (comp != null && comp.hasAnyAbilities()) { + if (event.dwheel > 0) { + comp.onCyclePrev(); + } else { + comp.onCycleNext(); + } + event.setCanceled(true); + return; + } + } + } + ArrayList removeList = new ArrayList<>(); for (Map.Entry entry : disabledButtonTimes.entrySet()) { if (entry.getValue() > 0) { @@ -125,6 +144,7 @@ public class ClientEventHandler { if (ClientHudManager.getInstance().getHudComponents().isEmpty()) { ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestTracker, new QuestTrackingComponent(Minecraft.getMinecraft())); ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestCompass, new CompassHudComponent(Minecraft.getMinecraft())); + ClientHudManager.getInstance().registerHud(EnumHudComponent.AbilityHotbar, new AbilityHotbarComponent(Minecraft.getMinecraft())); } ClientHudManager.getInstance().renderAllHUDs(event.partialTicks); diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index a0a5ce060..c0a113a96 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -257,6 +257,7 @@ import java.util.Random; public class ClientProxy extends CommonProxy { public static KeyBinding NPCButton; public static KeyBinding SpecialKey; + public static KeyBinding AbilityHudKey; public static final Random RAND = new Random(); public static FontContainer Font; @@ -332,11 +333,14 @@ public class ClientProxy extends CommonProxy { Minecraft mc = Minecraft.getMinecraft(); NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc"); - SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_B, "key.categories.customnpc"); + SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_GRAVE, "key.categories.customnpc"); ClientRegistry.registerKeyBinding(NPCButton); ClientRegistry.registerKeyBinding(SpecialKey); + AbilityHudKey = new KeyBinding("key.customnpcs.abilityHudKey", Keyboard.KEY_LMENU, "key.categories.customnpc"); + ClientRegistry.registerKeyBinding(AbilityHudKey); + new PresetController(CustomNpcs.Dir); if (ConfigMain.EnableUpdateChecker) { diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index da71dec70..565443c3d 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -7,6 +7,7 @@ import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.ChainedAbility; import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry; import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.data.ability.AbilityIconData; import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.network.PacketClient; @@ -157,7 +158,18 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText FieldDef.floatField("ability.maxRange", chain::getMaxRange, chain::setMaxRange).range(0, 64) ).tab("Target")); - // External field providers (e.g., DBC Addon injecting an "Icon" tab) + // ── Icon tab ────────────────────────────────────────────── + AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain); + fieldDefs.add(FieldDef.stringField("gui.texture", chainIcon::getTexture, chainIcon::setTexture).tab("Icon")); + fieldDefs.add(FieldDef.section("ability.icon.section.uv").tab("Icon")); + fieldDefs.add(FieldDef.intField("ability.icon.x", chainIcon::getIconX, chainIcon::setIconX).tab("Icon").range(0, 4096)); + fieldDefs.add(FieldDef.intField("ability.icon.y", chainIcon::getIconY, chainIcon::setIconY).tab("Icon").range(0, 4096)); + fieldDefs.add(FieldDef.section("gui.size").tab("Icon")); + fieldDefs.add(FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).tab("Icon").range(1, 256)); + fieldDefs.add(FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).tab("Icon").range(1, 256)); + fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f)); + + // External field providers (e.g., DBC Addon injecting a "DBC" tab) if (AbilityController.Instance != null) { for (IChainedAbilityFieldProvider provider : AbilityController.Instance.getChainedFieldProviders()) { provider.addFieldDefinitions(chain, fieldDefs); diff --git a/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java index aa6d9c21a..cd5ddb2dd 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java @@ -81,10 +81,10 @@ public class CompassHudComponent extends HudComponent { ConfigClient.CompassEnabledProperty.set(ConfigClient.CompassEnabled); ConfigClient.CompassOverlayX = posX; - ConfigClient.CompassOverlayXProperty.set(ConfigClient.CompassOverlayX); + ConfigClient.CompassOverlayXProperty.set((double) ConfigClient.CompassOverlayX); ConfigClient.CompassOverlayY = posY; - ConfigClient.CompassOverlayYProperty.set(ConfigClient.CompassOverlayY); + ConfigClient.CompassOverlayYProperty.set((double) ConfigClient.CompassOverlayY); ConfigClient.CompassOverlayScale = scale; ConfigClient.CompassOverlayScaleProperty.set(ConfigClient.CompassOverlayScale); diff --git a/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java index fe6eb07b6..7eda9a335 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java @@ -2,5 +2,6 @@ package noppes.npcs.client.gui.hud; public enum EnumHudComponent { QuestTracker, - QuestCompass + QuestCompass, + AbilityHotbar } diff --git a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java index 5908cf9b8..d36727aad 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java +++ b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java @@ -173,7 +173,8 @@ public class GuiHudEditor extends GuiScreen { int absHeight = (int) (hud.overlayHeight * effectiveScale); if (mouseX >= actualX && mouseX <= actualX + absWidth && mouseY >= actualY && mouseY <= actualY + absHeight) { - if (mouseX >= actualX + absWidth - HANDLE_SIZE && mouseY >= actualY + absHeight - HANDLE_SIZE) { + int scaledHandle = Math.max(8, (int) (HANDLE_SIZE * effectiveScale)); + if (mouseX >= actualX + absWidth - scaledHandle && mouseY >= actualY + absHeight - scaledHandle) { resizing = true; selectedComponent = hud; initialScale = hud.scale; @@ -214,12 +215,14 @@ public class GuiHudEditor extends GuiScreen { int newY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight) - dragOffsetY; if (newX < 0) newX = 0; if (newY < 0) newY = 0; - if (newX + (int) (selectedComponent.overlayWidth * effectiveScale) > scaledWidth) - newX = scaledWidth - (int) (selectedComponent.overlayWidth * effectiveScale); - if (newY + (int) (selectedComponent.overlayHeight * effectiveScale) > scaledHeight) - newY = scaledHeight - (int) (selectedComponent.overlayHeight * effectiveScale); - selectedComponent.posX = (int) (100F * newX / scaledWidth); - selectedComponent.posY = (int) (100F * newY / scaledHeight); + int compW = (int) Math.ceil(selectedComponent.overlayWidth * effectiveScale); + int compH = (int) Math.ceil(selectedComponent.overlayHeight * effectiveScale); + if (newX + compW > scaledWidth) + newX = scaledWidth - compW; + if (newY + compH > scaledHeight) + newY = scaledHeight - compH; + selectedComponent.posX = 100F * newX / scaledWidth; + selectedComponent.posY = 100F * newY / scaledHeight; } if (resizing) { int currentMouseX = Mouse.getX() * width / mc.displayWidth; @@ -260,8 +263,8 @@ public class GuiHudEditor extends GuiScreen { } int centerX = (res.getScaledWidth() - compWidth) / 2; int centerY = (res.getScaledHeight() - compHeight) / 2; - selectedComponent.posX = (int) (100F * centerX / res.getScaledWidth()); - selectedComponent.posY = (int) (100F * centerY / res.getScaledHeight()); + selectedComponent.posX = 100F * centerX / res.getScaledWidth(); + selectedComponent.posY = 100F * centerY / res.getScaledHeight(); updateCustomButtons(); } } else if (button.id == CYCLE_LEFT_ID) { diff --git a/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java index 53a7a2170..bc153f890 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java @@ -8,7 +8,8 @@ import java.util.List; public abstract class HudComponent { // Stored as percentages (0-100) of the current screen resolution. - protected int posX = 50, posY = 50, scale = 100, textAlign = 0; + public float posX = 50, posY = 50; + protected int scale = 100, textAlign = 0; public boolean enabled = true; public boolean hasData = false; diff --git a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java index 8ed5ece3a..ee6a6fe51 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java @@ -113,10 +113,10 @@ public class QuestTrackingComponent extends HudComponent { @Override public void save() { ConfigClient.QuestOverlayX = posX; - ConfigClient.QuestOverlayXProperty.set(ConfigClient.QuestOverlayX); + ConfigClient.QuestOverlayXProperty.set((double) ConfigClient.QuestOverlayX); ConfigClient.QuestOverlayY = posY; - ConfigClient.QuestOverlayYProperty.set(ConfigClient.QuestOverlayY); + ConfigClient.QuestOverlayYProperty.set((double) ConfigClient.QuestOverlayY); ConfigClient.QuestOverlayScale = scale; ConfigClient.QuestOverlayScaleProperty.set(ConfigClient.QuestOverlayScale); @@ -218,8 +218,8 @@ public class QuestTrackingComponent extends HudComponent { int compHeight = (int) (overlayHeight * effectiveScale); int centerX = (res.getScaledWidth() - compWidth) / 2; int centerY = (res.getScaledHeight() - compHeight) / 2; - posX = (int) (100F * centerX / res.getScaledWidth()); - posY = (int) (100F * centerY / res.getScaledHeight()); + posX = 100F * centerX / res.getScaledWidth(); + posY = 100F * centerY / res.getScaledHeight(); } else { super.onEditorButtonPressed(button); } diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java new file mode 100644 index 000000000..56189a698 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java @@ -0,0 +1,637 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import net.minecraft.client.Minecraft; +import noppes.npcs.client.ClientProxy; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.hud.HudComponent; +import noppes.npcs.config.ConfigClient; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerAbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +@SideOnly(Side.CLIENT) +public class AbilityHotbarComponent extends HudComponent { + public static final int TOTAL_SLOTS = AbilityHotbarData.TOTAL_SLOTS; + + private static final int BASE_SLOT_SIZE = 24; + private static final int BASE_SPACING = 28; + + private AbilityHotbarSlotRenderer[] slots = new AbilityHotbarSlotRenderer[TOTAL_SLOTS]; + + // Filtered carousel: only filled slots + one deselect entry + // Each entry is a raw slot index (0-11), or -1 for the deselect slot + private int[] activeIndices = new int[0]; + private int activeCenter = 0; + + private float scrollOffset = 0f; + private long scrollStartTime = 0; + private static final long SCROLL_DURATION = 150; + + private long lastUpdateTime = 0; + private static final long UPDATE_INTERVAL = 500; + + // Debounce: delay sending selection packet + private String pendingSelectKey = null; + private long pendingSelectTime = 0; + private static final long SELECT_DEBOUNCE = 300; + + // Grace period: don't let server state override local state after user interaction + private long lastUserCycleTime = 0; + private static final long USER_CYCLE_GRACE = 1000; + + // Fade: when ShowAlways=false, fade in/out when HUD key is held + private float fadeAlpha = 0f; + private static final float FADE_SPEED = 8f; // per second — ~125ms full transition + + private Minecraft mc; + + public AbilityHotbarComponent(Minecraft mc) { + this.mc = mc; + updateOverlayDimensions(); + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i] = new AbilityHotbarSlotRenderer(i); + } + load(); + } + + private int getEffectiveVisibleSlots() { + int configMax = ConfigClient.AbilityHotbarVisibleSlots; + if (configMax != 3 && configMax != 5 && configMax != 7) configMax = 5; + int filledCount = activeIndices.length - 1; // subtract deselect slot + if (filledCount < 0) filledCount = 0; + if (filledCount < 5) return Math.min(configMax, 3); + if (filledCount < 7) return Math.min(configMax, 5); + return configMax; + } + + private void updateOverlayDimensions() { + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + int visibleSlots = getEffectiveVisibleSlots(); + int span = BASE_SPACING * (visibleSlots - 1) + BASE_SLOT_SIZE; + int thick = BASE_SLOT_SIZE + 4; + if (isHorizontal) { + overlayWidth = span; + overlayHeight = thick; + } else { + overlayWidth = thick; + overlayHeight = span; + } + } + + @Override + public void loadData(NBTTagCompound compound) { + } + + @Override + public void load() { + posX = ConfigClient.AbilityHotbarX; + posY = ConfigClient.AbilityHotbarY; + scale = ConfigClient.AbilityHotbarScale; + enabled = ConfigClient.AbilityHotbarEnabled; + } + + @Override + public void save() { + ConfigClient.AbilityHotbarX = posX; + ConfigClient.AbilityHotbarXProperty.set((double) posX); + + ConfigClient.AbilityHotbarY = posY; + ConfigClient.AbilityHotbarYProperty.set((double) posY); + + ConfigClient.AbilityHotbarScale = scale; + ConfigClient.AbilityHotbarScaleProperty.set(scale); + + ConfigClient.AbilityHotbarEnabled = enabled; + ConfigClient.AbilityHotbarEnabledProperty.set(enabled); + + ConfigClient.AbilityHotbarHorizontalProperty.set(ConfigClient.AbilityHotbarHorizontal); + ConfigClient.AbilityHotbarAltTextureProperty.set(ConfigClient.AbilityHotbarAltTexture); + ConfigClient.AbilityHotbarTextPositionProperty.set(ConfigClient.AbilityHotbarTextPosition); + ConfigClient.AbilityHotbarVisibleSlotsProperty.set(ConfigClient.AbilityHotbarVisibleSlots); + ConfigClient.AbilityHotbarShowAlwaysProperty.set(ConfigClient.AbilityHotbarShowAlways); + + if (ConfigClient.config.hasChanged()) { + ConfigClient.config.save(); + } + } + + @Override + public void renderOnScreen(float partialTicks) { + if (!enabled || isEditting) return; + if (mc.thePlayer == null || mc.currentScreen != null) return; + if (!hasAnyAbilities()) return; + + // Fade logic: when ShowAlways=false, only show while HUD key is held + boolean showAlways = ConfigClient.AbilityHotbarShowAlways; + if (!showAlways) { + boolean hudKeyHeld = isHudKeyHeld(); + float dt = partialTicks > 0 ? 1f / 20f : 0.05f; // approximate frame time + if (hudKeyHeld || pendingSelectKey != null || scrollOffset != 0f) { + fadeAlpha = Math.min(1f, fadeAlpha + FADE_SPEED * dt); + } else { + fadeAlpha = Math.max(0f, fadeAlpha - FADE_SPEED * dt); + } + if (fadeAlpha <= 0f) return; + } else { + fadeAlpha = 1f; + } + + long currentTime = Minecraft.getSystemTime(); + if (currentTime - lastUpdateTime > UPDATE_INTERVAL) { + updateAbilities(); + lastUpdateTime = currentTime; + } + + // Flush debounced selection packet + if (pendingSelectKey != null && currentTime - pendingSelectTime >= SELECT_DEBOUNCE) { + PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(pendingSelectKey)); + pendingSelectKey = null; + } + + updateScrollAnimation(); + updateOverlayDimensions(); + + if (activeIndices.length == 0) return; + + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + float effectiveScale = getEffectiveScale(sr); + int visibleSlots = getEffectiveVisibleSlots(); + int half = visibleSlots / 2; + + int actualX = (int) (posX / 100.0f * sr.getScaledWidth()); + int actualY = (int) (posY / 100.0f * sr.getScaledHeight()); + + GL11.glPushMatrix(); + GL11.glTranslatef(actualX, actualY, 0); + GL11.glScalef(effectiveScale, effectiveScale, 1); + + int centerX = overlayWidth / 2; + int centerY = overlayHeight / 2; + + float cooldownProgress = 0; + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + if (playerData.abilityData.isOnCooldown()) { + cooldownProgress = 0.5f; + } + } + + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i].updateNameFade(); + } + + for (int offset = -half; offset <= half; offset++) { + int activeIdx = ((activeCenter + offset) % activeIndices.length + activeIndices.length) % activeIndices.length; + int rawSlotIndex = activeIndices[activeIdx]; + + float visualPos = offset + scrollOffset; + float absDist = Math.abs(visualPos); + + float slotScale; + if (absDist <= 1f) { + slotScale = 1.0f - 0.25f * absDist; + } else { + slotScale = 0.75f - 0.15f * (absDist - 1f); + } + slotScale = Math.max(0.1f, slotScale); + + int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale)); + + int cx, cy; + if (isHorizontal) { + cx = centerX + (int) (visualPos * BASE_SPACING); + cy = centerY; + } else { + cx = centerX; + cy = centerY + (int) (visualPos * BASE_SPACING); + } + + float maxDist = half + 0.5f; + if (absDist > maxDist) continue; + + float edgeAlpha = absDist > half - 0.5f ? 1f - (absDist - (half - 0.5f)) : 1f; + float slotAlpha = edgeAlpha * fadeAlpha; + boolean isCenter = (offset == 0 && scrollOffset == 0f); + float slotCooldown = isCenter ? cooldownProgress : 0; + + if (rawSlotIndex == -1) { + // Deselect slot — draw empty marker + drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha); + } else { + slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha); + } + } + + GL11.glPopMatrix(); + } + + private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha) { + float radius = size / 2f; + float baseAlpha = isCenter ? 0.9f : 0.6f; + float a = baseAlpha * alpha; + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + GL11.glPushMatrix(); + GL11.glTranslatef(cx, cy, 0); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + if (isCenter) { + GL11.glColor4f(0.5f, 0.2f, 0.2f, a); + } else { + GL11.glColor4f(0.3f, 0.3f, 0.3f, a); + } + + if (altTexture) { + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(-radius, -radius); + GL11.glVertex2f(radius, -radius); + GL11.glVertex2f(radius, radius); + GL11.glVertex2f(-radius, radius); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + for (int i = 0; i <= 32; i++) { + double angle = 2 * Math.PI * i / 32; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + + // Draw X mark + if (isCenter) { + GL11.glColor4f(0.8f, 0.4f, 0.4f, alpha); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, alpha * 0.8f); + } + float xSize = radius * 0.4f; + GL11.glLineWidth(2.0f); + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(-xSize, -xSize); + GL11.glVertex2f(xSize, xSize); + GL11.glVertex2f(-xSize, xSize); + GL11.glVertex2f(xSize, -xSize); + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + + @Override + public void renderEditing() { + isEditting = true; + updateOverlayDimensions(); + + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + float effectiveScale = getEffectiveScale(sr); + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + FontRenderer fr = mc.fontRenderer; + int visibleSlots = getEffectiveVisibleSlots(); + int half = visibleSlots / 2; + + int actualX = (int) (posX / 100.0f * sr.getScaledWidth()); + int actualY = (int) (posY / 100.0f * sr.getScaledHeight()); + + GL11.glPushMatrix(); + GL11.glTranslatef(actualX, actualY, 0); + GL11.glScalef(effectiveScale, effectiveScale, 1); + + int centerX = overlayWidth / 2; + int centerY = overlayHeight / 2; + + int[] slotCx = new int[visibleSlots]; + int[] slotCy = new int[visibleSlots]; + int[] slotSizes = new int[visibleSlots]; + + for (int offset = -half; offset <= half; offset++) { + float absDist = Math.abs(offset); + float slotScale; + if (absDist <= 1f) { + slotScale = 1.0f - 0.25f * absDist; + } else { + slotScale = 0.75f - 0.15f * (absDist - 1f); + } + slotScale = Math.max(0.1f, slotScale); + int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale)); + + int cx, cy; + if (isHorizontal) { + cx = centerX + offset * BASE_SPACING; + cy = centerY; + } else { + cx = centerX; + cy = centerY + offset * BASE_SPACING; + } + + int idx = offset + half; + slotCx[idx] = cx; + slotCy[idx] = cy; + slotSizes[idx] = scaledSize; + + float radius = scaledSize / 2f; + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + float alpha = offset == 0 ? 0.9f : 0.6f; + if (offset == 0) { + GL11.glColor4f(0.8f, 0.8f, 0.2f, alpha); + } else { + GL11.glColor4f(0.4f, 0.4f, 0.4f, alpha); + } + + if (altTexture) { + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(cx - radius, cy - radius); + GL11.glVertex2f(cx + radius, cy - radius); + GL11.glVertex2f(cx + radius, cy + radius); + GL11.glVertex2f(cx - radius, cy + radius); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(cx, cy); + for (int i = 0; i <= 32; i++) { + double angle = 2 * Math.PI * i / 32; + GL11.glVertex2f(cx + (float) (Math.cos(angle) * radius), cy + (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + } + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + for (int i = 0; i < visibleSlots; i++) { + String label = String.valueOf(i + 1); + float labelScale = slotSizes[i] / 24.0f; + if (labelScale < 0.4f) continue; + + int textColor = (i == half) ? 0xFFFFFFFF : 0xAABBBBBB; + int textW = fr.getStringWidth(label); + + GL11.glPushMatrix(); + GL11.glTranslatef(slotCx[i], slotCy[i], 0); + GL11.glScalef(labelScale, labelScale, 1); + fr.drawString(label, -textW / 2, -fr.FONT_HEIGHT / 2, textColor); + GL11.glPopMatrix(); + } + + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + String modeLabel = altTexture ? "Square" : "Circle"; + int modeLabelW = fr.getStringWidth(modeLabel); + fr.drawStringWithShadow(modeLabel, overlayWidth / 2 - modeLabelW / 2, overlayHeight + 2, 0xAA888888); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(0.2f, 0.8f, 0.2f, 0.8f); + GL11.glLineWidth(1.0f); + GL11.glBegin(GL11.GL_LINE_LOOP); + GL11.glVertex2f(0, 0); + GL11.glVertex2f(overlayWidth, 0); + GL11.glVertex2f(overlayWidth, overlayHeight); + GL11.glVertex2f(0, overlayHeight); + GL11.glEnd(); + + GL11.glColor4f(0.8f, 0.8f, 0.8f, 0.9f); + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(overlayWidth - 10, overlayHeight - 10); + GL11.glVertex2f(overlayWidth, overlayHeight - 10); + GL11.glVertex2f(overlayWidth, overlayHeight); + GL11.glVertex2f(overlayWidth - 10, overlayHeight); + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + GL11.glPopMatrix(); + } + + @Override + public void addEditorButtons(List buttonList) { + super.addEditorButtons(buttonList); + String orientLabel = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical"; + buttonList.add(new GuiButton(1, 0, 0, 120, 20, orientLabel)); + + String texLabel = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; + buttonList.add(new GuiButton(2, 0, 0, 120, 20, texLabel)); + + buttonList.add(new GuiButton(3, 0, 0, 120, 20, getTextPositionLabel())); + buttonList.add(new GuiButton(4, 0, 0, 120, 20, "Slots: " + ConfigClient.AbilityHotbarVisibleSlots)); + buttonList.add(new GuiButton(5, 0, 0, 120, 20, ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key")); + } + + @Override + public void onEditorButtonPressed(GuiButton button) { + if (button.id == 1) { + ConfigClient.AbilityHotbarHorizontal = !ConfigClient.AbilityHotbarHorizontal; + button.displayString = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical"; + updateOverlayDimensions(); + } else if (button.id == 2) { + ConfigClient.AbilityHotbarAltTexture = !ConfigClient.AbilityHotbarAltTexture; + button.displayString = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; + } else if (button.id == 3) { + ConfigClient.AbilityHotbarTextPosition = (ConfigClient.AbilityHotbarTextPosition + 1) % 3; + button.displayString = getTextPositionLabel(); + } else if (button.id == 4) { + int current = ConfigClient.AbilityHotbarVisibleSlots; + if (current <= 3) ConfigClient.AbilityHotbarVisibleSlots = 5; + else if (current <= 5) ConfigClient.AbilityHotbarVisibleSlots = 7; + else ConfigClient.AbilityHotbarVisibleSlots = 3; + button.displayString = "Slots: " + ConfigClient.AbilityHotbarVisibleSlots; + updateOverlayDimensions(); + } else if (button.id == 5) { + ConfigClient.AbilityHotbarShowAlways = !ConfigClient.AbilityHotbarShowAlways; + button.displayString = ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key"; + } else { + super.onEditorButtonPressed(button); + } + } + + private String getTextPositionLabel() { + boolean h = ConfigClient.AbilityHotbarHorizontal; + switch (ConfigClient.AbilityHotbarTextPosition) { + case 0: return "Text: Hide"; + case 1: return h ? "Text: Above" : "Text: Left"; + case 2: return h ? "Text: Below" : "Text: Right"; + default: return "Text: Hide"; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Ability Update & Scroll + // ═══════════════════════════════════════════════════════════════════ + + private void updateAbilities() { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null) return; + + PlayerAbilityHotbarData hotbarData = playerData.hotbarData; + if (hotbarData == null) return; + + for (int i = 0; i < TOTAL_SLOTS; i++) { + AbilityHotbarData slotData = hotbarData.slots[i]; + String key = slotData.isEmpty() ? null : slotData.abilityKey; + Ability ability = null; + IAbilityAction action = null; + if (key != null && AbilityController.Instance != null) { + if (slotData.isChainKey()) { + action = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + } else { + ability = AbilityController.Instance.resolveAbility(key); + action = ability; + } + if (ability == null && action == null) key = null; + } + slots[i].setAbility(key, ability, action); + } + + // Rebuild active indices: filled slots + one deselect slot (-1) + ArrayList active = new ArrayList<>(); + for (int i = 0; i < TOTAL_SLOTS; i++) { + if (slots[i].abilityKey != null) { + active.add(i); + } + } + active.add(-1); // Deselect slot at the end + activeIndices = new int[active.size()]; + for (int i = 0; i < active.size(); i++) { + activeIndices[i] = active.get(i); + } + + // Clamp activeCenter + if (activeCenter >= activeIndices.length) { + activeCenter = 0; + } + + // Don't override local selection state while user is scrolling, debounce is pending, + // or within the grace period after the last user interaction. + // This prevents the server state from fighting the local carousel position. + long now = Minecraft.getSystemTime(); + if (pendingSelectKey != null || scrollOffset != 0f || (now - lastUserCycleTime < USER_CYCLE_GRACE)) { + return; + } + + // Sync selected state and find which active index is selected + if (playerData.abilityData != null) { + String selectedKey = playerData.abilityData.getSelectedAbilityKey(); + boolean foundSelected = false; + for (int i = 0; i < TOTAL_SLOTS; i++) { + AbilityHotbarData slotData = hotbarData.slots[i]; + boolean sel = selectedKey != null && !slotData.isEmpty() + && selectedKey.equals(slotData.abilityKey); + slots[i].setSelectedState(sel); + if (sel) { + // Find this slot's position in activeIndices + for (int j = 0; j < activeIndices.length; j++) { + if (activeIndices[j] == i) { + activeCenter = j; + foundSelected = true; + break; + } + } + } + } + if (!foundSelected) { + // No ability selected on server — center on deselect slot + for (int j = 0; j < activeIndices.length; j++) { + if (activeIndices[j] == -1) { + activeCenter = j; + break; + } + } + } + } + } + + private boolean isHudKeyHeld() { + if (ClientProxy.AbilityHudKey == null) return false; + int keyCode = ClientProxy.AbilityHudKey.getKeyCode(); + return keyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(keyCode); + } + + public boolean hasAnyAbilities() { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.hotbarData == null) return false; + return playerData.hotbarData.hasAnyAbilities(); + } + + public void onCycleNext() { + cycle(1); + } + + public void onCyclePrev() { + cycle(-1); + } + + private void cycle(int direction) { + if (!enabled) return; + if (mc.thePlayer == null || mc.currentScreen != null) return; + if (activeIndices.length == 0) return; + + activeCenter = ((activeCenter + direction) % activeIndices.length + activeIndices.length) % activeIndices.length; + scrollOffset = direction; + long now = Minecraft.getSystemTime(); + scrollStartTime = now; + lastUserCycleTime = now; + + int rawSlotIndex = activeIndices[activeCenter]; + + // Update selection states locally + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i].setSelectedState(i == rawSlotIndex); + } + + // Debounce: queue the selection, don't send immediately + String keyToSend = rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null + ? slots[rawSlotIndex].abilityKey : ""; + pendingSelectKey = keyToSend; + pendingSelectTime = Minecraft.getSystemTime(); + } + + private void updateScrollAnimation() { + if (scrollOffset == 0f) return; + + long now = Minecraft.getSystemTime(); + float t = (float) (now - scrollStartTime) / SCROLL_DURATION; + t = Math.min(t, 1f); + + float eased = easeOutCubic(t); + float initialOffset = scrollOffset < 0 ? -1f : 1f; + scrollOffset = initialOffset * (1f - eased); + + if (t >= 1f) scrollOffset = 0f; + } + + private float easeOutCubic(float x) { + float v = 1 - x; + return 1 - v * v * v; + } + + public void refresh() { + updateAbilities(); + lastUpdateTime = Minecraft.getSystemTime(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java new file mode 100644 index 000000000..f23ac583a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java @@ -0,0 +1,262 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import noppes.npcs.config.ConfigClient; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.opengl.GL11; + +@SideOnly(Side.CLIENT) +public class AbilityHotbarSlotRenderer extends Gui { + private static final int CIRCLE_SEGMENTS = 32; + private static final long NAME_FADE_DURATION = 180; + + public int index; + public String abilityKey = null; + public Ability ability = null; + public IAbilityAction action = null; + private AbilityIcon icon = null; + + public boolean isSelected = false; + public float nameAlpha = 0f; + private boolean nameFadingIn = false; + private long nameFadeStartTime = 0; + + public AbilityHotbarSlotRenderer(int index) { + this.index = index; + } + + public void setAbility(String key, Ability ability, IAbilityAction action) { + this.abilityKey = key; + this.ability = ability; + this.action = action; + if (ability != null) { + this.icon = AbilityIcon.fromAbility(ability); + } else if (action instanceof ChainedAbility) { + this.icon = AbilityIcon.fromChainedAbility((ChainedAbility) action); + } else { + this.icon = null; + } + } + + public void drawCarousel(Minecraft mc, ScaledResolution sr, float cooldownProgress, + int cx, int cy, int size, boolean isCenter, float slotAlpha) { + float nameAlpha = this.nameAlpha; + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + if (size <= 0 || slotAlpha <= 0) return; + float radius = size / 2f; + float baseAlpha = isCenter ? 0.9f : 0.6f; + float alpha = baseAlpha * slotAlpha; + + GL11.glPushMatrix(); + GL11.glTranslatef(cx, cy, 0); + + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + if (altTexture) { + drawRoundedRect(-radius, -radius, radius, radius, 0.6f, 0.6f, 0.6f, 0.75f * alpha, false); + if (isCenter) { + drawRoundedRect(-radius, -radius, radius, radius, 0.8f, 0.8f, 0.2f, alpha, true); + } else { + drawRoundedRect(-radius, -radius, radius, radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true); + } + } else { + if (isCenter) { + drawCircle(radius, 0.8f, 0.8f, 0.2f, 0.66f * alpha, false); + drawCircle(radius, 0.8f, 0.8f, 0.2f, alpha, true); + } else { + drawCircle(radius, 1f, 1f, 1f, 0.66f * alpha, false); + drawCircle(radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true); + } + } + + // Ability icon + if (icon != null) { + GL11.glPushMatrix(); + float targetSize = size * 0.55f; + float iconNaturalSize = Math.max(icon.width, icon.height); + if (iconNaturalSize <= 0) iconNaturalSize = 16f; + float iconScale = targetSize / iconNaturalSize; + GL11.glScalef(iconScale, iconScale, 1); + GL11.glColor4f(1, 1, 1, slotAlpha); + icon.draw(getToggleState()); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + + // Cooldown arc + if (cooldownProgress > 0 && abilityKey != null) { + drawCooldownArc(radius, cooldownProgress); + } + + GL11.glPopMatrix(); + + // Ability name on center slot (respects text position config) + int textPos = ConfigClient.AbilityHotbarTextPosition; + if (textPos != 0 && isCenter && action != null && nameAlpha > 0) { + FontRenderer fr = mc.fontRenderer; + String name = getAbilityName(); + if (name != null && !name.isEmpty()) { + int a = (int) (nameAlpha * 255) & 0xFF; + int nameColor = (a << 24) | (getNameColor() & 0x00FFFFFF); + int nameX, nameY; + if (isHorizontal) { + nameX = cx - fr.getStringWidth(name) / 2; + if (textPos == 1) { + nameY = cy - (int) radius - fr.FONT_HEIGHT - 2; // Above + } else { + nameY = cy + (int) radius + 2; // Below + } + } else { + nameY = cy - fr.FONT_HEIGHT / 2; + if (textPos == 1) { + nameX = cx - (int) radius - fr.getStringWidth(name) - 4; // Left + } else { + nameX = cx + (int) radius + 4; // Right + } + } + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, nameAlpha); + fr.drawStringWithShadow(name, nameX, nameY, nameColor); + GL11.glDisable(GL11.GL_BLEND); + GL11.glColor4f(1, 1, 1, 1); + } + } + } + + private void drawRoundedRect(float x1, float y1, float x2, float y2, + float r, float g, float b, float a, boolean outline) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(r, g, b, a); + + if (outline) { + GL11.glLineWidth(2.0f); + GL11.glBegin(GL11.GL_LINE_LOOP); + } else { + GL11.glBegin(GL11.GL_QUADS); + } + + GL11.glVertex2f(x1, y1); + GL11.glVertex2f(x2, y1); + GL11.glVertex2f(x2, y2); + GL11.glVertex2f(x1, y2); + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawCircle(float radius, float r, float g, float b, float a, boolean outline) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(r, g, b, a); + + if (outline) { + GL11.glLineWidth(1.5f); + GL11.glBegin(GL11.GL_LINE_LOOP); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + } + + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawCooldownArc(float radius, float progress) { + progress = Math.min(1, Math.max(0, progress)); + if (progress <= 0) return; + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(0.1f, 0.1f, 0.1f, 0.7f); + + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + int steps = (int) (CIRCLE_SEGMENTS * progress) + 1; + for (int i = 0; i <= steps; i++) { + double angle = -Math.PI / 2 + 2 * Math.PI * i * progress / steps; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private String getAbilityName() { + if (ability != null) { + int state = getToggleState(); + if (state > 0) { + String label = ability.getToggleStateLabel(state); + if (label != null) return label; + } + return ability.getDisplayName(); + } + if (action instanceof ChainedAbility) return ((ChainedAbility) action).getDisplayName(); + return action != null ? action.getName() : ""; + } + + private int getToggleState() { + if (ability == null || !ability.isToggleable()) return 0; + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer == null) return 0; + PlayerData playerData = PlayerData.get(mc.thePlayer); + if (playerData == null || playerData.abilityData == null) return 0; + return playerData.abilityData.getToggleState(abilityKey); + } + + private int getNameColor() { + if (ability != null && ability.isToggleable()) { + return getToggleState() > 0 ? 0xFF55FF55 : 0xFFFF5555; + } + return 0xFFFFFFFF; + } + + public void setSelectedState(boolean newSelectState) { + if (!isSelected && newSelectState) { + nameFadingIn = true; + nameFadeStartTime = Minecraft.getSystemTime(); + } + if (isSelected && !newSelectState) { + nameFadingIn = false; + nameFadeStartTime = Minecraft.getSystemTime(); + } + isSelected = newSelectState; + } + + public void updateNameFade() { + long now = Minecraft.getSystemTime(); + float t = (float) (now - nameFadeStartTime) / NAME_FADE_DURATION; + t = Math.min(1f, Math.max(0f, t)); + if (nameFadingIn) { + nameAlpha = t; + } else { + nameAlpha = 1f - t; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java new file mode 100644 index 000000000..1371bcc2a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java @@ -0,0 +1,140 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityIconData; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.ImageData; +import org.lwjgl.opengl.GL11; + +@SideOnly(Side.CLIENT) +public class AbilityIcon extends Gui { + private static final ResourceLocation FALLBACK_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/ability_fallback.png"); + + // Backed by AbilityIconData + private final AbilityIconData data; + public int width; + public int height; + + private AbilityIcon(AbilityIconData data) { + this.data = data; + this.width = data.width; + this.height = data.height; + } + + public static AbilityIcon fromAbility(Ability ability) { + if (ability != null) { + return new AbilityIcon(AbilityIconData.fromAbility(ability)); + } + return fromDefaults(); + } + + public static AbilityIcon fromChainedAbility(ChainedAbility chain) { + if (chain != null) { + return new AbilityIcon(AbilityIconData.fromChainedAbility(chain)); + } + return fromDefaults(); + } + + public static AbilityIcon fromAction(IAbilityAction action) { + if (action instanceof Ability) return fromAbility((Ability) action); + if (action instanceof ChainedAbility) return fromChainedAbility((ChainedAbility) action); + return fromDefaults(); + } + + private static AbilityIcon fromDefaults() { + return new AbilityIcon(AbilityIconData.fromCustomData(new NBTTagCompound())); + } + + public void draw() { + draw(0); + } + + public void draw(int state) { + TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; + + ImageData imageData = null; + if (data.hasTexture()) { + imageData = ClientCacheHandler.getImageData(data.texture); + } + + GL11.glPushMatrix(); + GL11.glColor4f(1, 1, 1, 1); + + Tessellator t; + + if (imageData == null || !imageData.imageLoaded()) { + GL11.glScalef(1.0f, 1.0f, 1); + renderEngine.bindTexture(FALLBACK_TEXTURE); + t = getFallbackTessellator(); + } else { + GL11.glScalef(data.scale, data.scale, 1); + renderEngine.bindTexture(imageData.getLocation()); + t = getTessellator(imageData, state); + } + + t.draw(); + GL11.glPopMatrix(); + } + + private Tessellator getTessellator(ImageData imageData, int state) { + float hw = data.width / 2f; + float hh = data.height / 2f; + + float texW = imageData.getTotalWidth(); + float texH = imageData.getTotalHeight(); + + int ix = data.getIconXForState(state); + int iy = data.getIconYForState(state); + + float u1 = ix / texW; + float v1 = iy / texH; + float u2 = (ix + data.width) / texW; + float v2 = (iy + data.height) / texH; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, u1, v2); + t.addVertexWithUV(hw, hh, zLevel, u2, v2); + t.addVertexWithUV(hw, -hh, zLevel, u2, v1); + t.addVertexWithUV(-hw, -hh, zLevel, u1, v1); + return t; + } + + private Tessellator getFallbackTessellator() { + float hw = 16f; + float hh = 16f; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, 0, 1); + t.addVertexWithUV(hw, hh, zLevel, 1, 1); + t.addVertexWithUV(hw, -hh, zLevel, 1, 0); + t.addVertexWithUV(-hw, -hh, zLevel, 0, 0); + return t; + } + + public boolean hasTexture() { + return data.hasTexture(); + } + + /** + * Returns the approximate visual size (max dimension) that draw() produces. + * Textured: max(width,height) * scale. Fallback: 32. + */ + public float getDrawSize() { + if (data.hasTexture()) { + return Math.max(width, height) * data.scale; + } + return 32f; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java new file mode 100644 index 000000000..0f66036ae --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java @@ -0,0 +1,984 @@ +package noppes.npcs.client.gui.player.inventory; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityTogglePacket; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.hud.ability.AbilityIcon; +import noppes.npcs.client.gui.util.GuiMenuTopButton; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import tconstruct.client.tabs.AbstractTab; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener { + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/standardbg.png"); + + // Sub-tab: 0 = Abilities, 1 = Toggles + private int subTab = 0; + private static final int BTN_TAB_ABILITIES = -200; + private static final int BTN_TAB_TOGGLES = -201; + + // ═══ Panel Bounds (relative to guiLeft/guiTop) ═══ + // Selection panel (RIGHT side - icon grid) + private int selLeft = 140; + private int selTop = 4; + private int selRight = 316; + private int selBottom = 150; + + // Information panel (LEFT side - ability details) + private int infoLeft = 5; + private int infoTop = 4; + private int infoRight = 137; + private int infoBottom = 150; + + // Hotbar panel (BOTTOM) + private int hbLeft = 5; + private int hbTop = 153; + private int hbRight = 316; + private int hbBottom = 190; + + // ═══ Grid Settings ═══ + private int gridPad = 3; + private int gridCellSize = 22; + private int gridCols = 7; + + // ═══ Hotbar Settings ═══ + private int hbSlotSize = 18; + private int hbSlotGap = 2; + private int hbSlots = AbilityHotbarData.TOTAL_SLOTS; + + // ═══ Info Panel Settings ═══ + private int infoPad = 5; + private int infoIconSize = 40; + + // ═══ Drag Settings ═══ + private int dragThreshold = 3; + + // ═══ Filtered ability data ═══ + private List filteredKeys = new ArrayList<>(); + private List filteredDisplayNames = new ArrayList<>(); + private List filteredIcons = new ArrayList<>(); + private List filteredAbilities = new ArrayList<>(); + private List filteredActions = new ArrayList<>(); + + // ═══ Grid state ═══ + private int scrollRow = 0; + private int hoveredGridIndex = -1; + private float[] gridHoverScale; + private int selectedIndex = -1; + + // ═══ Detail panel cache ═══ + private AbilityIcon cachedDetailIcon = null; + private int cachedDetailIndex = -1; + + // ═══ Hotbar state ═══ + private int hoveredSlotIndex = -1; + private AbilityIcon[] hotbarIcons = new AbilityIcon[AbilityHotbarData.TOTAL_SLOTS]; + + // ═══ Drag state ═══ + private boolean isDragging = false; + private boolean dragPending = false; + private String draggedKey = null; + private AbilityIcon draggedIcon = null; + private int dragSourceSlot = -1; + private int dragStartX, dragStartY; + private int dragMouseX, dragMouseY; + + // ═══ Close sync ═══ + private String initialSelectedKey = null; + + // ═══ Toggle double-tap ═══ + private long lastToggleClickTime = 0; + private int lastToggleClickIndex = -1; + + public GuiAbilities() { + super(); + xSize = 280; + ySize = 180; + + hbSlotSize = 23; + gridCellSize = 24; + gridCols = 7; + } + + @Override + public void initGui() { + super.initGui(); + + GuiMenuTopButton tabAbilities = new GuiMenuTopButton(BTN_TAB_ABILITIES, guiLeft + xSize - 10, guiTop - 17, "gui.abilities"); + tabAbilities.active = (subTab == 0); + addTopButton(tabAbilities); + + GuiMenuTopButton tabToggles = new GuiMenuTopButton(BTN_TAB_TOGGLES, "gui.toggles", tabAbilities); + tabToggles.active = (subTab == 1); + addTopButton(tabToggles); + + buildFilteredList(); + updateHotbarIcons(); + + // Capture initial selected key for close sync + if (initialSelectedKey == null) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + initialSelectedKey = playerData.abilityData.getSelectedAbilityKey(); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Data Building + // ═══════════════════════════════════════════════════════════════════ + + private void buildFilteredList() { + filteredKeys.clear(); + filteredDisplayNames.clear(); + filteredIcons.clear(); + filteredAbilities.clear(); + filteredActions.clear(); + cachedDetailIcon = null; + cachedDetailIndex = -1; + + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) return; + + List abilities = playerData.abilityData.getUnlockedAbilityList(); + + // Build temporary lists before sorting + List tempKeys = new ArrayList<>(); + List tempNames = new ArrayList<>(); + List tempIcons = new ArrayList<>(); + List tempAbilities = new ArrayList<>(); + List tempActions = new ArrayList<>(); + + for (String key : abilities) { + Ability ability = null; + IAbilityAction action = null; + + if (key.startsWith(AbilityHotbarData.CHAIN_PREFIX)) { + String chainKey = key.substring(AbilityHotbarData.CHAIN_PREFIX.length()); + if (AbilityController.Instance != null) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey); + action = chain; + } + } else if (AbilityController.Instance != null) { + ability = AbilityController.Instance.resolveAbility(key); + action = ability; + } + + boolean isToggle = ability != null && ability.isToggleable(); + if (subTab == 0 && isToggle) continue; + if (subTab == 1 && !isToggle) continue; + + String displayName; + if (action instanceof ChainedAbility) { + displayName = "\u00A76\u2726 " + ((ChainedAbility) action).getDisplayName(); + } else if (ability != null) { + displayName = ability.getDisplayName(); + } else { + displayName = key; + } + + tempKeys.add(key); + tempNames.add(displayName); + tempIcons.add(AbilityIcon.fromAction(action)); + tempAbilities.add(ability); + tempActions.add(action); + } + + // Sort: toggles tab sorts enabled first, then alphabetically + List indices = new ArrayList<>(); + for (int i = 0; i < tempNames.size(); i++) indices.add(i); + final boolean sortTogglesFirst = (subTab == 1); + Collections.sort(indices, new Comparator() { + @Override + public int compare(Integer a, Integer b) { + if (sortTogglesFirst && playerData != null && playerData.abilityData != null) { + boolean aToggled = playerData.abilityData.isAbilityToggled(tempKeys.get(a)); + boolean bToggled = playerData.abilityData.isAbilityToggled(tempKeys.get(b)); + if (aToggled != bToggled) return aToggled ? -1 : 1; + } + return stripFormatting(tempNames.get(a)).compareToIgnoreCase(stripFormatting(tempNames.get(b))); + } + }); + + for (int idx : indices) { + filteredKeys.add(tempKeys.get(idx)); + filteredDisplayNames.add(tempNames.get(idx)); + filteredIcons.add(tempIcons.get(idx)); + filteredAbilities.add(tempAbilities.get(idx)); + filteredActions.add(tempActions.get(idx)); + } + + gridHoverScale = new float[filteredKeys.size()]; + Arrays.fill(gridHoverScale, 1.0f); + scrollRow = 0; + selectedIndex = -1; + } + + private String stripFormatting(String s) { + return s.replaceAll("\u00A7.", "").trim(); + } + + private void updateHotbarIcons() { + PlayerData playerData = ClientCacheHandler.playerData; + for (int i = 0; i < hbSlots; i++) { + hotbarIcons[i] = null; + if (playerData == null || playerData.hotbarData == null) continue; + AbilityHotbarData slotData = playerData.hotbarData.getSlot(i); + if (slotData == null || slotData.isEmpty()) continue; + + if (AbilityController.Instance != null) { + if (slotData.isChainKey()) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + if (chain != null) hotbarIcons[i] = AbilityIcon.fromChainedAbility(chain); + } else { + Ability ability = AbilityController.Instance.resolveAbility(slotData.abilityKey); + if (ability != null) hotbarIcons[i] = AbilityIcon.fromAbility(ability); + } + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Grid Positioning Helpers + // ═══════════════════════════════════════════════════════════════════ + + private int getGridVisibleRows() { + int usableHeight = (selBottom - selTop) - gridPad * 2; + return usableHeight / gridCellSize; + } + + private int getGridStartX() { + int panelWidth = selRight - selLeft; + int usableWidth = panelWidth - gridPad * 2; + int gridWidth = gridCols * gridCellSize; + int offsetX = (usableWidth - gridWidth) / 2; + return guiLeft + selLeft + gridPad + offsetX; + } + + private int getGridStartY() { + int panelHeight = selBottom - selTop; + int usableHeight = panelHeight - gridPad * 2; + int visibleRows = getGridVisibleRows(); + int gridHeight = visibleRows * gridCellSize; + int offsetY = (usableHeight - gridHeight) / 2; + return guiTop + selTop + gridPad + offsetY; + } + + private int getMaxScrollRow() { + int totalRows = (filteredKeys.size() + gridCols - 1) / gridCols; + return Math.max(0, totalRows - getGridVisibleRows()); + } + + // ═══════════════════════════════════════════════════════════════════ + // Drawing + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.renderEngine.bindTexture(resource); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, 252, 195); + drawTexturedModalRect(guiLeft + 252, guiTop, 188, 0, 67, 195); + super.drawScreen(mouseX, mouseY, partialTicks); + + updateHoverState(mouseX, mouseY); + updateHoverScales(); + + // Panel backgrounds + drawGradientRect(guiLeft + selLeft, guiTop + selTop, guiLeft + selRight, guiTop + selBottom, 0xC0101010, 0xC0101010); + drawGradientRect(guiLeft + infoLeft, guiTop + infoTop, guiLeft + infoRight, guiTop + infoBottom, 0xC0101010, 0xC0101010); + drawGradientRect(guiLeft + hbLeft, guiTop + hbTop, guiLeft + hbRight, guiTop + hbBottom, 0xC0101010, 0xC0101010); + + // RIGHT panel: Selection grid (with scissor clipping) + drawIconGrid(mouseX, mouseY); + + // LEFT panel: Ability information + drawInfoPanel(); + + // BOTTOM panel: Hotbar + drawHotbarSection(mouseX, mouseY); + + // Drag ghost + if (isDragging && draggedIcon != null) { + drawDragGhost(mouseX, mouseY); + } + + // Tooltip (last - renders on top) + drawTooltip(mouseX, mouseY); + } + + private void drawIconGrid(int mouseX, int mouseY) { + int visibleRows = getGridVisibleRows(); + int gridStartX = getGridStartX(); + int gridStartY = getGridStartY(); + int startIndex = scrollRow * gridCols; + + // GL Scissor to clip grid content within the selection panel + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + int scissorX = (guiLeft + selLeft) * scaleFactor; + int scissorY = mc.displayHeight - (guiTop + selBottom) * scaleFactor; + int scissorW = (selRight - selLeft) * scaleFactor; + int scissorH = (selBottom - selTop) * scaleFactor; + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(scissorX, scissorY, scissorW, scissorH); + + int maxVisibleCount = gridCols * visibleRows; + for (int vi = 0; vi < maxVisibleCount; vi++) { + int absIndex = startIndex + vi; + if (absIndex >= filteredKeys.size()) break; + + int col = vi % gridCols; + int row = vi / gridCols; + int cellX = gridStartX + col * gridCellSize; + int cellY = gridStartY + row * gridCellSize; + + boolean isHovered = (hoveredGridIndex == absIndex) && !isDragging; + boolean isSelected = (selectedIndex == absIndex); + boolean isDragSource = isDragging && dragSourceSlot == -1 && draggedKey != null + && draggedKey.equals(filteredKeys.get(absIndex)); + + // Cell background + int bgColor; + if (isDragSource) bgColor = 0x40333333; + else if (isSelected) bgColor = 0x60505070; + else if (isHovered) bgColor = 0x60404060; + else bgColor = 0x40202030; + drawRect(cellX, cellY, cellX + gridCellSize - 1, cellY + gridCellSize - 1, bgColor); + + // Cell border + int borderColor; + if (isSelected) borderColor = 0xAA9999DD; + else if (isHovered) borderColor = 0xAA8888CC; + else borderColor = 0x40404060; + drawHorizontalLine(cellX, cellX + gridCellSize - 2, cellY, borderColor); + drawHorizontalLine(cellX, cellX + gridCellSize - 2, cellY + gridCellSize - 2, borderColor); + drawVerticalLine(cellX, cellY, cellY + gridCellSize - 2, borderColor); + drawVerticalLine(cellX + gridCellSize - 2, cellY, cellY + gridCellSize - 2, borderColor); + + GL11.glColor4f(1, 1, 1, 1); + + // Icon (state-aware for multi-state toggles) + AbilityIcon icon = filteredIcons.get(absIndex); + if (icon != null) { + float hoverScale = gridHoverScale[absIndex]; + float targetPixels = (gridCellSize - 4) * hoverScale; + float drawSize = icon.getDrawSize(); + float iconScale = targetPixels / drawSize; + + int iconCenterX = cellX + (gridCellSize - 1) / 2; + int iconCenterY = cellY + (gridCellSize - 1) / 2; + + int cellToggleState = 0; + Ability cellAbility = filteredAbilities.get(absIndex); + PlayerData cellPlayerData = ClientCacheHandler.playerData; + if (cellAbility != null && cellAbility.isToggleable() && cellPlayerData != null && cellPlayerData.abilityData != null) { + cellToggleState = cellPlayerData.abilityData.getToggleState(filteredKeys.get(absIndex)); + } + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCenterX, iconCenterY, 0); + GL11.glScalef(iconScale, iconScale, 1); + + float alpha = isDragSource ? 0.3f : 1.0f; + GL11.glColor4f(1, 1, 1, alpha); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + icon.draw(cellToggleState); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + } + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Restore GL state + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + // Scroll indicator (drawn outside scissor) + int totalRows = (filteredKeys.size() + gridCols - 1) / gridCols; + if (totalRows > visibleRows) { + FontRenderer fr = mc.fontRenderer; + String scrollText = (scrollRow + 1) + "/" + (totalRows - visibleRows + 1); + int textX = guiLeft + selRight - fr.getStringWidth(scrollText) - 4; + int textY = guiTop + selBottom + 1; + fr.drawStringWithShadow(scrollText, textX, textY, 0x888888); + } + } + + private void drawInfoPanel() { + int infoIndex = hoveredGridIndex >= 0 ? hoveredGridIndex : selectedIndex; + if (infoIndex < 0 || infoIndex >= filteredKeys.size()) return; + + FontRenderer fr = mc.fontRenderer; + int panelInnerLeft = guiLeft + infoLeft + infoPad; + int panelInnerTop = guiTop + infoTop + infoPad; + int panelInnerWidth = (infoRight - infoLeft) - infoPad * 2; + int y = panelInnerTop; + + // Cached icon for detail preview + if (cachedDetailIndex != infoIndex) { + cachedDetailIcon = filteredIcons.get(infoIndex); + cachedDetailIndex = infoIndex; + } + + // Get toggle state for icon rendering and state display + int toggleState = 0; + PlayerData togglePlayerData = ClientCacheHandler.playerData; + Ability infoAbility = filteredAbilities.get(infoIndex); + if (infoAbility != null && infoAbility.isToggleable() && togglePlayerData != null && togglePlayerData.abilityData != null) { + toggleState = togglePlayerData.abilityData.getToggleState(filteredKeys.get(infoIndex)); + } + + // Preview icon (centered, state-aware for multi-state toggles) + if (cachedDetailIcon != null) { + float drawSize = cachedDetailIcon.getDrawSize(); + float iconScale = (float) infoIconSize / drawSize; + + int iconCX = panelInnerLeft + panelInnerWidth / 2; + int iconCY = y + infoIconSize / 2 + 4; + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCX, iconCY, 0); + GL11.glScalef(iconScale, iconScale, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, 1); + cachedDetailIcon.draw(toggleState); + GL11.glPopMatrix(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + y += infoIconSize + 12; + } + + // Ability name (centered, wrapped) + String name = filteredDisplayNames.get(infoIndex); + List nameLines = fr.listFormattedStringToWidth(name, panelInnerWidth); + for (String line : nameLines) { + int lineX = panelInnerLeft + (panelInnerWidth - fr.getStringWidth(line)) / 2; + fr.drawStringWithShadow(line, lineX, y, 0xFFFFFF); + y += fr.FONT_HEIGHT + 1; + } + y += 4; + + // Type info + Ability ability = filteredAbilities.get(infoIndex); + if (ability != null) { + String typeId = ability.getTypeId(); + if (typeId != null && !typeId.isEmpty()) { + String translated = StatCollector.translateToLocal(typeId); + if (!translated.equals(typeId)) { + int textW = fr.getStringWidth(translated); + fr.drawStringWithShadow("\u00A77" + translated, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xAAAAAA); + y += fr.FONT_HEIGHT + 3; + } + } + + if (ability.isToggleable()) { + String toggleText = "[" + StatCollector.translateToLocal("gui.toggle") + "]"; + int textW = fr.getStringWidth(toggleText); + fr.drawStringWithShadow("\u00A7a" + toggleText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FF55); + y += fr.FONT_HEIGHT + 3; + } + + // Toggle state (uses pre-computed toggleState) + if (ability.isToggleable()) { + String stateText; + String prefix; + if (toggleState > 0) { + // Active — check for state label (multi-state toggles like Ki Weapon) + String stateLabel = ability.getToggleStateLabel(toggleState); + stateText = stateLabel != null ? stateLabel : StatCollector.translateToLocal("gui.toggle.active"); + prefix = "\u00A72"; + } else { + stateText = StatCollector.translateToLocal("gui.toggle.inactive"); + prefix = "\u00A78"; + } + int textW = fr.getStringWidth(stateText); + fr.drawStringWithShadow(prefix + stateText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, toggleState > 0 ? 0x55FF55 : 0x888888); + } + } + } + + private void drawHotbarSection(int mouseX, int mouseY) { + FontRenderer fr = mc.fontRenderer; + + // Get selected ability key for yellow border + PlayerData selPlayerData = ClientCacheHandler.playerData; + String selectedKey = null; + if (selPlayerData != null && selPlayerData.abilityData != null) { + selectedKey = selPlayerData.abilityData.getSelectedAbilityKey(); + } + + // Hotbar slots centered within the panel + int panelWidth = hbRight - hbLeft; + int panelHeight = hbBottom - hbTop; + int totalSlotsWidth = hbSlots * (hbSlotSize + hbSlotGap) - hbSlotGap; + int hotbarStartX = guiLeft + hbLeft + (panelWidth - totalSlotsWidth) / 2; + int hotbarStartY = guiTop + hbTop + (panelHeight - hbSlotSize) / 2; + + for (int i = 0; i < hbSlots; i++) { + int sx = hotbarStartX + i * (hbSlotSize + hbSlotGap); + int sy = hotbarStartY; + + boolean isHovered = (hoveredSlotIndex == i); + boolean isDragHover = isDragging && isHovered; + + // Check if this slot's ability is the currently selected one + boolean isSelectedSlot = false; + if (selectedKey != null && !selectedKey.isEmpty() && selPlayerData.hotbarData != null) { + AbilityHotbarData slotData = selPlayerData.hotbarData.getSlot(i); + if (slotData != null && !slotData.isEmpty() && selectedKey.equals(slotData.abilityKey)) { + isSelectedSlot = true; + } + } + + // Slot background + int bgColor = isDragHover ? 0x80606030 : (isSelectedSlot ? 0x60505020 : (isHovered ? 0x60505050 : 0x50303030)); + drawRect(sx, sy, sx + hbSlotSize, sy + hbSlotSize, bgColor); + + // Slot border - yellow for selected, drag color, hover color, or default + int borderColor; + if (isDragHover) borderColor = 0xFFCCCC44; + else if (isSelectedSlot) borderColor = 0xFFCCCC00; + else if (isHovered) borderColor = 0xAA888888; + else borderColor = 0x60505050; + drawHorizontalLine(sx, sx + hbSlotSize - 1, sy, borderColor); + drawHorizontalLine(sx, sx + hbSlotSize - 1, sy + hbSlotSize - 1, borderColor); + drawVerticalLine(sx, sy, sy + hbSlotSize - 1, borderColor); + drawVerticalLine(sx + hbSlotSize - 1, sy, sy + hbSlotSize - 1, borderColor); + + GL11.glColor4f(1, 1, 1, 1); + + // Icon or slot number + AbilityIcon icon = hotbarIcons[i]; + boolean isSourceSlot = isDragging && dragSourceSlot == i; + + if (icon != null && !isSourceSlot) { + int iconCX = sx + hbSlotSize / 2; + int iconCY = sy + hbSlotSize / 2; + float targetPixels = hbSlotSize - 4; + float drawSize = icon.getDrawSize(); + float s = targetPixels / drawSize; + + // Compute toggle state for this hotbar slot's ability + int hbToggleState = 0; + if (selPlayerData != null && selPlayerData.abilityData != null && selPlayerData.hotbarData != null) { + AbilityHotbarData slotData = selPlayerData.hotbarData.getSlot(i); + if (slotData != null && !slotData.isEmpty()) { + hbToggleState = selPlayerData.abilityData.getToggleState(slotData.abilityKey); + } + } + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCX, iconCY, 0); + GL11.glScalef(s, s, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + icon.draw(hbToggleState); + GL11.glPopMatrix(); + GL11.glColor4f(1, 1, 1, 1); + } else { + String slotLabel = String.valueOf(i + 1); + int labelColor = isSourceSlot ? 0x333333 : 0x666666; + int lx = sx + (hbSlotSize - fr.getStringWidth(slotLabel)) / 2; + int ly = sy + (hbSlotSize - fr.FONT_HEIGHT) / 2 + 1; + fr.drawString(slotLabel, lx, ly, labelColor); + } + } + + // Restore GL + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawDragGhost(int mouseX, int mouseY) { + if (draggedIcon == null) return; + + float targetPixels = gridCellSize; + float drawSize = draggedIcon.getDrawSize(); + float ghostScale = targetPixels / drawSize; + + GL11.glPushMatrix(); + GL11.glTranslatef(mouseX, mouseY, 100); + GL11.glScalef(ghostScale, ghostScale, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, 0.8f); + draggedIcon.draw(0); + GL11.glColor4f(1, 1, 1, 1); + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawTooltip(int mouseX, int mouseY) { + if (isDragging) return; + + if (hoveredGridIndex >= 0 && hoveredGridIndex < filteredDisplayNames.size()) { + List lines = new ArrayList<>(); + lines.add(filteredDisplayNames.get(hoveredGridIndex)); + + Ability ability = filteredAbilities.get(hoveredGridIndex); + if (ability != null) { + String typeId = ability.getTypeId(); + if (typeId != null && !typeId.isEmpty()) { + String translated = StatCollector.translateToLocal(typeId); + if (!translated.equals(typeId)) { + lines.add("\u00A77" + translated); + } + } + if (ability.isToggleable()) { + lines.add("\u00A7a[" + StatCollector.translateToLocal("gui.toggle") + "]"); + } + } + + drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); + GL11.glDisable(GL11.GL_LIGHTING); + } + + if (hoveredSlotIndex >= 0 && hoveredSlotIndex < hbSlots) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slotData = playerData.hotbarData.getSlot(hoveredSlotIndex); + if (slotData != null && !slotData.isEmpty()) { + String name = getHotbarSlotDisplayName(slotData); + if (name != null) { + List lines = new ArrayList<>(); + lines.add(name); + lines.add("\u00A78Right-click to remove"); + drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); + GL11.glDisable(GL11.GL_LIGHTING); + } + } + } + } + } + + private String getHotbarSlotDisplayName(AbilityHotbarData slotData) { + if (AbilityController.Instance == null) return null; + if (slotData.isChainKey()) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + return chain != null ? chain.getDisplayName() : null; + } + Ability ability = AbilityController.Instance.resolveAbility(slotData.abilityKey); + return ability != null ? ability.getDisplayName() : null; + } + + // ═══════════════════════════════════════════════════════════════════ + // Hover & Animation + // ═══════════════════════════════════════════════════════════════════ + + private void updateHoverState(int mouseX, int mouseY) { + hoveredGridIndex = -1; + hoveredSlotIndex = -1; + + // Grid hit test (RIGHT panel - selection) + int visibleRows = getGridVisibleRows(); + int gridStartX = getGridStartX(); + int gridStartY = getGridStartY(); + int startIndex = scrollRow * gridCols; + + if (mouseX >= guiLeft + selLeft && mouseX < guiLeft + selRight + && mouseY >= guiTop + selTop && mouseY < guiTop + selBottom) { + for (int vi = 0; vi < gridCols * visibleRows; vi++) { + int absIndex = startIndex + vi; + if (absIndex >= filteredKeys.size()) break; + + int col = vi % gridCols; + int row = vi / gridCols; + int cellX = gridStartX + col * gridCellSize; + int cellY = gridStartY + row * gridCellSize; + + if (mouseX >= cellX && mouseX < cellX + gridCellSize - 1 + && mouseY >= cellY && mouseY < cellY + gridCellSize - 1) { + hoveredGridIndex = absIndex; + break; + } + } + } + + // Hotbar hit test + int panelWidth = hbRight - hbLeft; + int panelHeight = hbBottom - hbTop; + int totalSlotsWidth = hbSlots * (hbSlotSize + hbSlotGap) - hbSlotGap; + int hotbarStartX = guiLeft + hbLeft + (panelWidth - totalSlotsWidth) / 2; + int hotbarStartY = guiTop + hbTop + (panelHeight - hbSlotSize) / 2; + + for (int i = 0; i < hbSlots; i++) { + int sx = hotbarStartX + i * (hbSlotSize + hbSlotGap); + if (mouseX >= sx && mouseX < sx + hbSlotSize + && mouseY >= hotbarStartY && mouseY < hotbarStartY + hbSlotSize) { + hoveredSlotIndex = i; + break; + } + } + } + + private void updateHoverScales() { + if (gridHoverScale == null) return; + for (int i = 0; i < gridHoverScale.length; i++) { + float target = (i == hoveredGridIndex && !isDragging) ? 1.12f : 1.0f; + gridHoverScale[i] += (target - gridHoverScale[i]) * 0.3f; + if (Math.abs(gridHoverScale[i] - target) < 0.005f) { + gridHoverScale[i] = target; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Mouse Handlers + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void mouseClicked(int mouseX, int mouseY, int button) { + if (hasSubGui()) { + super.mouseClicked(mouseX, mouseY, button); + return; + } + + // Right-click on hotbar slot -> clear + if (button == 1 && hoveredSlotIndex >= 0) { + saveHotbarSlot(hoveredSlotIndex, ""); + updateHotbarIcons(); + return; + } + + // Left-click: start potential drag or select + if (button == 0) { + if (hoveredGridIndex >= 0 && hoveredGridIndex < filteredKeys.size()) { + // Toggle double-tap detection on toggle tab + if (subTab == 1) { + long now = System.currentTimeMillis(); + if (lastToggleClickIndex == hoveredGridIndex && (now - lastToggleClickTime) < 400) { + String key = filteredKeys.get(hoveredGridIndex); + Ability ability = filteredAbilities.get(hoveredGridIndex); + if (ability != null && ability.isToggleable()) { + PacketHandler.Instance.sendToServer(new AbilityTogglePacket(key)); + lastToggleClickIndex = -1; + lastToggleClickTime = 0; + // Rebuild list after a short delay to reflect new state + // For now just select and return - the list rebuilds on next initGui + selectedIndex = hoveredGridIndex; + cachedDetailIcon = null; + cachedDetailIndex = -1; + return; + } + } + lastToggleClickIndex = hoveredGridIndex; + lastToggleClickTime = now; + } + + selectedIndex = hoveredGridIndex; + cachedDetailIcon = null; + cachedDetailIndex = -1; + dragPending = true; + draggedKey = filteredKeys.get(hoveredGridIndex); + draggedIcon = filteredIcons.get(hoveredGridIndex); + dragSourceSlot = -1; + dragStartX = mouseX; + dragStartY = mouseY; + return; + } + + if (hoveredSlotIndex >= 0 && hotbarIcons[hoveredSlotIndex] != null) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slotData = playerData.hotbarData.getSlot(hoveredSlotIndex); + if (slotData != null && !slotData.isEmpty()) { + dragPending = true; + draggedKey = slotData.abilityKey; + draggedIcon = hotbarIcons[hoveredSlotIndex]; + dragSourceSlot = hoveredSlotIndex; + dragStartX = mouseX; + dragStartY = mouseY; + return; + } + } + } + } + + super.mouseClicked(mouseX, mouseY, button); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int button, long timeSinceLastClick) { + if (dragPending && !isDragging) { + int dx = mouseX - dragStartX; + int dy = mouseY - dragStartY; + if (dx * dx + dy * dy > dragThreshold * dragThreshold) { + isDragging = true; + } + } + if (isDragging) { + dragMouseX = mouseX; + dragMouseY = mouseY; + } + + super.mouseClickMove(mouseX, mouseY, button, timeSinceLastClick); + } + + @Override + protected void mouseMovedOrUp(int mouseX, int mouseY, int state) { + if (isDragging && draggedKey != null) { + updateHoverState(mouseX, mouseY); + + if (hoveredSlotIndex >= 0) { + if (dragSourceSlot >= 0) { + swapHotbarSlots(dragSourceSlot, hoveredSlotIndex); + } else { + saveHotbarSlot(hoveredSlotIndex, draggedKey); + } + updateHotbarIcons(); + } else if (dragSourceSlot >= 0 && hoveredGridIndex >= 0) { + saveHotbarSlot(dragSourceSlot, ""); + updateHotbarIcons(); + } + } + + isDragging = false; + dragPending = false; + draggedKey = null; + draggedIcon = null; + dragSourceSlot = -1; + + super.mouseMovedOrUp(mouseX, mouseY, state); + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + + int wheel = Mouse.getEventDWheel(); + if (wheel != 0) { + int maxScroll = getMaxScrollRow(); + if (wheel > 0) { + scrollRow = Math.max(0, scrollRow - 1); + } else { + scrollRow = Math.min(maxScroll, scrollRow + 1); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Actions & Network + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void actionPerformed(GuiButton btn) { + if (btn instanceof AbstractTab) return; + + if (btn.id <= -100 && btn.id > -200) { + super.actionPerformed(btn); + return; + } + + if (btn.id == BTN_TAB_ABILITIES) { + subTab = 0; + initGui(); + return; + } + if (btn.id == BTN_TAB_TOGGLES) { + subTab = 1; + initGui(); + return; + } + } + + private void saveHotbarSlot(int slotIndex, String abilityKey) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slot = playerData.hotbarData.getSlot(slotIndex); + if (slot != null) { + slot.abilityKey = abilityKey; + } + } + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagCompound slotTag = new NBTTagCompound(); + slotTag.setInteger("slot", slotIndex); + slotTag.setString("abilityKey", abilityKey != null ? abilityKey : ""); + compound.setTag("AbilityHotbar" + slotIndex, slotTag); + PacketHandler.Instance.sendToServer(new AbilityHotbarSavePacket(slotIndex, compound)); + } + + private void swapHotbarSlots(int fromSlot, int toSlot) { + if (fromSlot == toSlot) return; + + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.hotbarData == null) return; + + AbilityHotbarData fromData = playerData.hotbarData.getSlot(fromSlot); + AbilityHotbarData toData = playerData.hotbarData.getSlot(toSlot); + if (fromData == null || toData == null) return; + + String fromKey = fromData.abilityKey; + String toKey = toData.abilityKey; + + saveHotbarSlot(fromSlot, toKey != null ? toKey : ""); + saveHotbarSlot(toSlot, fromKey != null ? fromKey : ""); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + // Send selection sync if changed + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + String currentKey = playerData.abilityData.getSelectedAbilityKey(); + boolean changed = (initialSelectedKey == null && currentKey != null && !currentKey.isEmpty()) + || (initialSelectedKey != null && !initialSelectedKey.equals(currentKey)); + if (changed) { + PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(currentKey != null ? currentKey : "")); + } + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (i == 1 || isInventoryKey(i)) { + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java index f27913d89..3e4b9706a 100644 --- a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java @@ -73,6 +73,14 @@ public class GuiCNPCInventory extends GuiNPCInterface { addSideButton(profileButton); } + y += 21; + GuiMenuSideButton abilitiesButton = new GuiMenuSideButton(-105, guiLeft + xSize + 37, this.guiTop + y, 22, 22, ""); + abilitiesButton.rightSided = true; + abilitiesButton.active = activeTab == -105; + abilitiesButton.renderIconPosX = 80; + abilitiesButton.renderResource = specialIcons; + addSideButton(abilitiesButton); + y += 21; GuiMenuSideButton clientButton = new GuiMenuSideButton(-103, guiLeft + xSize + 37, this.guiTop + y, 22, 22, ""); clientButton.rightSided = true; @@ -154,6 +162,10 @@ public class GuiCNPCInventory extends GuiNPCInterface { activeTab = -104; mc.displayGuiScreen(new GuiProfiles()); } + if (guibutton.id == -105 && activeTab != -105) { + activeTab = -105; + mc.displayGuiScreen(new GuiAbilities()); + } } } diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java b/src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java new file mode 100644 index 000000000..a3d85f7e4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java @@ -0,0 +1,155 @@ +package noppes.npcs.client.gui.player.inventory; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * SubGui for selecting an ability to assign to a hotbar slot. + */ +public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + private HashMap displayToKey = new HashMap<>(); + private GuiCustomScroll scrollAbilities; + private String selected = null; + private String search = ""; + + public boolean confirmed = false; + public String selectedAbilityKey = null; + public int slotIndex; + public boolean removeAbility = false; + + public SubGuiSelectAbilityForSlot(int slotIndex) { + this.slotIndex = slotIndex; + this.closeOnEsc = true; + this.drawDefaultBackground = true; + guiLeft -= 10; + xSize = 256 + 10; + this.setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + guiTop += 10; + + if (scrollAbilities == null) { + scrollAbilities = new GuiCustomScroll(this, 0, 0); + scrollAbilities.setSize(177, 185); + } + + scrollAbilities.guiLeft = guiLeft + 4; + scrollAbilities.guiTop = guiTop + 4; + addScroll(scrollAbilities); + + loadAbilities(); + scrollAbilities.setList(getSearchList()); + + addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 192, 177, 20, search)); + + addButton(new GuiNpcButton(0, guiLeft + 183, guiTop + 4, 79, 20, "gui.add")); + addButton(new GuiNpcButton(1, guiLeft + 183, guiTop + 26, 79, 20, "gui.cancel")); + addButton(new GuiNpcButton(2, guiLeft + 183, guiTop + 88, 79, 20, "gui.remove")); + } + + private void loadAbilities() { + displayToKey.clear(); + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) { + return; + } + + List abilities = playerData.abilityData.getUnlockedAbilityList(); + for (String key : abilities) { + String displayName; + if (key.startsWith(AbilityHotbarData.CHAIN_PREFIX)) { + String chainKey = key.substring(AbilityHotbarData.CHAIN_PREFIX.length()); + ChainedAbility chain = AbilityController.Instance != null ? + AbilityController.Instance.resolveChainedAbility(chainKey) : null; + displayName = chain != null ? "\u00A76\u2726 " + chain.getDisplayName() : key; + } else { + Ability ability = AbilityController.Instance != null ? + AbilityController.Instance.resolveAbility(key) : null; + displayName = ability != null ? ability.getDisplayName() : key; + } + displayToKey.put(displayName, key); + } + } + + @Override + public void actionPerformed(GuiButton button) { + int id = button.id; + + if (id == 0 && selected != null) { + confirmed = true; + selectedAbilityKey = displayToKey.get(selected); + this.close(); + } + if (id == 1) { + this.close(); + } + if (id == 2) { + this.removeAbility = true; + this.close(); + } + } + + @Override + public void customScrollClicked(int i, int i1, int i2, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll == scrollAbilities) + selected = scrollAbilities.getSelected(); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll == scrollAbilities && selection != null) { + confirmed = true; + selectedAbilityKey = displayToKey.get(selection); + this.close(); + } + } + + @Override + public void unFocused(GuiNpcTextField guiNpcTextField) { + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(55) != null) { + if (getTextField(55).isFocused()) { + if (search.equals(getTextField(55).getText())) + return; + search = getTextField(55).getText().toLowerCase(); + scrollAbilities.resetScroll(); + scrollAbilities.setList(getSearchList()); + } + } + } + + private List getSearchList() { + if (search.isEmpty()) { + return new ArrayList<>(displayToKey.keySet()); + } + + List list = new ArrayList<>(); + for (String name : displayToKey.keySet()) { + if (name.toLowerCase().contains(search)) + list.add(name); + } + return list; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java index 413ca7b39..8c8eca60d 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java @@ -24,10 +24,21 @@ public class GuiMenuTopButton extends GuiNpcButton { height = 20; } + /** + * Place to the RIGHT of the given button. + */ public GuiMenuTopButton(int i, GuiButton parent, String s) { this(i, parent.xPosition + parent.width, parent.yPosition, s); } + /** + * Place to the LEFT of the given button. + */ + public GuiMenuTopButton(int i, String s, GuiButton rightNeighbor) { + this(i, rightNeighbor.xPosition - (Minecraft.getMinecraft().fontRenderer.getStringWidth(StatCollector.translateToLocal(s)) + 12), + rightNeighbor.yPosition, s); + } + public GuiMenuTopButton(int i, GuiButton parent, String s, IButtonListener listener) { this(i, parent, s); diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index d8c093382..5c1dc6c1a 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -69,10 +69,10 @@ public class ConfigClient { // HUD PROPERTIES public static Property QuestOverlayXProperty; - public static int QuestOverlayX = 0; + public static float QuestOverlayX = 0; public static Property QuestOverlayYProperty; - public static int QuestOverlayY = 31; + public static float QuestOverlayY = 31; public static Property QuestOverlayScaleProperty; public static int QuestOverlayScale = 223; @@ -84,10 +84,10 @@ public class ConfigClient { public static boolean CompassEnabled = true; public static Property CompassOverlayXProperty; - public static int CompassOverlayX = 37; + public static float CompassOverlayX = 37; public static Property CompassOverlayYProperty; - public static int CompassOverlayY = 0; + public static float CompassOverlayY = 0; public static Property CompassOverlayScaleProperty; public static int CompassOverlayScale = 276; @@ -95,6 +95,37 @@ public class ConfigClient { public static Property CompassOverlayWidthProperty; public static int CompassOverlayWidth = 200; + // Ability Hotbar HUD + public static Property AbilityHotbarEnabledProperty; + public static boolean AbilityHotbarEnabled = true; + + public static Property AbilityHotbarXProperty; + public static float AbilityHotbarX = 3; + + public static Property AbilityHotbarYProperty; + public static float AbilityHotbarY = 50; + + public static Property AbilityHotbarScaleProperty; + public static int AbilityHotbarScale = 100; + + public static Property AbilityHotbarHorizontalProperty; + public static boolean AbilityHotbarHorizontal = false; + + public static Property AbilityHotbarAltTextureProperty; + public static boolean AbilityHotbarAltTexture = false; + + // 0=Hide, 1=Above(H)/Left(V), 2=Below(H)/Right(V) + public static Property AbilityHotbarTextPositionProperty; + public static int AbilityHotbarTextPosition = 2; + + // Max visible slots: 3, 5, or 7 + public static Property AbilityHotbarVisibleSlotsProperty; + public static int AbilityHotbarVisibleSlots = 5; + + // Show Always: true = always visible, false = only visible while HUD key held + public static Property AbilityHotbarShowAlwaysProperty; + public static boolean AbilityHotbarShowAlways = true; + /** * Texture Properties **/ @@ -125,11 +156,11 @@ public class ConfigClient { config.load(); // Hud Quest Overlay settings - QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0, "X position of the quest overlay."); - QuestOverlayX = QuestOverlayXProperty.getInt(0); + QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0.0, "X position of the quest overlay."); + QuestOverlayX = (float) QuestOverlayXProperty.getDouble(0); - QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31, "Y position of the quest overlay."); - QuestOverlayY = QuestOverlayYProperty.getInt(31); + QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31.0, "Y position of the quest overlay."); + QuestOverlayY = (float) QuestOverlayYProperty.getDouble(31); QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 223, "Scale percentage of the quest overlay."); QuestOverlayScale = QuestOverlayScaleProperty.getInt(223); @@ -149,22 +180,18 @@ public class ConfigClient { CompassOverlayXProperty = config.get( HUD, "Compass Hud X", - 37, - "Horizontal position of compass overlay (0-100 percentage)", - 0, - 100 + 37.0, + "Horizontal position of compass overlay (0-100 percentage)" ); - CompassOverlayX = CompassOverlayXProperty.getInt(); + CompassOverlayX = (float) CompassOverlayXProperty.getDouble(); CompassOverlayYProperty = config.get( HUD, "Compass Hud Y", - 0, - "Vertical position of compass overlay (0-100 percentage)", - 0, - 100 + 0.0, + "Vertical position of compass overlay (0-100 percentage)" ); - CompassOverlayY = CompassOverlayYProperty.getInt(); + CompassOverlayY = (float) CompassOverlayYProperty.getDouble(); CompassOverlayScaleProperty = config.get( HUD, @@ -186,6 +213,33 @@ public class ConfigClient { ); CompassOverlayWidth = CompassOverlayWidthProperty.getInt(); + // Ability Hotbar HUD Configs + AbilityHotbarEnabledProperty = config.get(HUD, "Ability Hotbar Enabled", true, "Enable Ability Hotbar HUD Component"); + AbilityHotbarEnabled = AbilityHotbarEnabledProperty.getBoolean(); + + AbilityHotbarXProperty = config.get(HUD, "Ability Hotbar X", 3.0, "Horizontal position (0-100 percentage)"); + AbilityHotbarX = (float) AbilityHotbarXProperty.getDouble(); + + AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 50.0, "Vertical position (0-100 percentage)"); + AbilityHotbarY = (float) AbilityHotbarYProperty.getDouble(); + + AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 100, "Scale percentage", 50, 300); + AbilityHotbarScale = AbilityHotbarScaleProperty.getInt(); + + AbilityHotbarHorizontalProperty = config.get(HUD, "Ability Hotbar Horizontal", false, "Display horizontally instead of vertically"); + AbilityHotbarHorizontal = AbilityHotbarHorizontalProperty.getBoolean(); + + AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", false, "Use rounded square instead of circle slots"); + AbilityHotbarAltTexture = AbilityHotbarAltTextureProperty.getBoolean(); + + AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (0=Hide, 1=Above/Left, 2=Below/Right)"); + AbilityHotbarTextPosition = AbilityHotbarTextPositionProperty.getInt(2); + + AbilityHotbarVisibleSlotsProperty = config.get(HUD, "Ability Hotbar Visible Slots", 5, "Max visible slots in hotbar (3, 5, or 7)"); + AbilityHotbarVisibleSlots = AbilityHotbarVisibleSlotsProperty.getInt(5); + + AbilityHotbarShowAlwaysProperty = config.get(HUD, "Ability Hotbar Show Always", true, "Always show hotbar (false = only while HUD key is held)"); + AbilityHotbarShowAlways = AbilityHotbarShowAlwaysProperty.getBoolean(true); // General AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side."); diff --git a/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java b/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java new file mode 100644 index 000000000..7941c81f1 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java @@ -0,0 +1,47 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class AbilityHotbarData { + public static final String CHAIN_PREFIX = "chain:"; + public static final int TOTAL_SLOTS = 12; + + public int slot = -1; + public String abilityKey = ""; + + public AbilityHotbarData() { + } + + public AbilityHotbarData(int slot) { + this.slot = slot; + } + + public boolean isChainKey() { + return abilityKey != null && abilityKey.startsWith(CHAIN_PREFIX); + } + + public String getResolveKey() { + if (isChainKey()) return abilityKey.substring(CHAIN_PREFIX.length()); + return abilityKey; + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("slot", slot); + tag.setString("abilityKey", abilityKey != null ? abilityKey : ""); + compound.setTag("AbilityHotbar" + slot, tag); + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + abilityKey = compound.getString("abilityKey"); + } + + public void reset() { + abilityKey = ""; + } + + public boolean isEmpty() { + return abilityKey == null || abilityKey.isEmpty(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index d2afe1c64..4df2485e6 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -364,6 +364,12 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA // Regular ability activation Ability ability = (Ability) action; + // Toggle abilities cycle state instead of executing + if (ability.isToggleable()) { + toggleAbility(key); + return true; + } + // Check universal cooldown (abilities can optionally ignore it) if (!ability.isIgnoreCooldown() && isOnCooldown()) return false; @@ -460,7 +466,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } public void setSelectedIndex(int index) { - if (index >= 0 && index < unlockedAbilities.size()) { + if (index == -1 || (index >= 0 && index < unlockedAbilities.size())) { this.selectedIndex = index; syncToClient(); } @@ -935,8 +941,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } /** - * Remove any unlocked ability keys that can no longer be resolved. - * Called during load to clean up references to deleted abilities. + * Remove any unlocked ability keys that can no longer be resolved or + * are no longer allowed for players (e.g. NPC-only abilities). + * Called during load to clean up references to deleted/restricted abilities. * Supports both regular ability keys and "chain:" prefixed chained ability keys. */ private void validateUnlockedAbilities() { @@ -949,6 +956,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA if (resolved == null) { it.remove(); LogWriter.info("Removed invalid ability reference from player data: " + key); + } else if (!resolved.getAllowedBy().allowsPlayer()) { + it.remove(); + LogWriter.info("Removed non-player ability from player data: " + key); } } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java new file mode 100644 index 000000000..f062d891c --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java @@ -0,0 +1,84 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +public class PlayerAbilityHotbarData { + public AbilityHotbarData[] slots = new AbilityHotbarData[AbilityHotbarData.TOTAL_SLOTS]; + + public PlayerAbilityHotbarData() { + for (int i = 0; i < slots.length; i++) { + slots[i] = new AbilityHotbarData(i); + } + } + + public AbilityHotbarData getSlot(int index) { + if (index < 0 || index >= slots.length) return null; + return slots[index]; + } + + public void setSlot(int index, String abilityKey) { + if (index < 0 || index >= slots.length) return; + slots[index].abilityKey = abilityKey != null ? abilityKey : ""; + } + + public void clearSlot(int index) { + if (index < 0 || index >= slots.length) return; + slots[index].reset(); + } + + public boolean hasAnyAbilities() { + for (AbilityHotbarData slot : slots) { + if (!slot.isEmpty()) return true; + } + return false; + } + + public void writeToNBT(NBTTagCompound compound) { + for (int i = 0; i < slots.length; i++) { + slots[i].writeToNBT(compound); + } + } + + public void readFromNBT(NBTTagCompound compound) { + for (int i = 0; i < slots.length; i++) { + NBTTagCompound slotTag = compound.getCompoundTag("AbilityHotbar" + i); + slots[i].readFromNBT(slotTag); + } + validateSlots(); + } + + public void validateSlots() { + if (AbilityController.Instance == null) return; + for (AbilityHotbarData slot : slots) { + if (slot.isEmpty()) continue; + boolean valid; + if (slot.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slot.abilityKey); + // Also check that resolved ability allows player usage + if (valid) { + Ability ability = AbilityController.Instance.resolveAbility(slot.abilityKey); + if (ability != null && !ability.getAllowedBy().allowsPlayer()) { + valid = false; + } + } + } + if (!valid) { + slot.reset(); + } + } + } + + public void syncToClient(EntityPlayer player) { + if (player instanceof EntityPlayerMP) { + AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player); + } + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index 9052811cf..8283d4f6c 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -65,6 +65,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { public PlayerTradeData tradeData = new PlayerTradeData(this); public PlayerAbilityData abilityData = new PlayerAbilityData(this); + public PlayerAbilityHotbarData hotbarData = new PlayerAbilityHotbarData(); public ActionManager actionManager = new ActionManager(); public PlayerDataScript scriptData; @@ -119,6 +120,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { // Sync player ability data to client abilityData.syncToClient(); + + // Sync hotbar data to client + hotbarData.syncToClient(player); } public void onLogout() { @@ -151,6 +155,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { magicData.readToNBT(data); tradeData.readFromNBT(data); abilityData.readFromNBT(data); + hotbarData.readFromNBT(data); if (player != null) { playername = player.getCommandSenderName(); @@ -195,6 +200,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { magicData.writeToNBT(compound); tradeData.writeToNBT(compound); abilityData.writeToNBT(compound); + hotbarData.writeToNBT(compound); compound.setString("PlayerName", playername); compound.setString("UUID", uuid); diff --git a/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java b/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java index e52742812..8c3fcde4c 100644 --- a/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java +++ b/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java @@ -4,6 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import noppes.npcs.CustomItems; +import noppes.npcs.client.gui.player.inventory.GuiAbilities; import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory; import noppes.npcs.client.gui.player.inventory.GuiFaction; import noppes.npcs.client.gui.player.inventory.GuiParty; @@ -58,5 +59,8 @@ public class InventoryTabCustomNpc extends AbstractTab { if (tab == -104) { mc.displayGuiScreen(new GuiProfiles()); } + if (tab == -105) { + mc.displayGuiScreen(new GuiAbilities()); + } } } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index b963e5d34..810100e47 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2,6 +2,7 @@ customnpcs.defaultTextColor=404040 key.categories.customnpc=CustomNPC+ key.customnpcs.special=Special Key +key.customnpcs.abilityHudKey=Ability HUD Key key.npcInventory=NPC Inventory entity.CustomNpc.name=Custom Npc @@ -167,6 +168,12 @@ gui.apply=Apply gui.cancel=Cancel gui.continue=Continue gui.yes=Yes +gui.abilities=Abilities +gui.toggles=Toggles +gui.toggle=Toggle +gui.toggle.active=Active +gui.toggle.inactive=Inactive +gui.abilityHotbar=Ability Hotbar gui.lineColor1=Upper line color gui.lineColor2=Middle line color @@ -2055,6 +2062,10 @@ ability.userType.PLAYER_ONLY=Players ability.userType.BOTH=Both ability.dieOnImpact=Die on Impact +ability.icon.section.uv=UV Coordinates +ability.icon.x=Icon X +ability.icon.y=Icon Y + gui.both=Both gui.players=Players diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png b/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png new file mode 100644 index 0000000000000000000000000000000000000000..ad84e33278d4db41e6a1f867556c1a4d03ddd188 GIT binary patch literal 203 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=ffJNuDl_Ar*7pUb)EIV8G#ek?(bf z>>6_E=CEySTRCBOfA@*194@BbqmWa+zK!R|?*A=fE-VX< zMKcJrh%+4B%aL`b%cFB~$CU~eC+=v)%!lXC@hwvHu{yKzM+ne$44$rjF6*2UngIN2 BOg;br literal 0 HcmV?d00001 From 1f31ae94c17de4ab49cf1ec045a4f8d2806bc1e4 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 02:15:51 -0500 Subject: [PATCH 03/51] Charge and Slam Fixes --- .../data/ability/type/AbilityCharge.java | 5 ++ .../data/ability/type/AbilityMovement.java | 2 +- .../data/ability/type/AbilitySlam.java | 57 ++++++++++++++++++- 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index d6d7044f3..79c16b21e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -227,6 +227,11 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { // Telegraph follows caster during windup - allows caster to reposition instance.setEntityIdToFollow(caster.getEntityId()); + // For player casters, track their rotation so telegraph follows look direction + if (isPlayerCaster(caster)) { + instance.setTrackFollowedEntityYaw(true); + } + return instance; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java index d5b8d8c52..b54056146 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java @@ -25,7 +25,7 @@ public abstract class AbilityMovement extends Ability { * Until the round trip completes, the server sees the old (stationary) position, * which would falsely trigger stall detection. */ - private static final int PLAYER_STALL_GRACE_TICKS = 5; + private static final int PLAYER_STALL_GRACE_TICKS = 8; private static final int NPC_STALL_GRACE_TICKS = 2; // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java index 9f1c64ff5..079bcbf0f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -41,10 +41,24 @@ public class AbilitySlam extends Ability implements IAbilitySlam { private float leapSpeed = 1.0f; private float leapHeight = 4.0f; + /** + * Grace period (in active ticks) before landing detection activates. + * Players need more time because: + * - Server sets motionY and sends S12 velocity packet to client + * - Client receives S12 and starts moving upward + * - Client sends C03 position packet back to server with onGround=false + * Until the round trip completes, the server's player.onGround (from stale C03) + * remains true, which would falsely trigger landing detection. + */ + private static final int PLAYER_LANDING_GRACE_TICKS = 10; + private static final int NPC_LANDING_GRACE_TICKS = 3; + // Runtime state private transient double targetX, targetY, targetZ; + private transient double startY; // Y position at launch for rise detection private transient boolean hasLaunched = false; private transient boolean hasLanded = false; + private transient boolean hasRisen = false; // Whether entity has risen above launch position private transient int airTicks = 0; private transient int maxAirTicks = 60; // Timeout to prevent stuck in air @@ -118,7 +132,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { public void onExecute(EntityLivingBase caster, EntityLivingBase target) { hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; + startY = caster.posY; caster.fallDistance = 0; if (isPlayerCaster(caster)) { @@ -297,9 +313,33 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.fallDistance = 0; } - // Check for landing: hit the ground or hit a wall mid-flight - if (airTicks > 3) { - if (caster.onGround || caster.isCollidedHorizontally) { + // Prevent NPC navigator from interfering with ballistic arc. + // lockMovement=WINDUP means applyMovementControl() doesn't clear + // the navigator during ACTIVE, so AI pathfinding could add motion. + if (!isPreview() && caster instanceof EntityNPCInterface) { + ((EntityNPCInterface) caster).getNavigator().clearPathEntity(); + } + + // Track if entity has risen above launch position. + // This prevents premature landing detection for players, where + // server-side caster.onGround remains true from stale C03 packets + // until the velocity S12 round-trip completes (can take 4-8+ ticks). + if (!hasRisen && caster.posY > startY + 0.5) { + hasRisen = true; + } + + // Landing detection uses different grace periods for NPC vs Player. + // NPCs: server physics is authoritative, onGround is accurate after 3 ticks. + // Players: onGround depends on C03 packets, needs longer grace + rise confirmation. + int graceTicks = isPlayerCaster(caster) ? PLAYER_LANDING_GRACE_TICKS : NPC_LANDING_GRACE_TICKS; + if (airTicks > graceTicks) { + if (hasRisen && (caster.onGround || caster.isCollidedHorizontally)) { + onLanding(caster, caster.worldObj); + return; + } + // Safety: if entity hasn't risen after triple the grace period, + // the launch may have failed (blocked by ceiling, etc.) - force landing + if (!hasRisen && airTicks > graceTicks * 3) { onLanding(caster, caster.worldObj); return; } @@ -424,6 +464,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; } @@ -434,6 +475,15 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } hasLaunched = false; hasLanded = false; + hasRisen = false; + airTicks = 0; + } + + @Override + public void cleanup() { + hasLaunched = false; + hasLanded = false; + hasRisen = false; airTicks = 0; } @@ -442,6 +492,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { super.reset(); hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; } From 0d871b16bff8d06aec7fadd0c7167766bf71a839 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 02:16:07 -0500 Subject: [PATCH 04/51] Line of Sight Handling for Cutter and Heavy Hit --- .../controllers/data/ability/Ability.java | 135 +++++++++++++++++- .../data/ability/type/AbilityCutter.java | 17 ++- .../data/ability/type/AbilityHeavyHit.java | 4 + 3 files changed, 152 insertions(+), 4 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index ee4bb5090..10673068c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -15,8 +15,13 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; +import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; +import net.minecraft.util.Vec3; import net.minecraft.world.World; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityEnergyPanel; import noppes.npcs.DataAbilities; import noppes.npcs.NpcDamageSource; import noppes.npcs.api.INbt; @@ -1344,7 +1349,7 @@ public abstract class Ability implements IAbility, IAbilityAction { activeSound = nbt.getString("activeSound"); windUpAnimationId = nbt.getInteger("windUpAnimationId"); activeAnimationId = nbt.getInteger("activeAnimationId"); - dazedAnimationId = nbt.getInteger("dazedAnimationId"); + dazedAnimationId = nbt.hasKey("dazedAnimationId") ? nbt.getInteger("dazedAnimationId") : -1; windUpAnimationName = nbt.getString("windUpAnimationName"); activeAnimationName = nbt.getString("activeAnimationName"); dazedAnimationName = nbt.getString("dazedAnimationName"); @@ -2144,6 +2149,134 @@ public abstract class Ability implements IAbility, IAbilityAction { return false; } + // ═══════════════════════════════════════════════════════════════════ + // LINE-OF-SIGHT UTILITIES + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if there is a clear line of sight (no solid blocks) between caster and target. + * Raycasts from caster's eye position to target's body center. + * + * @return true if there IS line of sight (no blocks in the way) + */ + public static boolean hasLineOfSight(World world, EntityLivingBase caster, EntityLivingBase target) { + Vec3 start = Vec3.createVectorHelper(caster.posX, caster.posY + caster.getEyeHeight(), caster.posZ); + Vec3 end = Vec3.createVectorHelper(target.posX, target.posY + target.height * 0.5, target.posZ); + MovingObjectPosition result = world.rayTraceBlocks(start, end); + return result == null; + } + + /** + * Check if an enemy barrier (dome or panel) blocks the line between caster and target. + * Barriers owned by the caster or allies of the caster are not considered blocking. + * + * @return true if an enemy barrier blocks the attack + */ + @SuppressWarnings("unchecked") + public static boolean isBlockedByBarrier(World world, EntityLivingBase caster, EntityLivingBase target) { + // Barrier entities have tiny Minecraft bounding boxes (1x1 for domes, 0.5x0.5 for panels) + // but their actual collision geometry extends up to MAX_ENTITY_RADIUS (50) blocks. + // Must expand search to match EntityEnergyProjectile.checkBarrierCollision() pattern. + double searchRange = 55.0; // MAX_ENTITY_RADIUS(50) + 5 + double minX = Math.min(caster.posX, target.posX) - searchRange; + double minY = Math.min(caster.posY, target.posY) - searchRange; + double minZ = Math.min(caster.posZ, target.posZ) - searchRange; + double maxX = Math.max(caster.posX, target.posX) + searchRange; + double maxY = Math.max(caster.posY, target.posY) + searchRange; + double maxZ = Math.max(caster.posZ, target.posZ) + searchRange; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + List barriers = world.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); + + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead) continue; + if (barrier.isCharging()) continue; + + // Skip barriers owned by caster or allies + if (barrier.getOwnerEntityId() == caster.getEntityId()) continue; + Entity barrierOwner = barrier.getOwnerEntity(); + if (barrierOwner instanceof EntityLivingBase) { + if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue; + } + + if (barrier instanceof EntityEnergyDome) { + if (isDomeBlocking((EntityEnergyDome) barrier, caster, target)) return true; + } else if (barrier instanceof EntityEnergyPanel) { + if (isPanelBlocking((EntityEnergyPanel) barrier, caster, target)) return true; + } + } + + return false; + } + + /** + * Check if a dome blocks an attack from caster to target. + * Blocks when caster is outside and target is inside the dome. + */ + private static boolean isDomeBlocking(EntityEnergyDome dome, EntityLivingBase caster, EntityLivingBase target) { + float radius = dome.getDomeRadius(); + + double cdx = caster.posX - dome.posX; + double cdy = (caster.posY + caster.getEyeHeight()) - dome.posY; + double cdz = caster.posZ - dome.posZ; + double casterDist = Math.sqrt(cdx * cdx + cdy * cdy + cdz * cdz); + + double tdx = target.posX - dome.posX; + double tdy = (target.posY + target.height * 0.5) - dome.posY; + double tdz = target.posZ - dome.posZ; + double targetDist = Math.sqrt(tdx * tdx + tdy * tdy + tdz * tdz); + + // Block when caster is outside and target is inside + return casterDist > radius && targetDist < radius; + } + + /** + * Check if a panel blocks an attack from caster to target. + * Checks if the line from caster to target crosses through the panel bounds. + */ + private static boolean isPanelBlocking(EntityEnergyPanel panel, EntityLivingBase caster, EntityLivingBase target) { + float halfW = panel.getPanelData().panelWidth * 0.5f; + float halfH = panel.getPanelData().panelHeight * 0.5f; + + // Panel normal direction + float yawRad = (float) Math.toRadians(panel.getPanelYaw()); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + + // Line from caster to target + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + double dx = target.posX - startX; + double dy = (target.posY + target.height * 0.5) - startY; + double dz = target.posZ - startZ; + + // Dot product of line direction with panel normal + double denom = dx * normalX + dz * normalZ; + if (Math.abs(denom) < 0.0001) return false; // Line parallel to panel + + // Parameter t where line crosses panel plane + double relX = panel.posX - startX; + double relZ = panel.posZ - startZ; + double t = (relX * normalX + relZ * normalZ) / denom; + + if (t < 0 || t > 1) return false; // Intersection outside the line segment + + // Calculate intersection point + double hitX = startX + dx * t; + double hitY = startY + dy * t; + double hitZ = startZ + dz * t; + + // Transform to panel local space (right axis) + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + double localRight = (hitX - panel.posX) * cos + (hitZ - panel.posZ) * sin; + double localUp = hitY - panel.posY; + + // Check bounds + return Math.abs(localRight) <= halfW && Math.abs(localUp) <= halfH; + } + // ═══════════════════════════════════════════════════════════════════ // IAbility API METHODS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index e49e5bb55..bdb90c951 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -134,6 +134,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { if (target != null && !isRotationLockedDuringWindup()) { instance.setTargetEntityId(target.getEntityId()); + } else { + // No target to track yaw from — track the caster's rotation instead + // so the telegraph follows where the player/NPC is facing + instance.setTrackFollowedEntityYaw(true); } return instance; @@ -160,9 +164,12 @@ public class AbilityCutter extends Ability implements IAbilityCutter { currentRotation = -arcAngle / 2.0f; activeSoundPlayed = false; - // Lock sweep direction toward target at execute time to prevent - // AI look-at jitter from misdirecting the sweep at close range - if (target != null) { + // Use the telegraph's locked yaw if available, so the sweep direction + // matches the telegraph the player/NPC was seeing during windup. + // The telegraph yaw is locked when entering ACTIVE phase via lockPosition(). + if (!telegraphInstances.isEmpty()) { + sweepBaseYaw = telegraphInstances.get(0).getYaw(); + } else if (target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; if (dx * dx + dz * dz > 0.0001) { @@ -260,6 +267,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { if (dist < minDist || dist > maxDist) continue; if (!isInSweepRange(dx, dz, sweepBaseYaw, minAngle, maxAngle)) continue; + // Line-of-sight check: skip targets behind solid blocks or enemy barriers + if (!hasLineOfSight(world, caster, entity)) continue; + if (isBlockedByBarrier(world, caster, entity)) continue; + hitEntities.add(entity.getEntityId()); float distFactor = 1.0f - ((float) dist / maxDist) * 0.3f; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java index 740f97be8..7e61f04c0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -121,6 +121,10 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { double sideDist = dx * rightX + dz * rightZ; if (Math.abs(sideDist) > hitWidth) continue; + // Line-of-sight check: skip targets behind solid blocks or enemy barriers + if (!hasLineOfSight(caster.worldObj, caster, livingTarget)) continue; + if (isBlockedByBarrier(caster.worldObj, caster, livingTarget)) continue; + // Entity is within the rectangle - apply damage boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); if (wasHit) { From 5e24a0cf367a114a7ca27e3ebb4fe2f1325c3ccb Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 02:16:26 -0500 Subject: [PATCH 05/51] Fixed Dazed Handling --- .../java/noppes/npcs/controllers/data/PlayerAbilityData.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 4df2485e6..72df5b16b 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -250,6 +250,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA @Override protected void onInterruptComplete() { // Player clears state immediately (unlike NPC which ticks through DAZED) + // Stop the dazed animation that was started in interruptCurrentAbility() + stopAbilityAnimation(); currentAbility = null; currentAbilityKey = null; currentTarget = null; From 077fc3cb1db011825ec6b47e16731b099d9f40de Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 02:16:40 -0500 Subject: [PATCH 06/51] Better Telegraph Tracking --- .../data/telegraph/TelegraphInstance.java | 16 ++++++++++++++++ .../noppes/npcs/client/ClientTickHandler.java | 17 ++++++++++------- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java index a5d2f0d95..7c502e284 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java @@ -33,6 +33,7 @@ public class TelegraphInstance { private int entityIdToFollow = -1; private int casterEntityId = -1; private int targetEntityId = -1; // For LINE telegraphs: entity to face (yaw tracking) + private boolean trackFollowedEntityYaw = false; // Track followed entity's rotationYaw when no targetEntity // Timing private int remainingTicks; @@ -96,6 +97,11 @@ public class TelegraphInstance { this.z = entity.posZ; // Find ground level below the entity for proper telegraph placement this.y = Ability.findGroundLevel(world, entity.posX, entity.posY, entity.posZ); + + // Track followed entity's yaw for directional telegraphs (player casters) + if (trackFollowedEntityYaw && targetEntityId < 0) { + this.yaw = entity.rotationYaw; + } } } @@ -218,6 +224,7 @@ public class TelegraphInstance { nbt.setInteger("entityIdToFollow", entityIdToFollow); nbt.setInteger("casterEntityId", casterEntityId); nbt.setInteger("targetEntityId", targetEntityId); + nbt.setBoolean("trackFollowedYaw", trackFollowedEntityYaw); nbt.setInteger("remainingTicks", remainingTicks); nbt.setInteger("totalTicks", totalTicks); @@ -243,6 +250,7 @@ public class TelegraphInstance { this.entityIdToFollow = nbt.getInteger("entityIdToFollow"); this.casterEntityId = nbt.getInteger("casterEntityId"); this.targetEntityId = nbt.getInteger("targetEntityId"); + this.trackFollowedEntityYaw = nbt.hasKey("trackFollowedYaw") && nbt.getBoolean("trackFollowedYaw"); this.remainingTicks = nbt.getInteger("remainingTicks"); this.totalTicks = nbt.getInteger("totalTicks"); @@ -335,6 +343,14 @@ public class TelegraphInstance { this.targetEntityId = targetEntityId; } + public boolean isTrackFollowedEntityYaw() { + return trackFollowedEntityYaw; + } + + public void setTrackFollowedEntityYaw(boolean track) { + this.trackFollowedEntityYaw = track; + } + public int getRemainingTicks() { return remainingTicks; } diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 36ad964e9..1c16de390 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -154,6 +154,16 @@ public class ClientTickHandler { renderCNPCPlayer.itemRenderer.updateEquippedItem(); } } + + // Tick telegraph manager AFTER entity updates so telegraph positions + // match entity interpolation (Phase.END runs after world tick) + if (TelegraphManager.ClientInstance != null) { + TelegraphManager.ClientInstance.tick(mc.theWorld); + } + + // Update lightning bolts for ability effects + LightningBolt.updateAll(); + return; } if (mc.thePlayer != null && mc.thePlayer.openContainer instanceof ContainerPlayer) { @@ -179,13 +189,6 @@ public class ClientTickHandler { MusicController.Instance.onUpdate(); ScriptSoundController.Instance.onUpdate(); - // Tick telegraph manager for ability warnings - if (TelegraphManager.ClientInstance != null) { - TelegraphManager.ClientInstance.tick(mc.theWorld); - } - - // Update lightning bolts for ability effects - LightningBolt.updateAll(); if (Minecraft.getMinecraft().thePlayer != null && (prevWidth != mc.displayWidth || prevHeight != mc.displayHeight)) { prevWidth = mc.displayWidth; prevHeight = mc.displayHeight; From 747918c4dc47dd724c7ad40def78700d94b3b02e Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 02:17:00 -0500 Subject: [PATCH 07/51] Better Barrier Tracking --- .../java/kamkeel/npcs/entity/EntityEnergyBarrier.java | 11 +++++++++++ .../java/kamkeel/npcs/entity/EntityEnergyDome.java | 5 +++++ .../java/kamkeel/npcs/entity/EntityEnergyPanel.java | 7 +++++++ 3 files changed, 23 insertions(+) diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java index af6766b15..a5d263075 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -1,5 +1,6 @@ package kamkeel.npcs.entity; +import kamkeel.npcs.controllers.data.ability.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -236,6 +237,16 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { } } + /** + * Check if an entity is an ally of this barrier's owner. + * Allies should not be knocked back by barriers. + */ + protected boolean isAllyOfOwner(EntityLivingBase entity) { + Entity owner = getOwnerEntity(); + if (owner == null || !(owner instanceof EntityLivingBase)) return false; + return AbilityTargetHelper.isAlly((EntityLivingBase) owner, entity); + } + // ==================== GETTERS ==================== public EnergyBarrierData getBarrierData() { diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 782413435..dbe8d4db6 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -58,6 +58,10 @@ public class EntityEnergyDome extends EntityEnergyBarrier { Entity owner = ownerEntityId >= 0 ? worldObj.getEntityByID(ownerEntityId) : null; if (owner != null) { this.setPosition(owner.posX, owner.posY, owner.posZ); + // Sync prevPos with owner's prevPos for smooth interpolation + this.prevPosX = owner.prevPosX; + this.prevPosY = owner.prevPosY; + this.prevPosZ = owner.prevPosZ; } } @@ -162,6 +166,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { for (EntityLivingBase ent : entities) { if (ent.getEntityId() == ownerEntityId) continue; if (!isKnockbackTarget(ent)) continue; + if (isAllyOfOwner(ent)) continue; double dx = ent.posX - posX; double dy = (ent.posY + ent.height * 0.5) - posY; diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index d3665e319..19bc1f136 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -130,6 +130,12 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { double newZ = owner.posZ + (Math.cos(yawRad) * frontDist); this.setPosition(newX, newY, newZ); + + // Sync prevPos with owner's prevPos for smooth interpolation + float prevYawRad = (float) Math.toRadians(owner.prevRotationYaw); + this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist); + this.prevPosY = owner.prevPosY + panelData.heightOffset + (owner.height * 0.5f); + this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist); } private void updateLaunched() { @@ -296,6 +302,7 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { for (EntityLivingBase ent : entities) { if (ent.getEntityId() == ownerEntityId) continue; if (!isKnockbackTarget(ent)) continue; + if (isAllyOfOwner(ent)) continue; // Transform entity position to panel-local space double dx = ent.posX - posX; From 86fe9fd6bb10f3884732324c580424c372da9b7d Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 02:17:11 -0500 Subject: [PATCH 08/51] Sweeper Height and Width Configs --- .../client/renderer/RenderAbilitySweeper.java | 74 ++++++++++--------- .../data/ability/type/AbilityZone.java | 2 +- .../ability/type/energy/AbilitySweeper.java | 2 +- .../npcs/entity/EntityAbilitySweeper.java | 25 ++++--- 4 files changed, 56 insertions(+), 47 deletions(-) diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java index b72be7a7c..fc7bc33c7 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java @@ -25,6 +25,7 @@ public class RenderAbilitySweeper extends Render { float beamLength = sweeper.getBeamLength(); float beamWidth = sweeper.getBeamWidth(); + float beamHeight = sweeper.getBeamHeight(); int innerColor = sweeper.getInnerColor(); int outerColor = sweeper.getOuterColor(); boolean outerColorEnabled = sweeper.isOuterColorEnabled(); @@ -38,7 +39,7 @@ public class RenderAbilitySweeper extends Render { GL11.glRotatef(-angle, 0, 1, 0); // Negative for correct direction // Render the beam extending in the +Z direction (like beam trail segments) - renderBeam(beamLength, beamWidth, innerColor, outerColor, outerColorEnabled, outerColorWidth); + renderBeam(beamLength, beamWidth, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth); GL11.glPopMatrix(); @@ -71,8 +72,9 @@ public class RenderAbilitySweeper extends Render { * Render beam using the same style as the Beam entity trail. * Three layers: outer glow, middle, inner core. * outerColorWidth is an additive offset from inner width (consistent with other renderers). + * Width and height control the rectangular cross-section independently. */ - private void renderBeam(float length, float width, int innerColor, int outerColor, + private void renderBeam(float length, float width, float height, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth) { // Extract colors float outerR = ((outerColor >> 16) & 0xFF) / 255.0f; @@ -83,37 +85,40 @@ public class RenderAbilitySweeper extends Render { float innerG = ((innerColor >> 8) & 0xFF) / 255.0f; float innerB = (innerColor & 0xFF) / 255.0f; - // Inner scale defines the core width (consistent with other renderers) + // Inner scale defines the core size (consistent with other renderers) float innerScale = 0.6f; float innerWidth = width * innerScale; + float innerHeight = height * innerScale; // Render from origin (0,0,0) to (0,0,length) in local coords // After rotation this extends in the correct world direction // Outer glow (wider, translucent) - only if enabled - // outerColorWidth is additive offset from inner width + // outerColorWidth is additive offset from inner size if (outerColorEnabled) { float outerWidth = innerWidth + outerColorWidth * width; + float outerHeight = innerHeight + outerColorWidth * height; GL11.glDepthMask(false); - renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerR, outerG, outerB, 0.3f); + renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f); GL11.glDepthMask(true); // Middle layer (halfway between inner and outer) float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f; - renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, outerR, outerG, outerB, 0.6f); + float midHeight = innerHeight + (outerHeight - innerHeight) * 0.5f; + renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, midHeight, outerR, outerG, outerB, 0.6f); } // Inner core (solid) - renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerR, innerG, innerB, 1.0f); + renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f); } /** - * Render a beam segment as a 3D rectangular prism. + * Render a beam segment as a 3D rectangular prism with independent width and height. * Uses the same approach as RenderAbilityBeam.renderBeamRectangle. */ private void renderBeamSegment(double x1, double y1, double z1, double x2, double y2, double z2, - float width, float r, float g, float b, float a) { + float width, float height, float r, float g, float b, float a) { // Calculate direction double dx = x2 - x1; double dy = y2 - y1; @@ -151,39 +156,40 @@ public class RenderAbilitySweeper extends Render { double vertZ = dx * horzY - dy * horzX; float halfWidth = width * 0.5f; + float halfHeight = height * 0.5f; - // Calculate 8 corners of the box - double s1x = x1 - horzX * halfWidth - vertX * halfWidth; - double s1y = y1 - horzY * halfWidth - vertY * halfWidth; - double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth; + // Calculate 8 corners of the box (horz scaled by halfWidth, vert scaled by halfHeight) + double s1x = x1 - horzX * halfWidth - vertX * halfHeight; + double s1y = y1 - horzY * halfWidth - vertY * halfHeight; + double s1z = z1 - horzZ * halfWidth - vertZ * halfHeight; - double s2x = x1 + horzX * halfWidth - vertX * halfWidth; - double s2y = y1 + horzY * halfWidth - vertY * halfWidth; - double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth; + double s2x = x1 + horzX * halfWidth - vertX * halfHeight; + double s2y = y1 + horzY * halfWidth - vertY * halfHeight; + double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight; - double s3x = x1 + horzX * halfWidth + vertX * halfWidth; - double s3y = y1 + horzY * halfWidth + vertY * halfWidth; - double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth; + double s3x = x1 + horzX * halfWidth + vertX * halfHeight; + double s3y = y1 + horzY * halfWidth + vertY * halfHeight; + double s3z = z1 + horzZ * halfWidth + vertZ * halfHeight; - double s4x = x1 - horzX * halfWidth + vertX * halfWidth; - double s4y = y1 - horzY * halfWidth + vertY * halfWidth; - double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth; + double s4x = x1 - horzX * halfWidth + vertX * halfHeight; + double s4y = y1 - horzY * halfWidth + vertY * halfHeight; + double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight; - double e1x = x2 - horzX * halfWidth - vertX * halfWidth; - double e1y = y2 - horzY * halfWidth - vertY * halfWidth; - double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth; + double e1x = x2 - horzX * halfWidth - vertX * halfHeight; + double e1y = y2 - horzY * halfWidth - vertY * halfHeight; + double e1z = z2 - horzZ * halfWidth - vertZ * halfHeight; - double e2x = x2 + horzX * halfWidth - vertX * halfWidth; - double e2y = y2 + horzY * halfWidth - vertY * halfWidth; - double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth; + double e2x = x2 + horzX * halfWidth - vertX * halfHeight; + double e2y = y2 + horzY * halfWidth - vertY * halfHeight; + double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight; - double e3x = x2 + horzX * halfWidth + vertX * halfWidth; - double e3y = y2 + horzY * halfWidth + vertY * halfWidth; - double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth; + double e3x = x2 + horzX * halfWidth + vertX * halfHeight; + double e3y = y2 + horzY * halfWidth + vertY * halfHeight; + double e3z = z2 + horzZ * halfWidth + vertZ * halfHeight; - double e4x = x2 - horzX * halfWidth + vertX * halfWidth; - double e4y = y2 - horzY * halfWidth + vertY * halfWidth; - double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth; + double e4x = x2 - horzX * halfWidth + vertX * halfHeight; + double e4y = y2 - horzY * halfWidth + vertY * halfHeight; + double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight; Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java index b5cc53a9e..7f2a92329 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -67,7 +67,7 @@ public abstract class AbilityZone extends Ability { this.maxRange = 20.0f; this.lockMovement = LockMovementType.WINDUP; this.cooldownTicks = 0; - this.allowedBy = UserType.NPC_ONLY; + this.allowedBy = UserType.BOTH; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java index 5c9a9fe37..a1340ae39 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -31,7 +31,7 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { // Type-specific parameters private float beamLength = 10.0f; private float beamWidth = 0.3f; // Thin like beam trail - private float beamHeight = 0.5f; // Height above ground (low enough to jump over) + private float beamHeight = 1.0f; // Beam vertical size in blocks (1 block tall, jumpable) private float damage = 5.0f; private int damageInterval = 5; private boolean piercing = true; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index fd739876d..4323141f5 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -34,7 +34,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { // Beam properties private float beamLength = 10.0f; private float beamWidth = 0.3f; // Thin like beam trail - private float beamHeight = 0.8f; + private float beamHeight = 1.0f; // Combat properties private float damage = 5.0f; @@ -100,8 +100,8 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { this.baseYaw = owner.rotationYaw; } - // Position at owner - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + // Position at beam center (bottom at feet, top at feet + beamHeight) + this.setPosition(owner.posX, owner.posY + beamHeight / 2.0, owner.posZ); // Ready to deal damage immediately this.ticksSinceDamage = damageInterval; @@ -149,7 +149,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { } if (owner != null) { - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + this.setPosition(owner.posX, owner.posY + beamHeight / 2.0, owner.posZ); } // Check if sweep is done @@ -204,10 +204,10 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { double checkY = startY; double checkZ = startZ + dirZ * beamLength * progress; - // Narrow hitbox for thin beam + // Hitbox: beam center ± half-height vertically, generous width for thin beams AxisAlignedBB checkBox = AxisAlignedBB.getBoundingBox( - checkX - beamWidth * 2, checkY - 0.5, checkZ - beamWidth * 2, - checkX + beamWidth * 2, checkY + 1.0, checkZ + beamWidth * 2 + checkX - beamWidth * 2, checkY - beamHeight / 2.0, checkZ - beamWidth * 2, + checkX + beamWidth * 2, checkY + beamHeight / 2.0, checkZ + beamWidth * 2 ); @SuppressWarnings("unchecked") @@ -259,11 +259,14 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { return false; } - // Height check - entity's feet must be below beam top (allows jumping over) + // Height check - entity must overlap beam vertically + double beamTopY = startY + beamHeight / 2.0; + double beamBottomY = startY - beamHeight / 2.0; double entityFeetY = entity.posY; - double beamTopY = startY + 0.5; + double entityTopY = entity.posY + entity.height; - return entityFeetY < beamTopY; + // Entity feet must be below beam top AND entity top must be above beam bottom + return entityFeetY < beamTopY && entityTopY > beamBottomY; } /** @@ -366,7 +369,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { readEnergyBaseNBT(nbt); this.beamLength = sanitize(nbt.getFloat("BeamLength"), 10.0f, MAX_ENTITY_SIZE); this.beamWidth = sanitize(nbt.getFloat("BeamWidth"), 0.3f, MAX_ENTITY_SIZE); - this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 0.8f, MAX_ENTITY_SIZE); + this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 1.0f, MAX_ENTITY_SIZE); this.sweepSpeed = nbt.hasKey("SweepSpeed") ? nbt.getFloat("SweepSpeed") : 3.0f; if (Float.isNaN(sweepSpeed) || Float.isInfinite(sweepSpeed) || sweepSpeed <= 0) sweepSpeed = 3.0f; this.numberOfRotations = nbt.hasKey("NumRotations") ? nbt.getInteger("NumRotations") : 2; From 877fe2b275bc76ec3b5eb14df554be0efa353dc3 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:33:58 -0500 Subject: [PATCH 09/51] Fix Conditions Build Error --- .../npcs/controllers/data/ability/ConditionField.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java index cf4d2ad8f..d96178759 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java @@ -127,10 +127,11 @@ public abstract class ConditionField { public void readNBT(NBTTagCompound nbt) { if (!nbt.hasKey(key)) return; T v; - if (type == Integer.class) v = (T) (Integer) nbt.getInteger(key); - else if (type == Float.class) v = (T) (Float) nbt.getFloat(key); - else if (type == Double.class) v = (T) (Double) nbt.getDouble(key); - else if (type == Long.class) v = (T) (Long) nbt.getLong(key); + Class t = type; + if (t == Integer.class) v = (T) (Integer) nbt.getInteger(key); + else if (t == Float.class) v = (T) (Float) nbt.getFloat(key); + else if (t == Double.class) v = (T) (Double) nbt.getDouble(key); + else if (t == Long.class) v = (T) (Long) nbt.getLong(key); else return; setValue(v); } From 44118ec770122c57ffd8cd5de5f0f8c78c7ca089 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:47:12 -0500 Subject: [PATCH 10/51] Complete Ability Hud System + Added-Per-Ability Cooldown System to be Reflected in Hud and Hud GUI --- src/api | 2 +- .../controllers/data/ability/Ability.java | 20 ++- .../kamkeel/npcs/network/PacketHandler.java | 2 + .../npcs/network/enums/EnumDataPacket.java | 1 + .../ability/AbilityCooldownSyncPacket.java | 109 ++++++++++++++++ .../noppes/npcs/AbstractDataAbilities.java | 118 +++++++++++++++++- src/main/java/noppes/npcs/DataAbilities.java | 20 ++- .../hud/ability/AbilityHotbarComponent.java | 72 +++++++++-- .../ability/AbilityHotbarSlotRenderer.java | 72 ++++++++--- .../gui/player/inventory/GuiAbilities.java | 20 +++ .../java/noppes/npcs/config/ConfigClient.java | 11 +- .../controllers/data/PlayerAbilityData.java | 64 ++++++++-- .../assets/customnpcs/lang/en_US.lang | 3 +- 13 files changed, 467 insertions(+), 47 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java diff --git a/src/api b/src/api index a27e11595..72718c360 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit a27e1159508c799c1b7b612ee09574f207bd64e0 +Subproject commit 72718c36016c526b00681ea2ba8c506030aca555 diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 10673068c..3563fe892 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -109,6 +109,10 @@ public abstract class Ability implements IAbility, IAbilityAction { // Cooldown override protected boolean ignoreCooldown = false; + // Per-ability cooldown: if true, this ability has its own independent cooldown + // instead of sharing the global cooldown with other abilities + protected boolean perAbilityCooldown = false; + // ═══════════════════════════════════════════════════════════════════ // BUILT-IN (set in constructor via configureAsBuiltIn, NOT persisted) // ═══════════════════════════════════════════════════════════════════ @@ -603,8 +607,10 @@ public abstract class Ability implements IAbility, IAbilityAction { FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) .hover("ability.hover.sync") ).tab("General").visibleWhen(() -> hasWindUpAnimation() && isSyncWindupWithAnimation())); - defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks) - .tab("General").range(0, 10000)); + defs.add(FieldDef.row( + FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks).range(0, 10000), + FieldDef.boolField("ability.perAbilityCooldown", this::isPerAbilityCooldown, this::setPerAbilityCooldown) + ).tab("General")); defs.add(FieldDef.section("ability.section.movement").tab("General")); defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), () -> this.getLockMovement().getDisplayKey(), @@ -1282,6 +1288,7 @@ public abstract class Ability implements IAbility, IAbilityAction { nbt.setTag("customData", (NBTTagCompound) customData.copy()); nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); + nbt.setBoolean("perAbilityCooldown", perAbilityCooldown); // Toggle nbt.setInteger("toggleStates", toggleStates); @@ -1363,6 +1370,7 @@ public abstract class Ability implements IAbility, IAbilityAction { customData = nbt.getCompoundTag("customData"); allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); ignoreCooldown = nbt.getBoolean("ignoreCooldown"); + perAbilityCooldown = nbt.getBoolean("perAbilityCooldown"); // Toggle toggleStates = nbt.getInteger("toggleStates"); @@ -1951,6 +1959,14 @@ public abstract class Ability implements IAbility, IAbilityAction { this.ignoreCooldown = ignoreCooldown; } + public boolean isPerAbilityCooldown() { + return perAbilityCooldown; + } + + public void setPerAbilityCooldown(boolean perAbilityCooldown) { + this.perAbilityCooldown = perAbilityCooldown; + } + public boolean isToggleable() { return toggleStates > 0; } diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index ca172edc3..766210559 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -26,6 +26,7 @@ import kamkeel.npcs.network.packets.data.SoundManagementPacket; import kamkeel.npcs.network.packets.data.SwingPlayerArmPacket; import kamkeel.npcs.network.packets.data.UpdateAnimationsPacket; import kamkeel.npcs.network.packets.data.VillagerListPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; @@ -603,6 +604,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); DATA_PACKET.registerPacket(new AbilityHotbarSyncPacket()); + DATA_PACKET.registerPacket(new AbilityCooldownSyncPacket()); } public void registerPlayerPackets() { diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index e72cd2810..bc6d7d1f9 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -65,6 +65,7 @@ public enum EnumDataPacket { PLAYER_ABILITY_SYNC, PLAYER_ABILITY_STATE, ABILITY_HOTBAR_SYNC, + ABILITY_COOLDOWN_SYNC, // Auction System AUCTION_DATA, diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java new file mode 100644 index 000000000..484cc602c --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java @@ -0,0 +1,109 @@ +package kamkeel.npcs.network.packets.data.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Lightweight packet that syncs cooldown state (global + per-ability) to the client. + * Sent when cooldowns are rolled, reset, or on login. + */ +public final class AbilityCooldownSyncPacket extends AbstractPacket { + public static final String packetName = "Data|AbilityCooldownSync"; + + private long globalCooldownEndTime; + private int globalCooldownDuration; + private HashMap perAbilityCooldownEndTimes; + private HashMap perAbilityCooldownDurations; + + public AbilityCooldownSyncPacket() { + } + + public AbilityCooldownSyncPacket(long globalEndTime, int globalDuration, + HashMap perEndTimes, + HashMap perDurations) { + this.globalCooldownEndTime = globalEndTime; + this.globalCooldownDuration = globalDuration; + this.perAbilityCooldownEndTimes = perEndTimes; + this.perAbilityCooldownDurations = perDurations; + } + + @Override + public Enum getType() { + return EnumDataPacket.ABILITY_COOLDOWN_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeLong(globalCooldownEndTime); + out.writeInt(globalCooldownDuration); + + // Write per-ability cooldowns + int count = perAbilityCooldownEndTimes != null ? perAbilityCooldownEndTimes.size() : 0; + out.writeInt(count); + if (count > 0) { + for (Map.Entry entry : perAbilityCooldownEndTimes.entrySet()) { + ByteBufUtils.writeUTF8String(out, entry.getKey()); + out.writeLong(entry.getValue()); + Integer dur = perAbilityCooldownDurations.get(entry.getKey()); + out.writeInt(dur != null ? dur : 0); + } + } + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + long globalEndTime = in.readLong(); + int globalDuration = in.readInt(); + + int count = in.readInt(); + HashMap perEndTimes = new HashMap<>(); + HashMap perDurations = new HashMap<>(); + for (int i = 0; i < count; i++) { + String key = ByteBufUtils.readUTF8String(in); + long endTime = in.readLong(); + int duration = in.readInt(); + perEndTimes.put(key, endTime); + perDurations.put(key, duration); + } + + PlayerData data = PlayerData.get(player); + if (data != null && data.abilityData != null) { + data.abilityData.applyCooldownSync(globalEndTime, globalDuration, perEndTimes, perDurations); + } + } + + /** + * Send the player's current cooldown state to their client. + */ + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null || data.abilityData == null) return; + + PacketHandler.Instance.sendToPlayer(new AbilityCooldownSyncPacket( + data.abilityData.getCooldownEndTime(), + data.abilityData.getGlobalCooldownDurationValue(), + data.abilityData.getPerAbilityCooldownEndTimes(), + data.abilityData.getPerAbilityCooldownDurations() + ), player); + } +} diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java index 240714738..b78ca37e7 100644 --- a/src/main/java/noppes/npcs/AbstractDataAbilities.java +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -14,6 +14,7 @@ import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -44,10 +45,25 @@ public abstract class AbstractDataAbilities { protected Ability currentAbility; /** - * World time when cooldown ends + * World time when global cooldown ends */ protected long cooldownEndTime = 0; + /** + * Duration of the current global cooldown in ticks (for progress calculation) + */ + protected int globalCooldownDuration = 0; + + /** + * Per-ability cooldown end times. Key = ability key, Value = world time when cooldown ends. + */ + protected HashMap perAbilityCooldownEndTimes = new HashMap<>(); + + /** + * Per-ability cooldown durations in ticks (for progress calculation). + */ + protected HashMap perAbilityCooldownDurations = new HashMap<>(); + /** * Rotation lock state */ @@ -526,6 +542,106 @@ public abstract class AbstractDataAbilities { cooldownEndTime = endTime; } + /** + * Get the global cooldown end time. + */ + public long getCooldownEndTime() { + return cooldownEndTime; + } + + /** + * Get the global cooldown duration value. + */ + public int getGlobalCooldownDurationValue() { + return globalCooldownDuration; + } + + /** + * Get the per-ability cooldown end times map. + */ + public HashMap getPerAbilityCooldownEndTimes() { + return perAbilityCooldownEndTimes; + } + + /** + * Get the per-ability cooldown durations map. + */ + public HashMap getPerAbilityCooldownDurations() { + return perAbilityCooldownDurations; + } + + /** + * Apply cooldown sync data from server. Called on client side. + */ + public void applyCooldownSync(long globalEndTime, int globalDuration, + HashMap perEndTimes, + HashMap perDurations) { + this.cooldownEndTime = globalEndTime; + this.globalCooldownDuration = globalDuration; + this.perAbilityCooldownEndTimes = perEndTimes; + this.perAbilityCooldownDurations = perDurations; + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-ABILITY COOLDOWN MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if a specific ability is on its per-ability cooldown. + */ + public boolean isOnPerAbilityCooldown(String key) { + Long endTime = perAbilityCooldownEndTimes.get(key); + return endTime != null && getWorldTime() < endTime; + } + + /** + * Set a per-ability cooldown. + */ + public void setPerAbilityCooldown(String key, long endTime, int duration) { + perAbilityCooldownEndTimes.put(key, endTime); + perAbilityCooldownDurations.put(key, duration); + } + + /** + * Reset a specific per-ability cooldown. + */ + public void resetPerAbilityCooldown(String key) { + perAbilityCooldownEndTimes.remove(key); + perAbilityCooldownDurations.remove(key); + } + + /** + * Reset all per-ability cooldowns. + */ + public void resetAllPerAbilityCooldowns() { + perAbilityCooldownEndTimes.clear(); + perAbilityCooldownDurations.clear(); + } + + /** + * Get global cooldown progress for HUD rendering. + * @return 1.0 when cooldown just started (fully covered), 0.0 when done + */ + public float getGlobalCooldownProgress() { + if (globalCooldownDuration <= 0) return 0f; + long remaining = cooldownEndTime - getWorldTime(); + if (remaining <= 0) return 0f; + return Math.min(1f, (float) remaining / globalCooldownDuration); + } + + /** + * Get per-ability cooldown progress for HUD rendering. + * @return 1.0 when cooldown just started (fully covered), 0.0 when done + */ + public float getPerAbilityCooldownProgress(String key) { + Long endTime = perAbilityCooldownEndTimes.get(key); + Integer duration = perAbilityCooldownDurations.get(key); + if (endTime == null || duration == null || duration <= 0) return 0f; + long remaining = endTime - getWorldTime(); + if (remaining <= 0) return 0f; + return Math.min(1f, (float) remaining / duration); + } + // ═══════════════════════════════════════════════════════════════════ // POSITION LOCKING // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 44fb852c6..548939a54 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -222,13 +222,18 @@ public class DataAbilities extends AbstractDataAbilities { @Override protected void rollCooldown(Ability ability) { + // Always roll NPC global cooldown (pacing timer) int baseCooldown = minCooldown; if (maxCooldown > minCooldown) { baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); } - cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown; - // Add ability-specific cooldown offset - cooldownEndTime += ability.getCooldownTicks(); + cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + ability.getCooldownTicks(); + + // Additionally set per-ability cooldown if enabled + if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) { + long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks(); + setPerAbilityCooldown(ability.getName(), endTime, ability.getCooldownTicks()); + } } @Override @@ -482,6 +487,14 @@ public class DataAbilities extends AbstractDataAbilities { return false; } + // Per-ability cooldown filter: ability may have its own independent cooldown + if (!action.isChain()) { + Ability ab = (Ability) action; + if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) { + return false; + } + } + return true; } @@ -726,6 +739,7 @@ public class DataAbilities extends AbstractDataAbilities { stopCurrentAbility(); clearActiveToggles(); interruptConcurrentSlots(); + resetAllPerAbilityCooldowns(); // Roll cooldown so NPC doesn't immediately attack after reset rollCooldownOnReset(); diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java index 56189a698..4b3be2d6a 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java @@ -56,7 +56,8 @@ public class AbilityHotbarComponent extends HudComponent { // Fade: when ShowAlways=false, fade in/out when HUD key is held private float fadeAlpha = 0f; - private static final float FADE_SPEED = 8f; // per second — ~125ms full transition + private long lastFadeTime = 0; + private static final float FADE_SPEED = 3f; // per second — ~333ms full transition private Minecraft mc; @@ -124,6 +125,7 @@ public class AbilityHotbarComponent extends HudComponent { ConfigClient.AbilityHotbarTextPositionProperty.set(ConfigClient.AbilityHotbarTextPosition); ConfigClient.AbilityHotbarVisibleSlotsProperty.set(ConfigClient.AbilityHotbarVisibleSlots); ConfigClient.AbilityHotbarShowAlwaysProperty.set(ConfigClient.AbilityHotbarShowAlways); + ConfigClient.AbilityHotbarTextVisibilityProperty.set(ConfigClient.AbilityHotbarTextVisibility); if (ConfigClient.config.hasChanged()) { ConfigClient.config.save(); @@ -138,9 +140,12 @@ public class AbilityHotbarComponent extends HudComponent { // Fade logic: when ShowAlways=false, only show while HUD key is held boolean showAlways = ConfigClient.AbilityHotbarShowAlways; + long now = Minecraft.getSystemTime(); if (!showAlways) { boolean hudKeyHeld = isHudKeyHeld(); - float dt = partialTicks > 0 ? 1f / 20f : 0.05f; // approximate frame time + float dt = lastFadeTime > 0 ? (now - lastFadeTime) / 1000f : 0f; + dt = Math.min(dt, 0.1f); // cap to avoid jumps after pauses + lastFadeTime = now; if (hudKeyHeld || pendingSelectKey != null || scrollOffset != 0f) { fadeAlpha = Math.min(1f, fadeAlpha + FADE_SPEED * dt); } else { @@ -149,6 +154,7 @@ public class AbilityHotbarComponent extends HudComponent { if (fadeAlpha <= 0f) return; } else { fadeAlpha = 1f; + lastFadeTime = now; } long currentTime = Minecraft.getSystemTime(); @@ -184,12 +190,15 @@ public class AbilityHotbarComponent extends HudComponent { int centerX = overlayWidth / 2; int centerY = overlayHeight / 2; - float cooldownProgress = 0; - PlayerData playerData = ClientCacheHandler.playerData; - if (playerData != null && playerData.abilityData != null) { - if (playerData.abilityData.isOnCooldown()) { - cooldownProgress = 0.5f; - } + // Compute text visibility: 0=Shown, 1=Hidden, 2=Held + boolean showText; + int textVis = ConfigClient.AbilityHotbarTextVisibility; + if (textVis == 1) { + showText = false; + } else if (textVis == 2) { + showText = isHudKeyHeld(); + } else { + showText = true; } for (int i = 0; i < TOTAL_SLOTS; i++) { @@ -228,13 +237,18 @@ public class AbilityHotbarComponent extends HudComponent { float edgeAlpha = absDist > half - 0.5f ? 1f - (absDist - (half - 0.5f)) : 1f; float slotAlpha = edgeAlpha * fadeAlpha; boolean isCenter = (offset == 0 && scrollOffset == 0f); - float slotCooldown = isCenter ? cooldownProgress : 0; + + // Compute per-slot cooldown progress (all slots, not just center) + float slotCooldown = 0f; + if (rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null) { + slotCooldown = getCooldownProgressForSlot(rawSlotIndex); + } if (rawSlotIndex == -1) { // Deselect slot — draw empty marker drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha); } else { - slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha); + slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText); } } @@ -441,6 +455,7 @@ public class AbilityHotbarComponent extends HudComponent { buttonList.add(new GuiButton(3, 0, 0, 120, 20, getTextPositionLabel())); buttonList.add(new GuiButton(4, 0, 0, 120, 20, "Slots: " + ConfigClient.AbilityHotbarVisibleSlots)); buttonList.add(new GuiButton(5, 0, 0, 120, 20, ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key")); + buttonList.add(new GuiButton(6, 0, 0, 120, 20, getTextVisibilityLabel())); } @Override @@ -453,7 +468,8 @@ public class AbilityHotbarComponent extends HudComponent { ConfigClient.AbilityHotbarAltTexture = !ConfigClient.AbilityHotbarAltTexture; button.displayString = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; } else if (button.id == 3) { - ConfigClient.AbilityHotbarTextPosition = (ConfigClient.AbilityHotbarTextPosition + 1) % 3; + // Toggle between 1 (Above/Left) and 2 (Below/Right) + ConfigClient.AbilityHotbarTextPosition = ConfigClient.AbilityHotbarTextPosition == 1 ? 2 : 1; button.displayString = getTextPositionLabel(); } else if (button.id == 4) { int current = ConfigClient.AbilityHotbarVisibleSlots; @@ -465,6 +481,9 @@ public class AbilityHotbarComponent extends HudComponent { } else if (button.id == 5) { ConfigClient.AbilityHotbarShowAlways = !ConfigClient.AbilityHotbarShowAlways; button.displayString = ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key"; + } else if (button.id == 6) { + ConfigClient.AbilityHotbarTextVisibility = (ConfigClient.AbilityHotbarTextVisibility + 1) % 3; + button.displayString = getTextVisibilityLabel(); } else { super.onEditorButtonPressed(button); } @@ -473,10 +492,18 @@ public class AbilityHotbarComponent extends HudComponent { private String getTextPositionLabel() { boolean h = ConfigClient.AbilityHotbarHorizontal; switch (ConfigClient.AbilityHotbarTextPosition) { - case 0: return "Text: Hide"; case 1: return h ? "Text: Above" : "Text: Left"; case 2: return h ? "Text: Below" : "Text: Right"; - default: return "Text: Hide"; + default: return h ? "Text: Below" : "Text: Right"; + } + } + + private String getTextVisibilityLabel() { + switch (ConfigClient.AbilityHotbarTextVisibility) { + case 0: return "Text: Shown"; + case 1: return "Text: Hidden"; + case 2: return "Text: Held"; + default: return "Text: Shown"; } } @@ -578,6 +605,25 @@ public class AbilityHotbarComponent extends HudComponent { return playerData.hotbarData.hasAnyAbilities(); } + /** + * Get cooldown progress for a hotbar slot. + * Per-ability cooldown abilities use their own cooldown; others use global. + * @return 1.0 = fully on cooldown, 0.0 = ready + */ + private float getCooldownProgressForSlot(int slotIndex) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) return 0f; + + String key = slots[slotIndex].abilityKey; + Ability ability = slots[slotIndex].ability; + + if (ability != null && ability.isPerAbilityCooldown()) { + return playerData.abilityData.getPerAbilityCooldownProgress(key); + } else { + return playerData.abilityData.getGlobalCooldownProgress(); + } + } + public void onCycleNext() { cycle(1); } diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java index f23ac583a..c91ad016b 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java @@ -47,7 +47,8 @@ public class AbilityHotbarSlotRenderer extends Gui { } public void drawCarousel(Minecraft mc, ScaledResolution sr, float cooldownProgress, - int cx, int cy, int size, boolean isCenter, float slotAlpha) { + int cx, int cy, int size, boolean isCenter, float slotAlpha, + boolean showText) { float nameAlpha = this.nameAlpha; boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; if (size <= 0 || slotAlpha <= 0) return; @@ -91,16 +92,16 @@ public class AbilityHotbarSlotRenderer extends Gui { GL11.glPopMatrix(); } - // Cooldown arc + // Cooldown overlay (all slots) if (cooldownProgress > 0 && abilityKey != null) { - drawCooldownArc(radius, cooldownProgress); + drawCooldownOverlay(radius, cooldownProgress, altTexture, slotAlpha); } GL11.glPopMatrix(); - // Ability name on center slot (respects text position config) + // Ability name on center slot (respects text position and visibility config) int textPos = ConfigClient.AbilityHotbarTextPosition; - if (textPos != 0 && isCenter && action != null && nameAlpha > 0) { + if (showText && isCenter && action != null && nameAlpha > 0) { FontRenderer fr = mc.fontRenderer; String name = getAbilityName(); if (name != null && !name.isEmpty()) { @@ -185,26 +186,65 @@ public class AbilityHotbarSlotRenderer extends Gui { GL11.glColor4f(1, 1, 1, 1); } - private void drawCooldownArc(float radius, float progress) { - progress = Math.min(1, Math.max(0, progress)); - if (progress <= 0) return; + /** + * Draw a cooldown overlay on the slot. + * progress: 1.0 = fully on cooldown (just started), 0.0 = ready + * Renders a filled shape covering the entire slot that transitions from red to green. + */ + private void drawCooldownOverlay(float radius, float progress, boolean altTexture, float slotAlpha) { + progress = Math.min(1f, Math.max(0f, progress)); + if (progress <= 0f) return; + + // Color: red (progress=1.0) → orange → yellow-green → green (progress→0.0) + float cr, cg, cb; + if (progress > 0.5f) { + float t = (progress - 0.5f) * 2f; // 1.0 at progress=1.0, 0.0 at progress=0.5 + cr = 0.8f; + cg = 0.15f + 0.25f * (1f - t); // 0.15 → 0.4 + cb = 0.1f; + } else if (progress > 0.2f) { + float t = (progress - 0.2f) / 0.3f; // 1.0 at 0.5, 0.0 at 0.2 + cr = 0.8f * t + 0.3f * (1f - t); // 0.8 → 0.3 + cg = 0.4f * t + 0.7f * (1f - t); // 0.4 → 0.7 + cb = 0.1f; + } else { + float t = progress / 0.2f; // 1.0 at 0.2, 0.0 at 0.0 + cr = 0.3f * t + 0.1f * (1f - t); // 0.3 → 0.1 + cg = 0.7f * t + 0.7f * (1f - t); // 0.7 + cb = 0.1f + 0.1f * (1f - t); // 0.1 → 0.2 + } + + // Semi-transparent so icon is visible underneath; fade out near end + float overlayAlpha = 0.5f * slotAlpha * Math.min(1f, progress * 3f); GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor4f(0.1f, 0.1f, 0.1f, 0.7f); + GL11.glColor4f(cr, cg, cb, overlayAlpha); - GL11.glBegin(GL11.GL_TRIANGLE_FAN); - GL11.glVertex2f(0, 0); - int steps = (int) (CIRCLE_SEGMENTS * progress) + 1; - for (int i = 0; i <= steps; i++) { - double angle = -Math.PI / 2 + 2 * Math.PI * i * progress / steps; - GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + if (altTexture) { + // Square slot: full filled rectangle + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(-radius, -radius); + GL11.glVertex2f(radius, -radius); + GL11.glVertex2f(radius, radius); + GL11.glVertex2f(-radius, radius); + GL11.glEnd(); + } else { + // Circle slot: full filled circle + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); } - GL11.glEnd(); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); GL11.glColor4f(1, 1, 1, 1); } diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java index 0f66036ae..1d0180463 100644 --- a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java @@ -525,6 +525,22 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener { } int textW = fr.getStringWidth(stateText); fr.drawStringWithShadow(prefix + stateText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, toggleState > 0 ? 0x55FF55 : 0x888888); + y += fr.FONT_HEIGHT + 3; + } + + // Cooldown info + if (ability.getCooldownTicks() > 0) { + float seconds = ability.getCooldownTicks() / 20.0f; + String cdText = StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s"; + int textW2 = fr.getStringWidth(cdText); + fr.drawStringWithShadow("\u00A77" + cdText, panelInnerLeft + (panelInnerWidth - textW2) / 2, y, 0xAAAAAA); + y += fr.FONT_HEIGHT + 3; + + if (ability.isPerAbilityCooldown()) { + String perText = "[" + StatCollector.translateToLocal("ability.perAbilityCooldown") + "]"; + int ptW = fr.getStringWidth(perText); + fr.drawStringWithShadow("\u00A7e" + perText, panelInnerLeft + (panelInnerWidth - ptW) / 2, y, 0xFFFF55); + } } } } @@ -663,6 +679,10 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener { if (ability.isToggleable()) { lines.add("\u00A7a[" + StatCollector.translateToLocal("gui.toggle") + "]"); } + if (ability.getCooldownTicks() > 0) { + float seconds = ability.getCooldownTicks() / 20.0f; + lines.add("\u00A77" + StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s"); + } } drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index 5c1dc6c1a..3616627f4 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -114,7 +114,7 @@ public class ConfigClient { public static Property AbilityHotbarAltTextureProperty; public static boolean AbilityHotbarAltTexture = false; - // 0=Hide, 1=Above(H)/Left(V), 2=Below(H)/Right(V) + // 1=Above(H)/Left(V), 2=Below(H)/Right(V) public static Property AbilityHotbarTextPositionProperty; public static int AbilityHotbarTextPosition = 2; @@ -126,6 +126,10 @@ public class ConfigClient { public static Property AbilityHotbarShowAlwaysProperty; public static boolean AbilityHotbarShowAlways = true; + // Text Visibility: 0=Shown, 1=Hidden, 2=Held (only while HUD key held) + public static Property AbilityHotbarTextVisibilityProperty; + public static int AbilityHotbarTextVisibility = 0; + /** * Texture Properties **/ @@ -232,7 +236,7 @@ public class ConfigClient { AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", false, "Use rounded square instead of circle slots"); AbilityHotbarAltTexture = AbilityHotbarAltTextureProperty.getBoolean(); - AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (0=Hide, 1=Above/Left, 2=Below/Right)"); + AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (1=Above/Left, 2=Below/Right)"); AbilityHotbarTextPosition = AbilityHotbarTextPositionProperty.getInt(2); AbilityHotbarVisibleSlotsProperty = config.get(HUD, "Ability Hotbar Visible Slots", 5, "Max visible slots in hotbar (3, 5, or 7)"); @@ -241,6 +245,9 @@ public class ConfigClient { AbilityHotbarShowAlwaysProperty = config.get(HUD, "Ability Hotbar Show Always", true, "Always show hotbar (false = only while HUD key is held)"); AbilityHotbarShowAlways = AbilityHotbarShowAlwaysProperty.getBoolean(true); + AbilityHotbarTextVisibilityProperty = config.get(HUD, "Ability Hotbar Text Visibility", 0, "Text visibility (0=Shown, 1=Hidden, 2=Held)"); + AbilityHotbarTextVisibility = AbilityHotbarTextVisibilityProperty.getInt(0); + // General AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side."); AllowClientScripts = AllowClientScriptsProperty.getBoolean(true); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 72df5b16b..0e32a37e7 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -8,6 +8,7 @@ import kamkeel.npcs.controllers.data.ability.IAbilityAction; import kamkeel.npcs.controllers.data.ability.ToggleEntry; import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; @@ -225,14 +226,30 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA @Override protected void rollCooldown(Ability ability) { - if (!ability.isIgnoreCooldown()) { - cooldownEndTime = getWorldTime() + ability.getCooldownTicks(); + if (ability.isIgnoreCooldown()) return; + + int duration = ability.getCooldownTicks(); + long endTime = getWorldTime() + duration; + + if (ability.isPerAbilityCooldown()) { + // Per-ability: only this ability goes on cooldown + if (currentAbilityKey != null) { + setPerAbilityCooldown(currentAbilityKey, endTime, duration); + } + } else { + // Global: all global-cooldown abilities share this cooldown + cooldownEndTime = endTime; + globalCooldownDuration = duration; } + syncCooldownToClient(); } @Override protected void rollChainCooldown(ChainedAbility chain) { - cooldownEndTime = getWorldTime() + chain.getCooldownTicks(); + int duration = chain.getCooldownTicks(); + cooldownEndTime = getWorldTime() + duration; + globalCooldownDuration = duration; + syncCooldownToClient(); } @Override @@ -372,8 +389,14 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA return true; } - // Check universal cooldown (abilities can optionally ignore it) - if (!ability.isIgnoreCooldown() && isOnCooldown()) return false; + // Check cooldown (per-ability cooldowns are independent from global) + if (!ability.isIgnoreCooldown()) { + if (ability.isPerAbilityCooldown()) { + if (isOnPerAbilityCooldown(key)) return false; + } else { + if (isOnCooldown()) return false; + } + } // Fire extender start hook (e.g., resource cost checks) if (!AbilityController.Instance.fireOnAbilityStart(ability, player, null)) { @@ -428,6 +451,18 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA EntityPlayer player = playerData.player; if (player instanceof EntityPlayerMP) { PlayerAbilitySyncPacket.sendToPlayer((EntityPlayerMP) player); + syncCooldownToClient(); + } + } + + /** + * Sync cooldown state (global + per-ability) to the client. + * Sent as a lightweight packet separate from full ability sync. + */ + public void syncCooldownToClient() { + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + AbilityCooldownSyncPacket.sendToPlayer((EntityPlayerMP) player); } } @@ -547,9 +582,15 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA /** * Check if a specific ability key is on cooldown. - * Currently uses universal cooldown (same for all abilities). + * Respects per-ability cooldown if the ability has it enabled. */ public boolean isOnCooldown(String key, EntityPlayer player) { + if (AbilityController.Instance != null) { + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability != null && ability.isPerAbilityCooldown()) { + return isOnPerAbilityCooldown(key); + } + } return isOnCooldown(player); } @@ -560,17 +601,21 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA /** * Reset cooldown for a specific ability key. - * Currently resets the universal cooldown. + * Resets per-ability cooldown if applicable, and global cooldown. */ public void resetCooldown(String key) { + resetPerAbilityCooldown(key); cooldownEndTime = 0; + syncCooldownToClient(); } /** - * Reset all cooldowns. + * Reset all cooldowns (global + all per-ability). */ public void resetAllCooldowns() { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + syncCooldownToClient(); } // ═══════════════════════════════════════════════════════════════════ @@ -604,6 +649,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA @Override public void resetCooldown() { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + syncCooldownToClient(); } // ═══════════════════════════════════════════════════════════════════ @@ -656,6 +703,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA if (clearCooldowns) { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); } interruptCooldownRolled = false; diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 810100e47..c2d575224 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2,7 +2,7 @@ customnpcs.defaultTextColor=404040 key.categories.customnpc=CustomNPC+ key.customnpcs.special=Special Key -key.customnpcs.abilityHudKey=Ability HUD Key +key.customnpcs.abilityHudKey=HUD Key key.npcInventory=NPC Inventory entity.CustomNpc.name=Custom Npc @@ -1672,6 +1672,7 @@ ability.cnpc.sweeper=Sweeper ability.weight=Weight ability.windUpTicks=Wind Up ability.cooldownTicks=Cooldown +ability.perAbilityCooldown=Per-Ability ability.lockMovement=Lock Movement ability.rotationMode=Rotation ability.rotationPhase=Phase From 5edc9b50474853339980c2f277f72999dab7ba26 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:49:50 -0500 Subject: [PATCH 11/51] Allow Externals to Modify Projectile Damage --- .../kamkeel/npcs/controllers/AbilityController.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index f706ff585..1c993e818 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -959,6 +959,17 @@ public class AbilityController implements IAbilityHandler { return false; } + /** + * Fire modifyProjectileDamage on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { + float damage = baseDamage; + for (IAbilityExtender ext : extenders) { + damage = ext.modifyProjectileDamage(ability, caster, damage); + } + return damage; + } + // ═══════════════════════════════════════════════════════════════════════════ // IAbilityHandler // ═══════════════════════════════════════════════════════════════════════════ From bc9342c2ebe772e4acbaca26f83d9bc70a4bc4f1 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:50:07 -0500 Subject: [PATCH 12/51] Guard Ability now reflects it has Damage when it canCounter --- .../npcs/controllers/data/ability/type/AbilityGuard.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java index 24489b9eb..1a1555f11 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java @@ -66,6 +66,11 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.counterAnimationName = "Ability_Guard_Counter"; } + @Override + public boolean hasDamage() { + return canCounter; + } + @Override public boolean allowBurst() { return false; From 4bd149c01bf93f5d668bb866f95f6e6e7e62ed5d Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:50:41 -0500 Subject: [PATCH 13/51] Check Barrier Collisions within Laser Shot --- .../npcs/entity/EntityAbilityLaser.java | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 38808cad9..736330cdd 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -14,6 +14,7 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.EventHooks; +import noppes.npcs.entity.EntityNPCInterface; import java.util.HashSet; import java.util.List; @@ -369,6 +370,109 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { return true; } + // ==================== BARRIER COLLISION ==================== + + /** + * Override barrier collision for lasers. The base class uses projectile position/velocity + * which doesn't work for lasers (posX/Y/Z stays at origin, motionX/Y/Z is zero). + * Instead, performs line-sphere intersection against domes. + */ + @Override + @SuppressWarnings("unchecked") + protected boolean checkBarrierCollision() { + if (currentLength <= 0 || fullyExtended) return false; + + // Search box covers the full laser line plus barrier search range + double searchRange = MAX_ENTITY_RADIUS + 5; + double minX = Math.min(startX, endX) - searchRange; + double minY = Math.min(startY, endY) - searchRange; + double minZ = Math.min(startZ, endZ) - searchRange; + double maxX = Math.max(startX, endX) + searchRange; + double maxY = Math.max(startY, endY) + searchRange; + double maxZ = Math.max(startZ, endZ) + searchRange; + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + + List barriers = worldObj.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead || barrier.isCharging()) continue; + if (barrier.getOwnerEntityId() == this.ownerEntityId) continue; + + // Same-faction NPC check + Entity bOwner = barrier.getOwnerEntity(); + Entity lOwner = this.getOwnerEntity(); + if (bOwner instanceof EntityNPCInterface && lOwner instanceof EntityNPCInterface) { + if (((EntityNPCInterface) bOwner).faction.id == ((EntityNPCInterface) lOwner).faction.id) { + continue; + } + } + + if (barrier instanceof EntityEnergyDome) { + EntityEnergyDome dome = (EntityEnergyDome) barrier; + float intersectDist = getLineSphereIntersection(dome); + if (intersectDist >= 0) { + // Truncate laser at dome surface + currentLength = intersectDist; + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + fullyExtended = true; + + float damage = getModifiedDamage(); + dome.onProjectileHit(this, damage); + return false; // Don't kill laser — it's truncated and will linger + } + } else { + // Non-dome barriers: fall through to standard check + if (barrier.isIncomingProjectile(this)) { + float damage = getModifiedDamage(); + if (barrier.onProjectileHit(this, damage)) { + hasHit = true; + this.setDead(); + return true; + } + } + } + } + return false; + } + + /** + * Line-sphere intersection between the laser line segment and a dome. + * Returns the distance along the laser direction to the first entry point, + * or -1 if no intersection from outside. + */ + private float getLineSphereIntersection(EntityEnergyDome dome) { + double cx = dome.posX; + double cy = dome.posY; + double cz = dome.posZ; + float radius = dome.getDomeRadius(); + + // If laser origin is inside the dome, don't block (outgoing) + double ocX = startX - cx; + double ocY = startY - cy; + double ocZ = startZ - cz; + double originDistSq = ocX * ocX + ocY * ocY + ocZ * ocZ; + if (originDistSq < (double) radius * radius) return -1; + + // Solve: |start + t*dir - C|^2 = R^2 + // a*t^2 + b*t + c = 0 + double a = dirX * dirX + dirY * dirY + dirZ * dirZ; + double b = 2.0 * (dirX * ocX + dirY * ocY + dirZ * ocZ); + double c = originDistSq - (double) radius * radius; + + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0) return -1; + + double sqrtD = Math.sqrt(discriminant); + double t1 = (-b - sqrtD) / (2.0 * a); // Entry point + + if (t1 >= 0 && t1 <= currentLength) { + return (float) t1; + } + + return -1; + } + // ==================== GETTERS FOR RENDERER ==================== public void setLockVerticalDirection(boolean lock) { From a6265d7ba38dddc70a9c28b75d8264ab9ecfc8f0 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:50:56 -0500 Subject: [PATCH 14/51] Forgot to Commit modifyProjectileDamage --- .../controllers/data/ability/IAbilityExtender.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java index e3e7e5c0b..2bb179cc2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java @@ -73,4 +73,18 @@ public interface IAbilityExtender { double knockbackDirX, double knockbackDirZ) { return false; } + + /** + * Called to modify outgoing projectile damage before it hits a barrier or is used in other contexts. + * Unlike onAbilityDamage (chain of responsibility), this is cumulative — all extenders apply their + * modifications in sequence, each receiving the previous extender's output. + * + * @param ability The source ability of the projectile + * @param caster The entity that fired the projectile + * @param baseDamage The base damage from the ability configuration + * @return The modified damage value + */ + default float modifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { + return baseDamage; + } } From cb57e26d042de98957e2792b549c22f561ac3e64 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 03:51:11 -0500 Subject: [PATCH 15/51] Modified Damage on Energy Projectile System --- .../npcs/entity/EntityEnergyProjectile.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index 4f0c16e50..8e8b62780 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -330,7 +330,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead) continue; if (barrier.isIncomingProjectile(this)) { - if (barrier.onProjectileHit(this, getDamage())) { + float damage = getModifiedDamage(); + if (barrier.onProjectileHit(this, damage)) { hasHit = true; this.setDead(); return true; @@ -341,6 +342,22 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { return false; } + /** + * Get the projectile damage modified by extenders (e.g. DBC damage scaling). + * Falls back to base getDamage() when no sourceAbility or no extenders modify it. + */ + protected float getModifiedDamage() { + float damage = getDamage(); + if (sourceAbility != null) { + Entity owner = getOwnerEntity(); + if (owner instanceof EntityLivingBase) { + damage = AbilityController.Instance.fireModifyProjectileDamage( + sourceAbility, (EntityLivingBase) owner, damage); + } + } + return damage; + } + // ==================== POSITION INTERPOLATION ==================== @Override From 14545818bd25f38ac717a1434fa1bf4a0eb504ee Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 13:13:45 -0500 Subject: [PATCH 16/51] Fix Animation Syncing for Built in --- src/main/java/noppes/npcs/CustomNpcs.java | 8 ++++++++ .../noppes/npcs/controllers/AnimationController.java | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index ff2d13031..ca2be8968 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -335,6 +335,14 @@ public class CustomNpcs { @EventHandler public void loadComplete(FMLLoadCompleteEvent ev) { proxy.buildPackageIndex(); + + // Load built-in animations on the client so they're available for ability preview. + // On dedicated servers, AnimationController.load() only runs on the server JVM, + // leaving the client without built-in animation data. In singleplayer, load() + // runs later during server start and reloads everything, so this is harmless. + if (FMLCommonHandler.instance().getSide().isClient()) { + AnimationController.Instance.loadClientBuiltIns(); + } } @EventHandler diff --git a/src/main/java/noppes/npcs/controllers/AnimationController.java b/src/main/java/noppes/npcs/controllers/AnimationController.java index bfbf978d2..e9a64bfe1 100644 --- a/src/main/java/noppes/npcs/controllers/AnimationController.java +++ b/src/main/java/noppes/npcs/controllers/AnimationController.java @@ -213,6 +213,18 @@ public class AnimationController implements IAnimationHandler { } } + /** + * Loads built-in animations for client-side usage. + * On dedicated servers, AnimationController.load() never runs on the client JVM, + * so built-in animations would be missing for client-only systems like ability preview. + * This method loads just the built-in animations (from assets and registered addons) + * without touching user animations or world save data. + */ + public void loadClientBuiltIns() { + loadBuiltInAnimations(); + loadRegisteredBuiltIns(); + } + private File getDir() { return new File(CustomNpcs.getWorldSaveDirectory(), "animations"); } From 09c2085270f0442f23ce8c2c2a49ce529ff43479 Mon Sep 17 00:00:00 2001 From: Vidal Date: Fri, 20 Feb 2026 18:58:41 -0300 Subject: [PATCH 17/51] Overhauled Condition system --- .../npcs/controllers/AbilityController.java | 14 +- .../controllers/data/ability/Ability.java | 15 +- .../data/ability/ChainedAbility.java | 15 +- .../data/ability/ConditionField.java | 197 ------------------ .../data/ability/IAbilityAction.java | 3 +- .../data/ability/IAbilityCondition.java | 94 --------- .../ability/conditions/AbilityCondition.java | 84 ++++++++ .../conditions/ConditionHPThreshold.java | 99 +++++++++ .../ability/conditions/ConditionHitCount.java | 67 ++++++ .../gui/advanced/SubGuiAbilityConfig.java | 90 ++++---- .../advanced/SubGuiChainedAbilityConfig.java | 121 +++++------ 11 files changed, 385 insertions(+), 414 deletions(-) delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 1c993e818..f226a505c 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -1,6 +1,9 @@ package kamkeel.npcs.controllers; import kamkeel.npcs.controllers.data.ability.*; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; @@ -54,7 +57,7 @@ public class AbilityController implements IAbilityHandler { private final List fieldProviders = new ArrayList<>(); private final List chainedFieldProviders = new ArrayList<>(); private final List extenders = new ArrayList<>(); - private final Map> conditionTypes = new HashMap<>(); + private final Map> conditionTypes = new HashMap<>(); private final List> flightCheckers = new ArrayList<>(); // ── Legacy Migration ───────────────────────────────────────────────────── @@ -147,7 +150,8 @@ public class AbilityController implements IAbilityHandler { } private void registerBuiltinConditionTypes() { - registerCondition(IAbilityCondition.ConditionHPAbove::new); + registerCondition(ConditionHPThreshold::new); + registerCondition(ConditionHitCount::new); } // ═══════════════════════════════════════════════════════════════════════════ @@ -880,8 +884,8 @@ public class AbilityController implements IAbilityHandler { return extenders; } - public void registerCondition(Supplier conditionFactory) { - IAbilityCondition temp = conditionFactory.get(); + public void registerCondition(Supplier conditionFactory) { + AbilityCondition temp = conditionFactory.get(); String typeId = temp.getTypeId(); if (conditionTypes.containsKey(typeId)) { LogWriter.info("AbilityController: Overwriting Condition type: " + typeId); @@ -889,7 +893,7 @@ public class AbilityController implements IAbilityHandler { conditionTypes.put(typeId, conditionFactory); } - public Supplier getConditionType(String key) { + public Supplier getConditionType(String key) { return conditionTypes.get(key); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 3563fe892..25cb77747 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.telegraph.Telegraph; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; @@ -58,7 +59,7 @@ public abstract class Ability implements IAbility, IAbilityAction { // Selection protected int weight = 10; protected boolean enabled = true; - protected List conditions = new ArrayList<>(); + protected List conditions = new ArrayList<>(); // Targeting protected TargetingMode targetingMode = TargetingMode.AGGRO_TARGET; @@ -1231,7 +1232,7 @@ public abstract class Ability implements IAbility, IAbilityAction { // ═══════════════════════════════════════════════════════════════════ public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { if (!c.check(caster, target)) return false; } return true; @@ -1241,7 +1242,7 @@ public abstract class Ability implements IAbility, IAbilityAction { * Check conditions for a player caster, skipping target-requiring conditions. */ public boolean checkConditionsForPlayer(EntityLivingBase caster) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { if (c.requiresTarget()) continue; if (!c.check(caster, null)) return false; } @@ -1310,7 +1311,7 @@ public abstract class Ability implements IAbility, IAbilityAction { // Conditions NBTTagList condList = new NBTTagList(); - for (Condition c : conditions) condList.appendTag(c.writeNBT()); + for (AbilityCondition c : conditions) condList.appendTag(c.writeNBT()); nbt.setTag("conditions", condList); // Effects @@ -1397,7 +1398,7 @@ public abstract class Ability implements IAbility, IAbilityAction { conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); for (int i = 0; i < condList.tagCount(); i++) { - Condition c = Condition.fromNBT(condList.getCompoundTagAt(i)); + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); if (c != null) conditions.add(c); } @@ -1935,11 +1936,11 @@ public abstract class Ability implements IAbility, IAbilityAction { return customData; } - public List getConditions() { + public List getConditions() { return conditions; } - public void addCondition(Condition c) { + public void addCondition(AbilityCondition c) { conditions.add(c); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java index 5de37416e..5a80166c7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java @@ -1,6 +1,7 @@ package kamkeel.npcs.controllers.data.ability; import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -57,7 +58,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { /** * Chain-level conditions (individual ability conditions are ignored). */ - private List conditions = new ArrayList<>(); + private List conditions = new ArrayList<>(); /** * Ordered list of ability entries to execute. @@ -185,11 +186,11 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { return UserType.NPC_ONLY; } - public List getConditions() { + public List getConditions() { return conditions; } - public void setConditions(List conditions) { + public void setConditions(List conditions) { this.conditions = conditions != null ? conditions : new ArrayList<>(); } @@ -279,7 +280,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { * Check all chain-level conditions against the caster and target. */ public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { if (!c.check(caster, target)) { return false; } @@ -291,7 +292,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { * Check conditions for player use (skip target-requiring conditions). */ public boolean checkConditionsForPlayer(EntityLivingBase caster) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { if (c.requiresTarget()) continue; if (!c.check(caster, null)) { return false; @@ -382,7 +383,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { // Conditions NBTTagList condList = new NBTTagList(); - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { condList.appendTag(c.writeNBT()); } nbt.setTag("Conditions", condList); @@ -416,7 +417,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { conditions.clear(); NBTTagList condList = nbt.getTagList("Conditions", 10); for (int i = 0; i < condList.tagCount(); i++) { - Condition c = Condition.fromNBT(condList.getCompoundTagAt(i)); + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); if (c != null) { conditions.add(c); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java deleted file mode 100644 index d96178759..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/ConditionField.java +++ /dev/null @@ -1,197 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import net.minecraft.nbt.NBTTagCompound; - -public abstract class ConditionField { - protected final String key; - protected final String label; - protected final Class type; // Float.class, Integer.class, etc - protected T value; - - public ConditionField(String key, String label, Class type, T defaultValue) { - this.key = key; - this.label = label; - this.type = type; - this.value = defaultValue; - } - - public T getValue() { - return value; - } - - public void setValue(T value) { - this.value = value; - } - - public String getKey() { - return key; - } - - public String getLabel() { - return label; - } - - public Class getType() { - return type; - } - - public abstract void writeNBT(NBTTagCompound nbt); - - public abstract void readNBT(NBTTagCompound nbt); - - public static ConditionField intField(String key, String label, int defaultValue) { - return intField(key, label, defaultValue, 0, Integer.MAX_VALUE); - } - - public static ConditionField intField(String key, String label, int defaultValue, int min, int max) { - return new NumberField<>(key, label, Integer.class, defaultValue, min, max); - } - - public static ConditionField doubleField(String key, String label, double defaultValue) { - return doubleField(key, label, defaultValue, 0, Double.MAX_VALUE); - } - - public static ConditionField doubleField(String key, String label, double defaultValue, double min, double max) { - return new NumberField<>(key, label, Double.class, defaultValue, min, max); - } - - public static ConditionField floatField(String key, String label, float defaultValue) { - return floatField(key, label, defaultValue, 0, Float.MAX_VALUE); - } - - public static ConditionField floatField(String key, String label, float defaultValue, float min, float max) { - return new NumberField<>(key, label, Float.class, defaultValue, min, max); - } - - public static ConditionField stringField(String key, String label) { - return new StringField(key, label, ""); - } - - public static ConditionField stringField(String key, String label, String defaultValue) { - return new StringField(key, label, defaultValue); - } - - public static ConditionField booleanField(String key, String label, boolean defaultValue) { - return new BoolField(key, label, defaultValue); - } - - public static > ConditionField enumField(String key, String label, E defaultValue, Class enumClass) { - return new EnumField<>(key, label, defaultValue, enumClass); - } - - public static > ConditionField enumField(String key, String label, E defaultValue) { - return new EnumField<>(key, label, defaultValue, defaultValue.getDeclaringClass()); - } - - private static class NumberField> extends ConditionField { - private T min; - private T max; - - public NumberField(String key, String label, Class type, T defaultValue, T min, T max) { - super(key, label, type, defaultValue); - this.min = min; - this.max = max; - } - - @Override - public void setValue(T value) { - if (value.compareTo(min) < 0) { - this.value = min; - } else if (value.compareTo(max) > 0) { - this.value = max; - } else { - this.value = value; - } - } - - public NumberField min(T value) { - this.min = value; - return this; - } - - public NumberField max(T value) { - this.max = value; - return this; - } - - @Override - public void writeNBT(NBTTagCompound nbt) { - if (value instanceof Integer) nbt.setInteger(key, (Integer) value); - else if (value instanceof Float) nbt.setFloat(key, (Float) value); - else if (value instanceof Double) nbt.setDouble(key, (Double) value); - else if (value instanceof Long) nbt.setLong(key, (Long) value); - } - - @Override - @SuppressWarnings("unchecked") - public void readNBT(NBTTagCompound nbt) { - if (!nbt.hasKey(key)) return; - T v; - Class t = type; - if (t == Integer.class) v = (T) (Integer) nbt.getInteger(key); - else if (t == Float.class) v = (T) (Float) nbt.getFloat(key); - else if (t == Double.class) v = (T) (Double) nbt.getDouble(key); - else if (t == Long.class) v = (T) (Long) nbt.getLong(key); - else return; - setValue(v); - } - } - - private static class StringField extends ConditionField { - public StringField(String key, String label, String defaultValue) { - super(key, label, String.class, defaultValue); - } - - @Override - public void writeNBT(NBTTagCompound nbt) { - nbt.setString(key, value); - } - - @Override - public void readNBT(NBTTagCompound nbt) { - setValue(nbt.getString(key)); - } - } - - private static class BoolField extends ConditionField { - public BoolField(String key, String label, boolean defaultValue) { - super(key, label, Boolean.class, defaultValue); - } - - @Override - public void writeNBT(NBTTagCompound nbt) { - nbt.setBoolean(key, value); - } - - @Override - public void readNBT(NBTTagCompound nbt) { - setValue(nbt.getBoolean(key)); - } - } - - private static class EnumField> extends ConditionField { - private final E[] options; - - public EnumField(String key, String label, E defaultValue, Class enumClass) { - super(key, label, enumClass, defaultValue); - this.options = enumClass.getEnumConstants(); - } - - public E[] getOptions() { - return options; - } - - @Override - public void writeNBT(NBTTagCompound nbt) { - nbt.setString(key, value.name()); - } - - @Override - public void readNBT(NBTTagCompound nbt) { - if (!nbt.hasKey(key)) return; - try { - setValue(Enum.valueOf(type, nbt.getString(key))); - } catch (IllegalArgumentException ignored) {} - } - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java index a1f4ac777..612cd9145 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java @@ -1,5 +1,6 @@ package kamkeel.npcs.controllers.data.ability; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -30,7 +31,7 @@ public interface IAbilityAction { UserType getAllowedBy(); - List getConditions(); + List getConditions(); boolean checkConditions(EntityLivingBase caster, EntityLivingBase target); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java deleted file mode 100644 index 2c1b7e670..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityCondition.java +++ /dev/null @@ -1,94 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import kamkeel.npcs.controllers.AbilityController; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.LogWriter; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.function.Supplier; - -public interface IAbilityCondition { - /** - * Check if this condition is met. - * - * @param caster The entity that would use the ability (NPC or Player) - * @param target The current target (may be null for self-targeting abilities or players) - * @return true if the condition is satisfied - */ - boolean check(EntityLivingBase caster, EntityLivingBase target); - - UserType getUserType(); - - String getTypeId(); - - List> getFields(); - - default NBTTagCompound writeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("userType", getUserType().ordinal()); - nbt.setString("type", getTypeId()); - for (ConditionField field : getFields()) { - field.writeNBT(nbt); - } - return nbt; - } - - default void readNBT(NBTTagCompound nbt) { - for (ConditionField field : getFields()) { - field.readNBT(nbt); - } - } - - static IAbilityCondition fromNBT(NBTTagCompound nbt) { - String typeId = nbt.getString("type"); - Supplier factory = AbilityController.Instance.getConditionType(typeId); - if (factory == null) { - LogWriter.info("AbilityController: Unknown condition type: " + typeId); - return null; - } - IAbilityCondition condition = factory.get(); - condition.readNBT(nbt); - - return condition; - } - - class ConditionHPAbove implements IAbilityCondition { - ConditionField threshold = ConditionField.floatField("threshold", "threshold", 0.5f); - - public ConditionHPAbove() { - } - - @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - return caster.getHealth() / caster.getMaxHealth() > threshold.getValue(); - } - - @Override - public UserType getUserType() { - return UserType.BOTH; - } - - @Override - public String getTypeId() { - return "hp_above"; - } - - public float getThreshold() { - return threshold.getValue(); - } - - public void setThreshold(float threshold) { - this.threshold.setValue(threshold); - } - - @Override - public List> getFields() { - return Arrays.asList( - threshold - ); - } - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java new file mode 100644 index 000000000..15d345a4c --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -0,0 +1,84 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.LogWriter; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; +import java.util.function.Supplier; + +public abstract class AbilityCondition { + protected String typeId = ""; + protected String name = ""; + protected UserType userType = UserType.BOTH; + + /** + * Check if this condition is met. + * + * @param caster The entity that would use the ability (NPC or Player) + * @param target The current target (may be null for self-targeting abilities or players) + * @return true if the condition is satisfied + */ + public abstract boolean check(EntityLivingBase caster, EntityLivingBase target); + + public boolean requiresTarget() { + return false; + } + + public UserType getUserType() { + return userType; + } + + public void setUserType(UserType userType) { + this.userType = userType; + } + + public String getTypeId() { + return typeId; + } + + public String getName() { + return name; + } + + @SideOnly(Side.CLIENT) + public abstract List getAbilityDefinitions(List defs); + + public final NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("userType", getUserType().ordinal()); + nbt.setString("type", getTypeId()); + nbt.setString("name", getName()); + writeTypeNBT(nbt); + return nbt; + } + + public abstract void writeTypeNBT(NBTTagCompound nbt); + + public abstract void readTypeNBT(NBTTagCompound nbt); + + public final void readNBT(NBTTagCompound nbt) { + typeId = nbt.getString("type"); + name = nbt.getString("name"); + userType = UserType.fromOrdinal(nbt.getInteger("userType")); + readTypeNBT(nbt); + } + + public static AbilityCondition fromNBT(NBTTagCompound nbt) { + String typeId = nbt.getString("type"); + Supplier factory = AbilityController.Instance.getConditionType(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown condition type: " + typeId); + return null; + } + AbilityCondition condition = factory.get(); + condition.readNBT(nbt); + + return condition; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java new file mode 100644 index 000000000..3d647475f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -0,0 +1,99 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Collections; +import java.util.List; + +public class ConditionHPThreshold extends AbilityCondition{ + private float threshold = 0.5f; // 50% + private ThresholdType thresholdType = ThresholdType.ABOVE; + + public enum ThresholdType { + ABOVE { + @Override + public boolean test(float value, float threshold) { + return value > threshold; + } + }, + BELOW { + @Override + public boolean test(float value, float threshold) { + return value < threshold; + } + }; + + public abstract boolean test(float value, float threshold); + + public static ThresholdType fromOrdinal(int ordinal) { + ThresholdType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return ABOVE; + } + } + + public ConditionHPThreshold() { + this.typeId = "condition.cnpc.hp_threshold"; + this.name = "Health Threshold"; + this.userType = UserType.NPC_ONLY; + } + + @Override + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + float casterHP = caster.getHealth() / caster.getMaxHealth(); + float targetHP = target.getHealth() / target.getMaxHealth(); + + + return compare(casterHP, targetHP); + } + + public boolean compare(float casterHp, float targetHp) { + boolean casterCheck = thresholdType.test(casterHp, threshold); + boolean targetCheck = thresholdType.test(targetHp, threshold); + + switch (getUserType()) { + case BOTH: + return casterCheck && targetCheck; + case PLAYER_ONLY: + return casterCheck; + default: + return targetCheck; + } + } + + public float getThreshold() { + return threshold; + } + + public void setThreshold(float threshold) { + this.threshold = Math.max(0, threshold); + } + + public ThresholdType getThresholdType() { + return thresholdType; + } + + public void setThresholdType(ThresholdType thresholdType) { + this.thresholdType = thresholdType; + } + + @Override + public List getAbilityDefinitions(List defs) { + return Collections.emptyList(); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("threshold", threshold); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + threshold = nbt.getFloat("threshold"); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java new file mode 100644 index 000000000..385e7eb99 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -0,0 +1,67 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.Collections; +import java.util.List; + +public class ConditionHitCount extends AbilityCondition{ + private int requiredHits = 3; + private int withinTicks = 60; + + public ConditionHitCount() { + this.typeId = "condition.cnpc.hit_count"; + this.name = "Hit Count"; + this.userType = UserType.NPC_ONLY; + } + + @Override + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + if (caster instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) caster; + if (npc.abilities != null) { + return npc.abilities.getRecentHitCount(withinTicks) >= requiredHits; + } + } + + // For players, hit count tracking is not yet supported + return false; + } + + public int getRequiredHits() { + return requiredHits; + } + + public void setRequiredHits(int requiredHits) { + this.requiredHits = Math.max(0, requiredHits); + } + + public int getWithinTicks() { + return withinTicks; + } + + public void setWithinTicks(int withinTicks) { + this.withinTicks = Math.max(0, withinTicks); + } + + @Override + public List getAbilityDefinitions(List defs) { + return Collections.emptyList(); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("requiredHits", requiredHits); + nbt.setInteger("withinTicks", withinTicks); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + requiredHits = nbt.getInteger("requiredHits"); + withinTicks = nbt.getInteger("withinTicks"); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index 3aa153f59..edbf676fb 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -60,7 +60,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi public SubGuiAbilityConfig(Ability ability, IAbilityConfigCallback callback) { this.ability = ability; this.callback = callback; - this.conditions = new ArrayList<>(ability.getConditions()); +// this.conditions = new ArrayList<>(ability.getConditions()); this.fieldDefs = ability.getAllDefinitions(); discoverCustomTabs(); @@ -230,51 +230,51 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi // ═══════════════════════════════════════════════════════════════════════════ private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) { - y += 3; - sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); - y += 15; - - for (int i = 0; i < conditions.size() && i < 3; i++) { - Condition cond = conditions.get(i); - String condName = getConditionDisplayName(cond); - sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); - sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); - sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); - y += 22; - } - - if (conditions.size() < 3) { - sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); - y += ROW_H; - } - +// y += 3; +// sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); +// y += 15; +// +// for (int i = 0; i < conditions.size() && i < 3; i++) { +// Condition cond = conditions.get(i); +// String condName = getConditionDisplayName(cond); +// sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); +// sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); +// sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); +// y += 22; +// } +// +// if (conditions.size() < 3) { +// sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); +// y += ROW_H; +// } +// return y; } - private String getConditionDisplayName(Condition cond) { - if (cond == null) return "None"; - String typeId = cond.getTypeId(); - switch (typeId) { - case "hp_above": - return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hp_below": - return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_above": - return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_below": - return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hit_count": - Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; - return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; - default: - return typeId; - } - } +// private String getConditionDisplayName(Condition cond) { +// if (cond == null) return "None"; +// String typeId = cond.getTypeId(); +// switch (typeId) { +// case "hp_above": +// return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; +// case "hp_below": +// return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; +// case "target_hp_above": +// return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; +// case "target_hp_below": +// return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; +// case "hit_count": +// Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; +// return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; +// default: +// return typeId; +// } +// } - private float getConditionThreshold(Condition cond) { - NBTTagCompound nbt = cond.writeNBT(); - return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; - } +// private float getConditionThreshold(Condition cond) { +// NBTTagCompound nbt = cond.writeNBT(); +// return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; +// } // ═══════════════════════════════════════════════════════════════════════════ // BUTTON EVENTS @@ -408,8 +408,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } protected void applyToAbility() { - ability.getConditions().clear(); - for (Condition c : conditions) ability.addCondition(c); +// ability.getConditions().clear(); +// for (Condition c : conditions) ability.addCondition(c); } public void loadAbility(Ability loadedAbility) { @@ -418,7 +418,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi nbt.setString("typeId", ability.getTypeId()); ability.readNBT(nbt); - this.conditions = new ArrayList<>(ability.getConditions()); +// this.conditions = new ArrayList<>(ability.getConditions()); this.fieldDefs = ability.getAllDefinitions(); discoverCustomTabs(); initGui(); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index 565443c3d..35b9e9f7c 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -10,6 +10,7 @@ import kamkeel.npcs.controllers.data.ability.Condition; import kamkeel.npcs.controllers.data.ability.AbilityIconData; import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import net.minecraft.client.gui.GuiButton; @@ -22,11 +23,14 @@ import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.GuiScrollWindow; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityAction; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import noppes.npcs.client.gui.util.*; + +import java.util.ArrayList; import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; -import noppes.npcs.client.gui.util.ISubGuiListener; -import noppes.npcs.client.gui.util.ITextfieldListener; -import noppes.npcs.client.gui.util.SubGuiInterface; + import java.util.ArrayList; import java.util.Collections; @@ -34,6 +38,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; + /** * SubGui for editing a {@link ChainedAbility}. * Core tabs: General, Entries, Conditions. @@ -89,7 +94,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText private List fieldDefs; private List entries; - private List conditions; +// private List conditions; // Dynamic tabs injected by field providers (e.g., "Icon") private List extraTabs = new ArrayList<>(); @@ -128,7 +133,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText this.readOnlyEntries = readOnlyEntries; this.npcSlots = npcSlots; this.entries = new ArrayList<>(chain.getEntries()); - this.conditions = new ArrayList<>(chain.getConditions()); +// this.conditions = new ArrayList<>(chain.getConditions()); buildFieldDefs(); @@ -424,23 +429,23 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) { - y += 3; - sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); - y += 15; - - for (int i = 0; i < conditions.size() && i < 3; i++) { - Condition cond = conditions.get(i); - String condName = getConditionDisplayName(cond); - sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); - sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); - sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); - y += 22; - } - - if (conditions.size() < 3) { - sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); - y += ROW_H; - } +// y += 3; +// sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); +// y += 15; +// +// for (int i = 0; i < conditions.size() && i < 3; i++) { +// Condition cond = conditions.get(i); +// String condName = getConditionDisplayName(cond); +// sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); +// sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); +// sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); +// y += 22; +// } +// +// if (conditions.size() < 3) { +// sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); +// y += ROW_H; +// } return y; } @@ -618,29 +623,29 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private boolean handleConditionButton(int id) { - if (id >= COND_BASE && id < COND_END) { - int condIndex = (id - COND_BASE) / COND_STRIDE; - int action = (id - COND_BASE) % COND_STRIDE; - if (action == 0 || action == 1) { - if (condIndex < conditions.size()) { - editingConditionIndex = condIndex; - setSubGui(new SubGuiConditionEdit(conditions.get(condIndex))); - } - } else if (action == 2) { - if (condIndex < conditions.size()) { - conditions.remove(condIndex); - initGui(); - } - } - return true; - } - if (id == BTN_ADD_COND) { - if (conditions.size() < 3) { - editingConditionIndex = conditions.size(); - setSubGui(new SubGuiConditionEdit(null)); - } - return true; - } +// if (id >= COND_BASE && id < COND_END) { +// int condIndex = (id - COND_BASE) / COND_STRIDE; +// int action = (id - COND_BASE) % COND_STRIDE; +// if (action == 0 || action == 1) { +// if (condIndex < conditions.size()) { +// editingConditionIndex = condIndex; +// setSubGui(new SubGuiConditionEdit(conditions.get(condIndex))); +// } +// } else if (action == 2) { +// if (condIndex < conditions.size()) { +// conditions.remove(condIndex); +// initGui(); +// } +// } +// return true; +// } +// if (id == BTN_ADD_COND) { +// if (conditions.size() < 3) { +// editingConditionIndex = conditions.size(); +// setSubGui(new SubGuiConditionEdit(null)); +// } +// return true; +// } return false; } @@ -845,14 +850,14 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private void handleConditionEditClosed(SubGuiConditionEdit gui) { - Condition result = gui.getResult(); - if (result != null && editingConditionIndex >= 0) { - if (editingConditionIndex < conditions.size()) { - conditions.set(editingConditionIndex, result); - } else { - conditions.add(result); - } - } +// Condition result = gui.getResult(); +// if (result != null && editingConditionIndex >= 0) { +// if (editingConditionIndex < conditions.size()) { +// conditions.set(editingConditionIndex, result); +// } else { +// conditions.add(result); +// } +// } editingConditionIndex = -1; } @@ -890,10 +895,10 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } // Conditions - chain.getConditions().clear(); - for (Condition c : conditions) { - chain.getConditions().add(c); - } +// chain.getConditions().clear(); +// for (Condition c : conditions) { +// chain.getConditions().add(c); +// } // Remove consumed NPC slots (descending order to preserve indices) if (npcSlots != null && !consumedSlotIndices.isEmpty()) { From c121d0c4e21dd5afeafad0fc1c4760a525e35e9f Mon Sep 17 00:00:00 2001 From: somehussar <148253652+somehussar@users.noreply.github.com> Date: Sat, 21 Feb 2026 00:03:48 +0100 Subject: [PATCH 18/51] Fix missing spawndata. --- .../kamkeel/npcs/network/PacketHandler.java | 20 +-- .../npcs/network/enums/EnumDataPacket.java | 1 + .../packets/data/RequestProperSpawnData.java | 119 ++++++++++++++++++ .../noppes/npcs/client/ClientTickHandler.java | 4 + .../npcs/entity/EntityNPCInterface.java | 11 ++ 5 files changed, 137 insertions(+), 18 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index 766210559..8e784b5b8 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -8,24 +8,7 @@ import cpw.mods.fml.common.network.internal.FMLProxyPacket; import cpw.mods.fml.relauncher.Side; import io.netty.buffer.ByteBuf; import kamkeel.npcs.network.enums.EnumChannelType; -import kamkeel.npcs.network.packets.data.AchievementPacket; -import kamkeel.npcs.network.packets.data.ChatAlertPacket; -import kamkeel.npcs.network.packets.data.ChatBubblePacket; -import kamkeel.npcs.network.packets.data.ClonerPacket; -import kamkeel.npcs.network.packets.data.ConfigCommandPacket; -import kamkeel.npcs.network.packets.data.DisableMouseInputPacket; -import kamkeel.npcs.network.packets.data.LoginPacket; -import kamkeel.npcs.network.packets.data.MarkDataPacket; -import kamkeel.npcs.network.packets.data.OverlayQuestTrackingPacket; -import kamkeel.npcs.network.packets.data.ParticlePacket; -import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket; -import kamkeel.npcs.network.packets.data.PlayerUpdateSkinOverlaysPacket; -import kamkeel.npcs.network.packets.data.QuestCompletionPacket; -import kamkeel.npcs.network.packets.data.ScrollSelectedPacket; -import kamkeel.npcs.network.packets.data.SoundManagementPacket; -import kamkeel.npcs.network.packets.data.SwingPlayerArmPacket; -import kamkeel.npcs.network.packets.data.UpdateAnimationsPacket; -import kamkeel.npcs.network.packets.data.VillagerListPacket; +import kamkeel.npcs.network.packets.data.*; import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; @@ -583,6 +566,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new DialogPacket()); DATA_PACKET.registerPacket(new RolePacket()); DATA_PACKET.registerPacket(new WeaponNpcPacket()); + DATA_PACKET.registerPacket(new RequestProperSpawnData()); // Data | Script Packets DATA_PACKET.registerPacket(new ScriptedParticlePacket()); diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index bc6d7d1f9..ec351a2c9 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -23,6 +23,7 @@ public enum EnumDataPacket { DELETE_NPC, CLONE_NPC, WEAPON_NPC, + REQUEST_SPAWN_DATA, // Data SCROLL_LIST, diff --git a/src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java b/src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java new file mode 100644 index 000000000..afd013a74 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java @@ -0,0 +1,119 @@ +package kamkeel.npcs.network.packets.data; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.LogWriter; +import noppes.npcs.entity.EntityNPCInterface; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class RequestProperSpawnData extends AbstractPacket { + public static final String packetName = "Data|SpawnData"; + private static final int BATCH_LIMIT = 5; + + @SideOnly(Side.CLIENT) + private static final Set entitiesToFix = new HashSet<>(); + @SideOnly(Side.CLIENT) + private static long lastBatchAttemptMillis = 0; + + private int entityId; + + public RequestProperSpawnData() {} + + @SideOnly(Side.CLIENT) + public RequestProperSpawnData(int entityId) { + this.entityId = entityId; + } + + public static void clear() { + entitiesToFix.clear(); + } + + @Override + public Enum getType() { + return EnumDataPacket.REQUEST_SPAWN_DATA; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + @SideOnly(Side.CLIENT) + public void sendData(ByteBuf out) throws IOException { + out.writeInt(this.entityId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + return; + + int entityId = in.readInt(); + Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(entityId); + if (entity instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) entity; + NBTTagCompound compound = npc.writeSpawnData(); + compound.setInteger("EntityId", npc.getEntityId()); + PacketHandler.Instance.sendToPlayer(new UpdateNpcPacket(compound), (EntityPlayerMP) player); + } + } + + @SideOnly(Side.CLIENT) + public static void reportMissingData(EntityNPCInterface npc) { + int entityID = npc.getEntityId(); + + if (npc.immediateSpawnDataFixAttempts++ < 3) { + PacketClient.sendClient(new RequestProperSpawnData(entityID)); + } else { + entitiesToFix.add(entityID); + } + } + + @SideOnly(Side.CLIENT) + public static boolean canDoBatchUpdate() { + return System.currentTimeMillis() - lastBatchAttemptMillis >= 5000; + } + + @SideOnly(Side.CLIENT) + public static void handleBacklog() { + Minecraft mc = Minecraft.getMinecraft(); + if (mc == null || mc.theWorld == null || mc.thePlayer == null) + return; + + if (entitiesToFix.isEmpty()) + return; + // Remove entity checks if they're no longer loaded + entitiesToFix.removeIf( value -> !(Minecraft.getMinecraft().theWorld.getEntityByID(value) instanceof EntityNPCInterface) ); + + Iterator it = entitiesToFix.iterator(); + int count = 0; + + while (it.hasNext() && count < BATCH_LIMIT) { + PacketClient.sendClient(new RequestProperSpawnData(it.next())); + it.remove(); + count++; + } + + if (count != 0) { + lastBatchAttemptMillis = System.currentTimeMillis(); + } + } +} diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 1c16de390..a23a9195c 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -9,6 +9,7 @@ import kamkeel.npcs.client.renderer.lightning.LightningBolt; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.data.RequestProperSpawnData; import kamkeel.npcs.network.packets.player.CheckPlayerValue; import kamkeel.npcs.network.packets.player.InputDevicePacket; import kamkeel.npcs.network.packets.player.ScreenSizePacket; @@ -59,6 +60,7 @@ public class ClientTickHandler { if (mc.theWorld == null) { ClientCacheHandler.clearCache(); ClientAbilityState.reset(); + RequestProperSpawnData.clear(); } this.prevWorld = mc.theWorld; } @@ -199,6 +201,8 @@ public class ClientTickHandler { return; if (mc.theWorld.getTotalWorldTime() % 20 == 0) { // Update every second + if (RequestProperSpawnData.canDoBatchUpdate()) + RequestProperSpawnData.handleBacklog(); updateCompassMarks(); } } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 187ce583d..6cfb59553 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -68,6 +68,7 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.ServerChatEvent; import noppes.npcs.CustomItems; @@ -229,6 +230,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti public FlyingMoveHelper flyMoveHelper = new FlyingMoveHelper(this); public PathNavigate flyNavigator = new PathNavigateFlying(this, worldObj); + @SideOnly(Side.CLIENT) + public int immediateSpawnDataFixAttempts = 0; + public EntityNPCInterface(World world) { super(world); try { @@ -1829,10 +1833,17 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti try { readSpawnData(ByteBufUtils.readNBT(buf)); } catch (IOException e) { + RequestProperSpawnData.reportMissingData(this); } } public void readSpawnData(NBTTagCompound compound) { + if ((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))) { + RequestProperSpawnData.reportMissingData(this); + return; + } + + immediateSpawnDataFixAttempts = 0; stats.maxHealth = compound.getDouble("MaxHealth"); ais.setWalkingSpeed(compound.getInteger("Speed")); stats.hideKilledBody = compound.getBoolean("DeadBody"); From f620e820e831736b59451928e66f3ddb263c29b7 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 18:16:52 -0500 Subject: [PATCH 19/51] Dome, Panel Settings --- .../client/renderer/RenderEnergyDome.java | 2 +- .../client/renderer/RenderEnergyPanel.java | 2 +- .../data/ability/data/EnergyBarrierData.java | 14 + .../data/ability/type/energy/AbilityDome.java | 9 + .../type/energy/AbilityEnergyBarrier.java | 25 ++ .../npcs/entity/EntityAbilityLaser.java | 12 +- .../npcs/entity/EntityEnergyBarrier.java | 177 +++++++++++- .../kamkeel/npcs/entity/EntityEnergyDome.java | 263 ++++++++++++++---- .../npcs/entity/EntityEnergyPanel.java | 245 +++++++++++----- .../npcs/entity/EntityEnergyProjectile.java | 19 +- src/main/java/noppes/npcs/CustomNpcs.java | 1 + .../java/noppes/npcs/ServerEventsHandler.java | 47 ++++ .../noppes/npcs/client/ClientTickHandler.java | 35 +++ .../java/noppes/npcs/config/ConfigEnergy.java | 37 +++ .../noppes/npcs/config/LoadConfiguration.java | 3 + .../assets/customnpcs/lang/en_US.lang | 7 + 16 files changed, 752 insertions(+), 146 deletions(-) create mode 100644 src/main/java/noppes/npcs/config/ConfigEnergy.java diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java index 871d48461..7388d7ec2 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java @@ -34,7 +34,7 @@ public class RenderEnergyDome extends RenderEnergyBarrier { // Hit flash effect float flashAlpha = computeFlashAlpha(dome); - float innerScale = 0.95f; + float innerScale = 1.0f; // Render outer dome (translucent glow) if (dome.isOuterColorEnabled()) { diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java index 279c6902d..38bdd57b2 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java @@ -48,7 +48,7 @@ public class RenderEnergyPanel extends RenderEnergyBarrier { GL11.glPushMatrix(); GL11.glScalef(scale, scale, scale); - float innerScale = 0.9f; + float innerScale = 1.0f; float panelThickness = 0.1f; // Render outer panel (translucent glow) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java index ef9bcff57..6f3610376 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java @@ -31,6 +31,11 @@ public class EnergyBarrierData { public boolean meleeEnabled = false; public float meleeDamageMultiplier = 1.0f; + // Jail settings (dome only - captures entities inside at spawn) + public boolean jailEnabled = false; + public boolean damageProtection = false; + public float jailThreshold = 0.9f; + /** * Per-projectile-type damage multipliers. * Key is the ability typeId (e.g., "ability.cnpc.orb", "ability.cnpc.beam"). @@ -144,6 +149,9 @@ public class EnergyBarrierData { nbt.setInteger("barrierKnockbackTarget", knockbackTarget); nbt.setBoolean("barrierMelee", meleeEnabled); nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier); + nbt.setBoolean("barrierJail", jailEnabled); + nbt.setBoolean("barrierDmgProtect", damageProtection); + nbt.setFloat("barrierJailThreshold", jailThreshold); NBTTagCompound multNbt = new NBTTagCompound(); for (Map.Entry entry : damageMultipliers.entrySet()) { @@ -163,6 +171,9 @@ public class EnergyBarrierData { knockbackTarget = nbt.hasKey("barrierKnockbackTarget") ? nbt.getInteger("barrierKnockbackTarget") : 0; meleeEnabled = nbt.hasKey("barrierMelee") && nbt.getBoolean("barrierMelee"); meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f; + jailEnabled = nbt.hasKey("barrierJail") && nbt.getBoolean("barrierJail"); + damageProtection = nbt.hasKey("barrierDmgProtect") && nbt.getBoolean("barrierDmgProtect"); + jailThreshold = nbt.hasKey("barrierJailThreshold") ? nbt.getFloat("barrierJailThreshold") : 0.9f; damageMultipliers.clear(); if (nbt.hasKey("barrierMultipliers")) { @@ -183,6 +194,9 @@ public class EnergyBarrierData { copy.knockbackTarget = knockbackTarget; copy.meleeEnabled = meleeEnabled; copy.meleeDamageMultiplier = meleeDamageMultiplier; + copy.jailEnabled = jailEnabled; + copy.damageProtection = damageProtection; + copy.jailThreshold = jailThreshold; copy.damageMultipliers = new HashMap<>(damageMultipliers); return copy; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java index 78a317cc2..cdb8f6f2f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -135,5 +135,14 @@ public class AbilityDome extends AbilityEnergyBarrier { .range(1.0f, 50.0f)); defs.add(FieldDef.boolField("ability.followCaster", this::isFollowCaster, this::setFollowCaster) .hover("ability.hover.followCaster")); + + // Jail & protection section (dome-only: only enclosures can jail) + defs.add(FieldDef.section("ability.section.jail")); + defs.add(FieldDef.boolField("ability.jailEnabled", this::isJailEnabled, this::setJailEnabled) + .hover("ability.hover.jailEnabled")); + defs.add(FieldDef.floatField("ability.jailThreshold", this::getJailThreshold, this::setJailThreshold) + .range(0.1f, 1.0f).visibleWhen(this::isJailEnabled)); + defs.add(FieldDef.boolField("ability.damageProtection", this::isDamageProtection, this::setDamageProtection) + .hover("ability.hover.damageProtection")); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java index f78cf5654..d3b543885 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java @@ -232,6 +232,31 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { barrierData.meleeDamageMultiplier = mult; } + // Jail data + public boolean isJailEnabled() { + return barrierData.jailEnabled; + } + + public void setJailEnabled(boolean enabled) { + barrierData.jailEnabled = enabled; + } + + public boolean isDamageProtection() { + return barrierData.damageProtection; + } + + public void setDamageProtection(boolean enabled) { + barrierData.damageProtection = enabled; + } + + public float getJailThreshold() { + return barrierData.jailThreshold; + } + + public void setJailThreshold(float threshold) { + barrierData.jailThreshold = Math.max(0.1f, Math.min(1.0f, threshold)); + } + // ==================== GUI ==================== @SideOnly(Side.CLIENT) diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 736330cdd..8f9df2bb5 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -382,17 +382,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { protected boolean checkBarrierCollision() { if (currentLength <= 0 || fullyExtended) return false; - // Search box covers the full laser line plus barrier search range - double searchRange = MAX_ENTITY_RADIUS + 5; - double minX = Math.min(startX, endX) - searchRange; - double minY = Math.min(startY, endY) - searchRange; - double minZ = Math.min(startZ, endZ) - searchRange; - double maxX = Math.max(startX, endX) + searchRange; - double maxY = Math.max(startY, endY) + searchRange; - double maxZ = Math.max(startZ, endZ) + searchRange; - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - - List barriers = worldObj.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); + List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead || barrier.isCharging()) continue; if (barrier.getOwnerEntityId() == this.ownerEntityId) continue; diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java index a5d263075..1027fe93e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -5,12 +5,18 @@ import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.world.World; import noppes.npcs.EventHooks; import noppes.npcs.entity.EntityNPCInterface; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + /** * Base class for energy barrier entities (Dome, Panel). * Provides shared health, damage, hit flash, knockback target, @@ -19,6 +25,35 @@ import noppes.npcs.entity.EntityNPCInterface; */ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { + // ==================== ACTIVE BARRIER REGISTRY ==================== + private static final List> activeBarriers = new ArrayList<>(); + private boolean tracked = false; + + public static void trackBarrier(EntityEnergyBarrier barrier) { + activeBarriers.add(new WeakReference<>(barrier)); + } + + /** + * Get all living barriers in the given world. Auto-cleans dead refs. + */ + public static List getActiveBarriers(World world) { + List result = new ArrayList<>(); + Iterator> it = activeBarriers.iterator(); + while (it.hasNext()) { + EntityEnergyBarrier b = it.next().get(); + if (b == null || b.isDead) { + it.remove(); + } else if (b.worldObj == world) { + result.add(b); + } + } + return result; + } + + public static void clearAllBarriers() { + activeBarriers.clear(); + } + // ==================== BARRIER PROPERTIES ==================== protected EnergyBarrierData barrierData = new EnergyBarrierData(); protected float currentHealth; @@ -63,6 +98,65 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { */ protected abstract void knockbackEntities(); + /** + * Get the maximum extent of this barrier for distance pre-filtering. + * Dome returns radius, Panel returns max(width, height) / 2. + */ + public abstract float getMaxExtent(); + + /** + * Check if a generic (non-CNPC+) projectile is incoming toward this barrier. + * Uses the same geometric logic as isIncomingProjectile but with raw position data. + * + * @param posX, posY, posZ Current (or predicted) position of the projectile + * @param motionX, motionY, motionZ Current velocity of the projectile + * @param prevPosX, prevPosY, prevPosZ Previous position of the projectile + * @param ownerEntityId Entity ID of the projectile's shooter + */ + public abstract boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId); + + // ==================== GENERIC PROJECTILE HIT ==================== + + /** + * Apply damage from a generic (non-CNPC+) projectile to this barrier. + * Uses the typeId for damage multiplier lookup (e.g. "dbc.ki_attack"). + * + * @param projectileEntity The entity that hit the barrier (for context) + * @param damage Base damage to apply + * @param typeId Type identifier for damage multiplier lookup + * @return true if the barrier absorbed the hit (projectile should be destroyed) + */ + public boolean onGenericProjectileHit(Entity projectileEntity, float damage, String typeId) { + float multiplier = barrierData.getMultiplier(typeId); + float finalDamage = damage * multiplier; + + if (!worldObj.isRemote) { + float eventDamage = EventHooks.onEnergyBarrierHit(this, ownerEntityId, null, finalDamage); + if (eventDamage < 0) return false; + finalDamage = eventDamage; + } + + triggerHitFlash(); + + if (!barrierData.useHealth) { + return true; + } + + currentHealth -= finalDamage; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + + return true; + } + // ==================== PROJECTILE HIT ==================== /** @@ -146,8 +240,12 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { */ protected boolean updateBarrierTick() { if (!worldObj.isRemote) { - // Fire spawned event on first tick + // Track barrier and fire spawned event on first tick if (ticksAlive == 1) { + if (!tracked) { + trackBarrier(this); + tracked = true; + } EventHooks.onEnergyBarrierSpawned(this, ownerEntityId); } @@ -247,6 +345,83 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return AbilityTargetHelper.isAlly((EntityLivingBase) owner, entity); } + // ==================== CONTAINMENT & PROTECTION ==================== + + /** + * Check if an entity is geometrically inside this barrier's protected zone. + * Override in subclasses (dome checks sphere containment). + */ + public boolean isEntityInside(Entity entity) { + return false; + } + + /** + * Check if a damage source originates from outside this barrier. + * Uses geometry-specific containment check via isEntityInside(). + */ + public boolean isDamageFromOutside(DamageSource source) { + Entity attacker = source.getEntity(); + if (attacker == null) return true; // Environmental damage treated as outside + return !isEntityInside(attacker); + } + + /** + * Find a barrier that would protect the given entity from outside damage. + * Returns the barrier if: damageProtection is enabled AND entity is inside. + * Any entity inside a dome with damageProtection gets redirected damage. + */ + public static EntityEnergyBarrier getProtectingBarrier(Entity entity) { + if (entity == null || entity.worldObj == null) return null; + List barriers = getActiveBarriers(entity.worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier.isDead) continue; + if (!barrier.barrierData.damageProtection) continue; + if (barrier.isEntityInside(entity)) { + return barrier; + } + } + return null; + } + + /** + * Absorb damage from an external source. Reduces barrier health directly. + * Used by damage protection to redirect attacks on inside entities to the barrier. + * + * @param amount The damage amount to absorb + * @return true if damage was absorbed (barrier still alive or just destroyed) + */ + public boolean absorbDamage(float amount) { + if (worldObj.isRemote) return false; + + triggerHitFlash(); + + if (!barrierData.useHealth) { + return true; // Duration-only: absorb but no health loss + } + + currentHealth -= amount; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + return true; + } + + /** + * Teleport an entity to a position. Uses network handler for players + * to ensure reliable client synchronization. + */ + protected void teleportEntity(EntityLivingBase ent, double x, double y, double z) { + if (ent instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) ent; + player.playerNetServerHandler.setPlayerLocation(x, y, z, player.rotationYaw, player.rotationPitch); + } else { + ent.setPosition(x, y, z); + } + } + // ==================== GETTERS ==================== public EnergyBarrierData getBarrierData() { diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index dbe8d4db6..2d2a0ce34 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -45,6 +45,27 @@ public class EntityEnergyDome extends EntityEnergyBarrier { this.setPosition(x, y, z); } + protected void setSize(float width, float height){ + super.setSize(width, height); + + this.ySize = 0.0F; + this.yOffset = this.height * 0.5F; + } + + + // ==================== POSITION / BOUNDING BOX ==================== + + /** + * Override setPosition to maintain dome-sized bounding box. + * MC's default setPosition() resets BB based on width/height fields. + * Network sync calls setPosition(), which would shrink the BB. + * This ensures melee targeting always works against the full dome sphere. + */ + @Override + public void setPosition(double x, double y, double z) { + super.setPosition(x, y, z); + } + @Override public void onUpdate() { this.prevPosX = this.posX; @@ -70,6 +91,8 @@ public class EntityEnergyDome extends EntityEnergyBarrier { chargeTick++; float progress = getChargeProgress(); this.domeRadius = targetDomeRadius * progress; + // Refresh BB for current charge radius + this.setPosition(posX, posY, posZ); return; // Don't tick duration/death during charging } @@ -77,7 +100,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { if (updateBarrierTick()) return; - // Knockback entities inside the dome + // Knockback velocity push every tick if (!worldObj.isRemote && barrierData.knockbackEnabled) { knockbackEntities(); } @@ -86,17 +109,55 @@ public class EntityEnergyDome extends EntityEnergyBarrier { // ==================== INCOMING CHECK ==================== /** - * Check if a projectile at the given position is entering this dome from outside. - * Only blocks incoming projectiles (dot product check). + * Swept ray-sphere intersection test. + * Tests if the line segment from prevPos to currPos crosses the dome sphere boundary + * from outside. Handles fast projectiles that skip through in a single tick. + * + * @return true if the segment enters the sphere from outside */ + private boolean isIncomingRay( + double currX, double currY, double currZ, + double prevX, double prevY, double prevZ, + int projOwnerEntityId) + { + if (isCharging()) return false; + if (projOwnerEntityId == this.ownerEntityId) return false; + + // Ray: P(t) = prev + t * (curr - prev), t in [0, 1] + double rayDirX = currX - prevX; + double rayDirY = currY - prevY; + double rayDirZ = currZ - prevZ; + + // Vector from dome center to ray origin (prevPos) + double ocX = prevX - this.posX; + double ocY = prevY - this.posY; + double ocZ = prevZ - this.posZ; + + double r = domeRadius; + + // Quadratic: a*t^2 + b*t + c = 0 + double a = rayDirX * rayDirX + rayDirY * rayDirY + rayDirZ * rayDirZ; + double b = 2.0 * (ocX * rayDirX + ocY * rayDirY + ocZ * rayDirZ); + double c = (ocX * ocX + ocY * ocY + ocZ * ocZ) - r * r; + + // c > 0: prevPos is outside sphere; c <= 0: inside (don't block) + if (c <= 0) return false; + + if (a < 1e-10) return false; // No movement + + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0) return false; // Ray misses sphere entirely + + double sqrtDisc = Math.sqrt(discriminant); + double t1 = (-b - sqrtDisc) / (2.0 * a); // Entry point (first intersection) + + // Entry must be within this tick's movement segment [0, 1] + return t1 >= 0.0 && t1 <= 1.0; + } + @Override public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { - // Don't block during charging phase - if (isCharging()) return false; - // Don't block projectiles from the dome's owner - if (projectile.getOwnerEntityId() == this.ownerEntityId) return false; - - // Don't block projectiles from same-faction NPCs + // Faction check: don't block same-faction NPC projectiles Entity owner = getOwnerEntity(); Entity projOwner = projectile.getOwnerEntity(); if (owner instanceof noppes.npcs.entity.EntityNPCInterface && projOwner instanceof noppes.npcs.entity.EntityNPCInterface) { @@ -105,29 +166,29 @@ public class EntityEnergyDome extends EntityEnergyBarrier { } } - double dx = projectile.posX - this.posX; - double dy = projectile.posY - this.posY; - double dz = projectile.posZ - this.posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + double prevX = projectile.posX - projectile.motionX; + double prevY = projectile.posY - projectile.motionY; + double prevZ = projectile.posZ - projectile.motionZ; - // Check if projectile is outside dome radius - if (dist > domeRadius) return false; + return isIncomingRay( + projectile.posX, projectile.posY, projectile.posZ, + prevX, prevY, prevZ, + projectile.getOwnerEntityId()); + } - // Approximate the projectile's position before last tick's movement. - // checkBarrierCollision runs BEFORE updateProjectile, so posX is post-last-movement. - // posX - motionX gives the pre-movement position (works for moveEntity and setPosition). - double prevDx = (projectile.posX - projectile.motionX) - this.posX; - double prevDy = (projectile.posY - projectile.motionY) - this.posY; - double prevDz = (projectile.posZ - projectile.motionZ) - this.posZ; - double prevDist = Math.sqrt(prevDx * prevDx + prevDy * prevDy + prevDz * prevDz); + @Override + public boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId) + { + return isIncomingRay(posX, posY, posZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } - // Only block projectiles that crossed the dome boundary from outside. - // Projectiles spawned inside (prevDist < radius) pass through freely. - if (prevDist < domeRadius) return false; - - // Projectile entered from outside — check it's still moving inward - double dot = dx * projectile.motionX + dy * projectile.motionY + dz * projectile.motionZ; - return dot < 0; + @Override + public float getMaxExtent() { + return domeRadius; } // ==================== CHARGING ==================== @@ -147,19 +208,41 @@ public class EntityEnergyDome extends EntityEnergyBarrier { setCharging(false); } - // ==================== KNOCKBACK ==================== + // ==================== KNOCKBACK (DBO-style motion prediction) ==================== /** - * Push entities away from the dome surface. - * Entities outside are pushed outward, entities inside are pushed inward (containment). + * DBO Ki Shield style knockback — unified algorithm with geometric jail: + *

+ * When jailEnabled = false (default): + * - OUTSIDE entities: predict future position, if it would cross into dome push outward. + * If close and approaching, apply soft outward push. Full motion replacement. + * - INSIDE entities: NOT affected (free movement). Dome only blocks entry. + *

+ * When jailEnabled = true: + * - OUTSIDE entities: pushed outward (same as above, prevents entry). + * - INSIDE entities: pushed inward when near edge (geometric containment). + * Any entity inside stays inside, any entity outside stays outside. + *

+ * For moving domes (followCaster), dome velocity is accounted for by using + * relative velocity (entity motion minus dome motion) for predictions. */ @Override @SuppressWarnings("unchecked") protected void knockbackEntities() { - float margin = 1.0f; + float margin = 2.0f; + float r = domeRadius; + float strength = barrierData.knockbackStrength; + boolean jail = barrierData.jailEnabled; + float jailThresh = barrierData.jailThreshold; + + // Dome velocity for moving domes (followCaster) + double domeVelX = posX - prevPosX; + double domeVelY = posY - prevPosY; + double domeVelZ = posZ - prevPosZ; + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - domeRadius - margin, posY - domeRadius - margin, posZ - domeRadius - margin, - posX + domeRadius + margin, posY + domeRadius + margin, posZ + domeRadius + margin + posX - r - margin, posY - r - margin, posZ - r - margin, + posX + r + margin, posY + r + margin, posZ + r + margin ); List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); @@ -168,31 +251,102 @@ public class EntityEnergyDome extends EntityEnergyBarrier { if (!isKnockbackTarget(ent)) continue; if (isAllyOfOwner(ent)) continue; + // Current position relative to dome center double dx = ent.posX - posX; double dy = (ent.posY + ent.height * 0.5) - posY; double dz = ent.posZ - posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist < 0.01) continue; - // Only affect entities near the dome surface - if (dist < domeRadius + margin && dist > domeRadius - margin) { - double pushStrength = barrierData.knockbackStrength * 0.5; - double pushDir = dist >= domeRadius ? 1.0 : -1.0; // Outside = outward, Inside = inward - ent.addVelocity( - (dx / dist) * pushStrength * pushDir, - 0.05 * pushDir, - (dz / dist) * pushStrength * pushDir - ); - ent.velocityChanged = true; + // Normalized direction from dome center toward entity (outward) + double nx = dx / dist; + double ny = dy / dist; + double nz = dz / dist; + + // Entity velocity relative to dome (accounts for moving domes) + double relVelX = ent.motionX - domeVelX; + double relVelY = ent.motionY - domeVelY; + double relVelZ = ent.motionZ - domeVelZ; + + boolean isInside = dist < r; + + if (isInside && jail) { + // --- INSIDE + JAIL ENABLED: push toward center when near dome edge --- + if (dist > r * jailThresh) { + double overshoot = dist - r * jailThresh; + double force = (overshoot + 0.1) * strength * 0.2; + // Set motion to dome velocity + inward push (keeps entity moving with dome) + ent.motionX = domeVelX - nx * force; + ent.motionY = domeVelY - ny * force; + ent.motionZ = domeVelZ - nz * force; + ent.velocityChanged = true; + } else { + // Predict if entity would escape next tick (relative to dome) + double futDx = dx + relVelX; + double futDy = dy + relVelY; + double futDz = dz + relVelZ; + double futDist = Math.sqrt(futDx * futDx + futDy * futDy + futDz * futDz); + if (futDist >= r) { + // Would escape: cancel outward motion, match dome velocity + double radialVel = relVelX * nx + relVelY * ny + relVelZ * nz; + if (radialVel > 0) { + ent.motionX -= radialVel * nx; + ent.motionY -= radialVel * ny; + ent.motionZ -= radialVel * nz; + ent.velocityChanged = true; + } + } + } + } else if (!isInside) { + // --- OUTSIDE: push outward (prevent entry) --- + + // Predicted future distance from center (relative to dome movement) + double futDx = dx + relVelX; + double futDy = dy + relVelY; + double futDz = dz + relVelZ; + double futDist = Math.sqrt(futDx * futDx + futDy * futDy + futDz * futDz); + + // Radial velocity relative to dome (positive = moving away) + double radialVel = relVelX * nx + relVelY * ny + relVelZ * nz; + + if (futDist < r) { + // Would cross INTO dome: hard push outward proportional to overshoot + double overshoot = r - futDist; + double force = (overshoot * 2.0 + 0.05) * strength * 0.1; + ent.motionX = domeVelX + nx * force; + ent.motionY = domeVelY + ny * force * 0.5; + ent.motionZ = domeVelZ + nz * force; + ent.velocityChanged = true; + } else if (radialVel < 0 && dist < r + margin) { + // Close and approaching: soft push outward proportional to proximity + double proximity = 1.0 - ((dist - r) / margin); + double force = proximity * strength * 0.1; + ent.motionX = domeVelX + nx * force; + ent.motionY = domeVelY + ny * force * 0.5; + ent.motionZ = domeVelZ + nz * force; + ent.velocityChanged = true; + } } + // else: INSIDE + no jail → do nothing (free movement) } } + // ==================== CONTAINMENT CHECK ==================== + + @Override + public boolean isEntityInside(Entity entity) { + if (entity == null) return false; + double dx = entity.posX - posX; + double dy = (entity.posY + entity.height * 0.5) - posY; + double dz = entity.posZ - posZ; + return dx * dx + dy * dy + dz * dz < domeRadius * domeRadius; + } + // ==================== MELEE (spherical check) ==================== /** * Reject melee hits that land on the cubic bounding box but are outside the actual sphere. + * Uses distance from the sphere surface (not center) for accurate spherical rejection. */ @Override public boolean attackEntityFrom(DamageSource source, float amount) { @@ -201,10 +355,10 @@ public class EntityEnergyDome extends EntityEnergyBarrier { double dx = attacker.posX - this.posX; double dy = (attacker.posY + attacker.height * 0.5) - this.posY; double dz = attacker.posZ - this.posZ; - double distSq = dx * dx + dy * dy + dz * dz; - // Allow hit only if attacker is within sphere + melee reach margin - double maxDist = domeRadius + 5.0; - if (distSq > maxDist * maxDist) return false; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + double surfaceDist = Math.abs(dist - domeRadius); + // Allow hit only if attacker is within melee reach of the sphere surface + if (surfaceDist > 5.0) return false; } return super.attackEntityFrom(source, amount); } @@ -212,14 +366,13 @@ public class EntityEnergyDome extends EntityEnergyBarrier { // ==================== BOUNDING BOX ==================== /** - * Expands the ray-trace targeting area so players can melee-hit the dome - * from anywhere near its surface, not just the tiny 1x1 center. - * This is used by EntityRenderer.getMouseOver() to expand the entity BB - * for crosshair targeting without modifying the actual bounding box. + * Small expansion on top of the dome-sized bounding box for comfortable + * melee targeting. The actual BB is already dome-sized (set in onUpdate), + * so this only adds a small reach margin for crosshair ray-testing. */ @Override public float getCollisionBorderSize() { - return domeRadius; + return 1.0f; } @Override diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index 19bc1f136..cd33f6460 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -69,6 +69,30 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { } } + // ==================== POSITION / BOUNDING BOX ==================== + + /** + * Override setPosition to maintain panel-sized bounding box. + * MC's default setPosition() resets BB based on width/height fields. + * Network sync calls setPosition(), which would shrink the BB. + * This ensures melee targeting always works against the full panel surface. + */ + @Override + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + if (panelData != null) { + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float extent = Math.max(halfW, 0.5f); + this.boundingBox.setBounds(x - extent, y - halfH, z - extent, x + extent, y + halfH, z + extent); + } else { + float f = this.width / 2.0F; + this.boundingBox.setBounds(x - f, y, z - f, x + f, y + this.height, z + f); + } + } + @Override public void onUpdate() { this.prevPosX = this.posX; @@ -95,7 +119,7 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { if (updateBarrierTick()) return; - // Knockback (not during launched mode) + // Knockback velocity push every tick (not during launched mode) if (!worldObj.isRemote && barrierData.knockbackEnabled && mode != PanelMode.LAUNCHED) { knockbackEntities(); } @@ -205,16 +229,89 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { // ==================== INCOMING CHECK ==================== /** - * Check if a projectile hits this panel surface. - * Only blocks incoming projectiles (not from the panel's owner). + * Swept ray-plane intersection test for the panel. + * Tests if the line segment from prevPos to currPos crosses the panel plane + * within its width/height bounds. Handles fast projectiles that skip through + * the thin panel in a single tick. + * + * @return true if the segment crosses the panel from either side */ + private boolean isIncomingRay( + double currX, double currY, double currZ, + double prevX, double prevY, double prevZ, + int projOwnerEntityId) + { + if (isCharging()) return false; + if (projOwnerEntityId == this.ownerEntityId) return false; + + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float panelThickness = 0.5f; + + float yawRad = (float) Math.toRadians(panelYaw); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + + // Signed distance from prevPos and currPos to panel plane + double relPrevX = prevX - this.posX; + double relPrevY = prevY - this.posY; + double relPrevZ = prevZ - this.posZ; + double prevDist = relPrevX * normalX + relPrevZ * normalZ; + + double relCurrX = currX - this.posX; + double relCurrY = currY - this.posY; + double relCurrZ = currZ - this.posZ; + double currDist = relCurrX * normalX + relCurrZ * normalZ; + + // Check if segment crosses the plane (sign change) + if (prevDist * currDist > 0) { + // Both on same side — check if within thickness (slow projectile fallback) + if (Math.abs(currDist) <= panelThickness) { + double localRight = relCurrX * cos + relCurrZ * sin; + if (Math.abs(localRight) > halfW) return false; + if (Math.abs(relCurrY) > halfH) return false; + // Check incoming direction + double motX = currX - prevX; + double motZ = currZ - prevZ; + double dot = motX * normalX + motZ * normalZ; + if (currDist > 0 && dot >= 0) return false; + if (currDist < 0 && dot <= 0) return false; + return true; + } + return false; + } + + // Segment crosses plane — compute intersection parameter t + double rayDirX = currX - prevX; + double rayDirZ = currZ - prevZ; + double denom = rayDirX * normalX + rayDirZ * normalZ; + if (Math.abs(denom) < 1e-10) return false; // Parallel to plane + + double t = -prevDist / denom; + if (t < 0.0 || t > 1.0) return false; + + // Compute intersection point + double hitX = prevX + (currX - prevX) * t; + double hitY = prevY + (currY - prevY) * t; + double hitZ = prevZ + (currZ - prevZ) * t; + + // Transform hit point to panel-local space and check bounds + double relHitX = hitX - this.posX; + double relHitY = hitY - this.posY; + double relHitZ = hitZ - this.posZ; + + double localRight = relHitX * cos + relHitZ * sin; + if (Math.abs(localRight) > halfW) return false; + if (Math.abs(relHitY) > halfH) return false; + + return true; + } + @Override public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { - // Don't block during charging phase - if (isCharging()) return false; - if (projectile.getOwnerEntityId() == this.ownerEntityId) return false; - - // Faction check + // Faction check: don't block same-faction NPC projectiles Entity owner = getOwnerEntity(); Entity projOwner = projectile.getOwnerEntity(); if (owner instanceof EntityNPCInterface && projOwner instanceof EntityNPCInterface) { @@ -223,38 +320,29 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { } } - // Check if projectile is within panel bounds - float halfW = panelData.panelWidth * 0.5f; - float halfH = panelData.panelHeight * 0.5f; - float panelThickness = 0.5f; // Collision thickness + double prevX = projectile.posX - projectile.motionX; + double prevY = projectile.posY - projectile.motionY; + double prevZ = projectile.posZ - projectile.motionZ; - // Transform projectile position to panel-local space - float yawRad = (float) Math.toRadians(panelYaw); - double relX = projectile.posX - this.posX; - double relY = projectile.posY - this.posY; - double relZ = projectile.posZ - this.posZ; + return isIncomingRay( + projectile.posX, projectile.posY, projectile.posZ, + prevX, prevY, prevZ, + projectile.getOwnerEntityId()); + } - // Rotate into panel space (panel faces along -sin(yaw), cos(yaw)) - double cos = Math.cos(yawRad); - double sin = Math.sin(yawRad); - double localForward = relX * (-sin) + relZ * cos; // Distance along panel normal - double localRight = relX * cos + relZ * sin; // Distance along panel width + @Override + public boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId) + { + return isIncomingRay(posX, posY, posZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } - // Check bounds - if (Math.abs(localForward) > panelThickness) return false; - if (Math.abs(localRight) > halfW) return false; - if (Math.abs(relY) > halfH) return false; - - // Check incoming direction via dot product with panel normal - double normalX = -Math.sin(yawRad); - double normalZ = Math.cos(yawRad); - double dot = projectile.motionX * normalX + projectile.motionZ * normalZ; - - // Determine which side of the panel the projectile is on - if (localForward > 0 && dot >= 0) return false; // Moving away from front side - if (localForward < 0 && dot <= 0) return false; // Moving away from back side - - return true; + @Override + public float getMaxExtent() { + return Math.max(panelData.panelWidth, panelData.panelHeight) * 0.5f + 1.0f; } // ==================== CHARGING ==================== @@ -277,21 +365,26 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { setCharging(false); } - // ==================== KNOCKBACK ==================== + // ==================== KNOCKBACK (DBO-style motion prediction) ==================== /** - * Push entities away from the panel surface. + * DBO-inspired planar knockback: + * - Predict future position from current motion + * - Detect crossing or proximity to panel surface + * - Apply counter-force via full motion replacement + * - No separate phases — single unified algorithm */ @Override @SuppressWarnings("unchecked") protected void knockbackEntities() { float halfW = panelData.panelWidth * 0.5f; float halfH = panelData.panelHeight * 0.5f; - float margin = 1.0f; + float searchExtension = 5.0f; + float strength = barrierData.knockbackStrength; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - halfW - margin, posY - halfH - margin, posZ - halfW - margin, - posX + halfW + margin, posY + halfH + margin, posZ + halfW + margin + posX - halfW - searchExtension, posY - halfH - searchExtension, posZ - halfW - searchExtension, + posX + halfW + searchExtension, posY + halfH + searchExtension, posZ + halfW + searchExtension ); List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); @@ -304,44 +397,60 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { if (!isKnockbackTarget(ent)) continue; if (isAllyOfOwner(ent)) continue; - // Transform entity position to panel-local space + // Current position relative to panel center double dx = ent.posX - posX; double dy = (ent.posY + ent.height * 0.5) - posY; double dz = ent.posZ - posZ; - // Check proximity to panel surface + // Panel-local coordinates float localForward = (float) (dx * normalX + dz * normalZ); float localRight = (float) (dx * (-normalZ) + dz * normalX); - if (Math.abs(localForward) < margin && Math.abs(localRight) < halfW + margin && Math.abs(dy) < halfH + margin) { - // Push entity away from the panel face - float pushDir = localForward >= 0 ? 1.0f : -1.0f; - double pushStrength = barrierData.knockbackStrength * 0.5; - ent.addVelocity( - normalX * pushDir * pushStrength, - 0.1, - normalZ * pushDir * pushStrength - ); + // Skip if outside panel bounds (with margin) + if (Math.abs(localRight) > halfW + searchExtension) continue; + if (Math.abs(dy) > halfH + searchExtension) continue; + if (Math.abs(localForward) > searchExtension) continue; + + // Skip if outside panel width/height bounds (no wall to push against) + if (Math.abs(localRight) > halfW + 1.0f) continue; + if (Math.abs(dy) > halfH + 1.0f) continue; + + // Predicted future position + double futDx = (ent.posX + ent.motionX) - posX; + double futDz = (ent.posZ + ent.motionZ) - posZ; + float futLocalForward = (float) (futDx * normalX + futDz * normalZ); + + // Normal velocity component (positive = moving in normal direction) + double normalVel = ent.motionX * normalX + ent.motionZ * normalZ; + + // Determine which side the entity is on + float side = localForward >= 0 ? 1.0f : -1.0f; + boolean movingTowardPanel = (localForward >= 0 && normalVel < 0) || (localForward < 0 && normalVel > 0); + + // Check if predicted position would cross the plane (sign change) + boolean wouldCross = (localForward > 0 && futLocalForward <= 0) || (localForward < 0 && futLocalForward >= 0); + + if (wouldCross && Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH) { + // Hard block: full motion replacement to prevent crossing + // Push back along normal, proportional to how far past the surface they'd go + double overshoot = Math.abs(futLocalForward); + double pushForce = (overshoot + 0.05) * strength * 0.1; + ent.motionX = normalX * side * pushForce; + ent.motionZ = normalZ * side * pushForce; + ent.velocityChanged = true; + } else if (Math.abs(localForward) < 1.0 && movingTowardPanel + && Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH) { + // Soft push: entity is close and approaching, apply proportional force + double proximity = 1.0 - Math.abs(localForward); + double pushForce = proximity * strength * 0.1; + ent.motionX = normalX * side * pushForce; + ent.motionZ = normalZ * side * pushForce; ent.velocityChanged = true; } } } - // ==================== BOUNDING BOX ==================== - - @Override - public AxisAlignedBB getBoundingBox() { - if (barrierData.meleeEnabled) { - float halfW = panelData.panelWidth * 0.5f; - float halfH = panelData.panelHeight * 0.5f; - float extent = Math.max(halfW, 0.5f); - return AxisAlignedBB.getBoundingBox( - posX - extent, posY - halfH, posZ - extent, - posX + extent, posY + halfH, posZ + extent - ); - } - return null; - } + // ==================== RENDER ==================== @Override @SideOnly(Side.CLIENT) diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index 8e8b62780..5b741cc0b 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -318,17 +318,18 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { * @return true if projectile was absorbed (caller should stop processing) */ protected boolean checkBarrierCollision() { - // Search range must cover the largest possible barrier (dome radius up to MAX_ENTITY_RADIUS) - double searchRange = MAX_ENTITY_RADIUS + 5; - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - searchRange, posY - searchRange, posZ - searchRange, - posX + searchRange, posY + searchRange, posZ + searchRange - ); - - @SuppressWarnings("unchecked") - List barriers = worldObj.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); + List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead) continue; + + // Quick distance pre-filter + double dx = barrier.posX - this.posX; + double dy = barrier.posY - this.posY; + double dz = barrier.posZ - this.posZ; + double distSq = dx * dx + dy * dy + dz * dz; + double maxRange = barrier.getMaxExtent() + 5.0; + if (distSq > maxRange * maxRange) continue; + if (barrier.isIncomingProjectile(this)) { float damage = getModifiedDamage(); if (barrier.onProjectileHit(this, damage)) { diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index ca2be8968..5cdd71bff 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -430,6 +430,7 @@ public class CustomNpcs { } kamkeel.npcs.entity.EntityEnergyProjectile.clearAllProjectiles(); + kamkeel.npcs.entity.EntityEnergyBarrier.clearAllBarriers(); if (FMLCommonHandler.instance().getSide().isClient()) clientJaninoCompiler = null; diff --git a/src/main/java/noppes/npcs/ServerEventsHandler.java b/src/main/java/noppes/npcs/ServerEventsHandler.java index b6671b72a..fb2ea3d13 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -30,6 +30,7 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.village.MerchantRecipeList; import net.minecraftforge.event.entity.EntityJoinWorldEvent; +import kamkeel.npcs.entity.EntityEnergyBarrier; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; @@ -151,6 +152,52 @@ public class ServerEventsHandler { } } + @SubscribeEvent + public void barrierDamageProtection(LivingAttackEvent event) { + if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote) + return; + + EntityEnergyBarrier barrier = EntityEnergyBarrier.getProtectingBarrier(event.entityLiving); + if (barrier != null && barrier.isDamageFromOutside(event.source)) { + // Redirect the damage to the barrier instead of preventing it + barrier.absorbDamage(event.ammount); + event.setCanceled(true); + } + } + + @SubscribeEvent + public void domeItemBlacklist(PlayerInteractEvent event) { + if (event.action == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) return; + EntityPlayer player = event.entityPlayer; + if (player == null || player.worldObj == null || player.worldObj.isRemote) return; + + ItemStack held = player.getHeldItem(); + if (held == null) return; + + String itemId = net.minecraft.item.Item.itemRegistry.getNameForObject(held.getItem()); + if (itemId == null) return; + + String[] blacklist = noppes.npcs.config.ConfigEnergy.DomeItemBlacklist; + if (blacklist == null) return; + + boolean blacklisted = false; + for (String banned : blacklist) { + if (banned.equals(itemId)) { + blacklisted = true; + break; + } + } + if (!blacklisted) return; + + List barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier instanceof kamkeel.npcs.entity.EntityEnergyDome && barrier.isEntityInside(player)) { + event.setCanceled(true); + return; + } + } + } + @SubscribeEvent public void partyDamagedEvent(LivingAttackEvent event) { if (!(event.source != null && event.source.getEntity() instanceof EntityPlayer) || !(event.entityLiving instanceof EntityPlayer) || FMLCommonHandler.instance().getEffectiveSide().isClient()) diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 1c16de390..b97df1159 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -5,6 +5,7 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; +import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.client.renderer.lightning.LightningBolt; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; @@ -203,6 +204,40 @@ public class ClientTickHandler { } } + /** + * Enforce ability lock motion constraints right before entity update. + * The Phase.END zeroing in onClientTick can be overwritten by other mods' + * ClientTickEvent Phase.START handlers (e.g. flight mods re-applying gravity). + * PlayerTickEvent fires after all ClientTickEvent handlers but before + * player.onUpdate(), making this the definitive point to enforce motion locks. + */ + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerTick(TickEvent.PlayerTickEvent event) { + if (event.phase != Phase.START || event.side != Side.CLIENT) + return; + + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer == null || mc.currentScreen != null) + return; + + if (!ClientAbilityState.shouldSuppressMovementInput()) + return; + + if (!ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionX = 0; + mc.thePlayer.motionZ = 0; + } + + if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) + && !ClientAbilityState.hasAbilityMovement) { + if (ClientAbilityState.wasFlyingAtLock) { + mc.thePlayer.motionY = 0; + } else { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + } + } + } + @SubscribeEvent public void onMouse(InputEvent.MouseInputEvent event) { if (Mouse.getEventButton() == -1 && Mouse.getEventDWheel() == 0) diff --git a/src/main/java/noppes/npcs/config/ConfigEnergy.java b/src/main/java/noppes/npcs/config/ConfigEnergy.java new file mode 100644 index 000000000..f3b36a948 --- /dev/null +++ b/src/main/java/noppes/npcs/config/ConfigEnergy.java @@ -0,0 +1,37 @@ +package noppes.npcs.config; + +import cpw.mods.fml.common.FMLLog; +import net.minecraftforge.common.config.Configuration; +import org.apache.logging.log4j.Level; + +import java.io.File; + +public class ConfigEnergy { + public static Configuration config; + + public final static String DOMES = "Domes"; + + public static String[] DomeItemBlacklist; + + public static void init(File configFile) { + config = new Configuration(configFile); + + try { + config.load(); + + DomeItemBlacklist = config.getStringList( + "Item Blacklist", DOMES, + new String[]{"minecraft:ender_pearl"}, + "Items that cannot be used while inside an Energy Dome.\n" + + "Format: modid:itemname (e.g., minecraft:ender_pearl)" + ); + + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "CustomNPC+ has had a problem loading its energy configuration"); + } finally { + if (config.hasChanged()) { + config.save(); + } + } + } +} diff --git a/src/main/java/noppes/npcs/config/LoadConfiguration.java b/src/main/java/noppes/npcs/config/LoadConfiguration.java index dfac43d90..0fc46e3e3 100644 --- a/src/main/java/noppes/npcs/config/LoadConfiguration.java +++ b/src/main/java/noppes/npcs/config/LoadConfiguration.java @@ -10,6 +10,7 @@ public class LoadConfiguration { public static File clientConfigFile; public static File experimentalConfigFile; public static File marketConfigFile; + public static File energyConfigFile; public static void init(String configpath) { mainConfigFile = new File(configpath + "main.cfg"); @@ -19,6 +20,7 @@ public class LoadConfiguration { debugConfigFile = new File(configpath + "debug.cfg"); experimentalConfigFile = new File(configpath + "experimental.cfg"); marketConfigFile = new File(configpath + "market.cfg"); + energyConfigFile = new File(configpath + "energy.cfg"); ConfigMain.init(mainConfigFile); ConfigItem.init(itemConfigFile); @@ -27,5 +29,6 @@ public class LoadConfiguration { ConfigDebug.init(debugConfigFile); ConfigExperimental.init(experimentalConfigFile); ConfigMarket.init(marketConfigFile); + ConfigEnergy.init(energyConfigFile); } } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index c2d575224..55e94b72d 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2043,6 +2043,13 @@ ability.meleeDamageMultiplier=Melee Multiplier ability.followCaster=Follow Caster ability.hover.followCaster=Dome stays centered on the caster as they move +ability.section.jail=Jail & Protection +ability.jailEnabled=Jail Mode +ability.hover.jailEnabled=Entities inside stay inside, entities outside stay outside +ability.jailThreshold=Jail Threshold +ability.damageProtection=Damage Protection +ability.hover.damageProtection=Outside attacks on entities inside are redirected to the dome + ability.variant.small=Small ability.variant.large=Large ability.variant.static=Static From a2e0bb50b9fd0d00080a81de894b6122b0ac087f Mon Sep 17 00:00:00 2001 From: somehussar <148253652+somehussar@users.noreply.github.com> Date: Sat, 21 Feb 2026 00:27:31 +0100 Subject: [PATCH 20/51] Apparently the import got removed. --- src/main/java/noppes/npcs/entity/EntityNPCInterface.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 6cfb59553..4834504b3 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -11,6 +11,7 @@ import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; import kamkeel.npcs.network.packets.data.ChatBubblePacket; import kamkeel.npcs.network.packets.data.QuestCompletionPacket; +import kamkeel.npcs.network.packets.data.RequestProperSpawnData; import kamkeel.npcs.network.packets.data.SoundManagementPacket; import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket; import kamkeel.npcs.network.packets.data.npc.WeaponNpcPacket; From 89e87b7656d4313bf7cd1065d2b3c971dedf5e89 Mon Sep 17 00:00:00 2001 From: Vidal Date: Fri, 20 Feb 2026 21:36:08 -0300 Subject: [PATCH 21/51] Condition overhaul completed --- .../controllers/data/ability/Ability.java | 2 + .../ability/conditions/AbilityCondition.java | 35 ++- .../ability/conditions/ConditionFilter.java | 39 +++ .../conditions/ConditionHPThreshold.java | 31 ++- .../ability/conditions/ConditionHitCount.java | 10 +- .../gui/advanced/SubGuiAbilityConfig.java | 79 +++--- .../advanced/SubGuiChainedAbilityConfig.java | 139 +++++------ .../gui/advanced/SubGuiConditionEdit.java | 229 ++++++++---------- .../assets/customnpcs/lang/en_US.lang | 18 +- 9 files changed, 290 insertions(+), 292 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 25cb77747..5d793f5ec 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -1233,6 +1233,7 @@ public abstract class Ability implements IAbility, IAbilityAction { public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsNpc()) continue; if (!c.check(caster, target)) return false; } return true; @@ -1243,6 +1244,7 @@ public abstract class Ability implements IAbility, IAbilityAction { */ public boolean checkConditionsForPlayer(EntityLivingBase caster) { for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsPlayer()) continue; if (c.requiresTarget()) continue; if (!c.check(caster, null)) return false; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java index 15d345a4c..95d38bf9b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -9,6 +9,7 @@ import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.LogWriter; import noppes.npcs.client.gui.builder.FieldDef; +import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; @@ -16,6 +17,7 @@ public abstract class AbilityCondition { protected String typeId = ""; protected String name = ""; protected UserType userType = UserType.BOTH; + protected ConditionFilter conditionFilter = ConditionFilter.CASTER; /** * Check if this condition is met. @@ -34,10 +36,6 @@ public abstract class AbilityCondition { return userType; } - public void setUserType(UserType userType) { - this.userType = userType; - } - public String getTypeId() { return typeId; } @@ -46,14 +44,32 @@ public abstract class AbilityCondition { return name; } + public ConditionFilter getFilter() { + return conditionFilter; + } + + public void setFilter(ConditionFilter filter) { + this.conditionFilter = filter; + } + @SideOnly(Side.CLIENT) - public abstract List getAbilityDefinitions(List defs); + public abstract void getConditionDefinitions(List defs); + + @SideOnly(Side.CLIENT) + public final List getAllDefinitions() { + List defs = new ArrayList<>(); + + defs.add(FieldDef.enumField("condition.filter", ConditionFilter.class, this::getFilter, this::setFilter)); + getConditionDefinitions(defs); + return defs; + } public final NBTTagCompound writeNBT() { NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("userType", getUserType().ordinal()); - nbt.setString("type", getTypeId()); + nbt.setString("typeId", getTypeId()); nbt.setString("name", getName()); + nbt.setInteger("userType", getUserType().ordinal()); + nbt.setInteger("filter", getUserType().ordinal()); writeTypeNBT(nbt); return nbt; } @@ -63,14 +79,15 @@ public abstract class AbilityCondition { public abstract void readTypeNBT(NBTTagCompound nbt); public final void readNBT(NBTTagCompound nbt) { - typeId = nbt.getString("type"); + typeId = nbt.getString("typeId"); name = nbt.getString("name"); userType = UserType.fromOrdinal(nbt.getInteger("userType")); + conditionFilter = ConditionFilter.fromOrdinal(nbt.getInteger("filter")); readTypeNBT(nbt); } public static AbilityCondition fromNBT(NBTTagCompound nbt) { - String typeId = nbt.getString("type"); + String typeId = nbt.getString("typeId"); Supplier factory = AbilityController.Instance.getConditionType(typeId); if (factory == null) { LogWriter.info("AbilityController: Unknown condition type: " + typeId); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java new file mode 100644 index 000000000..6c8e0c24e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java @@ -0,0 +1,39 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; + +public enum ConditionFilter { + CASTER, + TARGET, + BOTH; + + public boolean checksCaster() { + return this == CASTER || this == BOTH; + } + + public boolean checksTarget() { + return this == TARGET || this == BOTH; + } + + public static ConditionFilter fromOrdinal(int ordinal) { + ConditionFilter[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return BOTH; + } + + @Override + public String toString() { + switch (this) { + case BOTH: + return "condition.filter.both"; + case CASTER: + return "condition.filter.caster"; + case TARGET: + return "condition.filter.target"; + default: + return name(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java index 3d647475f..803fc978c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -1,11 +1,9 @@ package kamkeel.npcs.controllers.data.ability.conditions; -import kamkeel.npcs.controllers.data.ability.UserType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; -import java.util.Collections; import java.util.List; public class ConditionHPThreshold extends AbilityCondition{ @@ -16,13 +14,13 @@ public class ConditionHPThreshold extends AbilityCondition{ ABOVE { @Override public boolean test(float value, float threshold) { - return value > threshold; + return value >= threshold; } }, BELOW { @Override public boolean test(float value, float threshold) { - return value < threshold; + return value <= threshold; } }; @@ -35,12 +33,23 @@ public class ConditionHPThreshold extends AbilityCondition{ } return ABOVE; } + + @Override + public String toString() { + switch (this) { + case ABOVE: + return "condition.hp_above"; + case BELOW: + return "condition.hp_below"; + default: + return name(); + } + } } public ConditionHPThreshold() { this.typeId = "condition.cnpc.hp_threshold"; - this.name = "Health Threshold"; - this.userType = UserType.NPC_ONLY; + this.name = "condition.hp_threshold"; } @Override @@ -56,10 +65,10 @@ public class ConditionHPThreshold extends AbilityCondition{ boolean casterCheck = thresholdType.test(casterHp, threshold); boolean targetCheck = thresholdType.test(targetHp, threshold); - switch (getUserType()) { + switch (getFilter()) { case BOTH: return casterCheck && targetCheck; - case PLAYER_ONLY: + case CASTER: return casterCheck; default: return targetCheck; @@ -83,8 +92,10 @@ public class ConditionHPThreshold extends AbilityCondition{ } @Override - public List getAbilityDefinitions(List defs) { - return Collections.emptyList(); + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.floatField("condition.threshold", this::getThreshold, this::setThreshold).min(0)); + defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, + this::getThresholdType, this::setThresholdType)); } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java index 385e7eb99..22465b593 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -6,16 +6,15 @@ import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.entity.EntityNPCInterface; -import java.util.Collections; import java.util.List; -public class ConditionHitCount extends AbilityCondition{ +public class ConditionHitCount extends AbilityCondition { private int requiredHits = 3; private int withinTicks = 60; public ConditionHitCount() { this.typeId = "condition.cnpc.hit_count"; - this.name = "Hit Count"; + this.name = "condition.hit_count"; this.userType = UserType.NPC_ONLY; } @@ -49,8 +48,9 @@ public class ConditionHitCount extends AbilityCondition{ } @Override - public List getAbilityDefinitions(List defs) { - return Collections.emptyList(); + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.intField("condition.required_hits", this::getRequiredHits, this::setRequiredHits).min(1)); + defs.add(FieldDef.intField("condition.within_ticks", this::getWithinTicks, this::setWithinTicks).min(0)); } @Override diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index edbf676fb..b611e4e6b 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -1,7 +1,7 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; import net.minecraft.client.gui.GuiButton; import net.minecraft.nbt.NBTTagCompound; @@ -49,7 +49,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi private List fieldDefs; private List customTabNames; - private List conditions; + private List conditions; private int editingConditionIndex = -1; private AbilityFieldBuilder builder; @@ -60,7 +60,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi public SubGuiAbilityConfig(Ability ability, IAbilityConfigCallback callback) { this.ability = ability; this.callback = callback; -// this.conditions = new ArrayList<>(ability.getConditions()); + this.conditions = new ArrayList<>(ability.getConditions()); this.fieldDefs = ability.getAllDefinitions(); discoverCustomTabs(); @@ -230,51 +230,32 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi // ═══════════════════════════════════════════════════════════════════════════ private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) { -// y += 3; -// sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); -// y += 15; -// -// for (int i = 0; i < conditions.size() && i < 3; i++) { -// Condition cond = conditions.get(i); -// String condName = getConditionDisplayName(cond); -// sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); -// sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); -// sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); -// y += 22; -// } -// -// if (conditions.size() < 3) { -// sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); -// y += ROW_H; -// } -// + y += 3; + sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); + y += 15; + + for (int i = 0; i < conditions.size() && i < 3; i++) { + AbilityCondition cond = conditions.get(i); + String condName = getConditionDisplayName(cond); + sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); + sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); + y += 22; + } + + if (conditions.size() < 3) { + sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); + y += ROW_H; + } + return y; } -// private String getConditionDisplayName(Condition cond) { -// if (cond == null) return "None"; -// String typeId = cond.getTypeId(); -// switch (typeId) { -// case "hp_above": -// return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; -// case "hp_below": -// return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; -// case "target_hp_above": -// return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; -// case "target_hp_below": -// return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; -// case "hit_count": -// Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; -// return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; -// default: -// return typeId; -// } -// } - -// private float getConditionThreshold(Condition cond) { -// NBTTagCompound nbt = cond.writeNBT(); -// return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; -// } + private String getConditionDisplayName(AbilityCondition cond) { + if (cond == null) return "None"; + String name = cond.getName(); + return StatCollector.translateToLocal(name); + } // ═══════════════════════════════════════════════════════════════════════════ // BUTTON EVENTS @@ -382,7 +363,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi if (subgui instanceof SubGuiConditionEdit) { SubGuiConditionEdit condEdit = (SubGuiConditionEdit) subgui; - Condition result = condEdit.getResult(); + AbilityCondition result = condEdit.getResult(); if (result != null && editingConditionIndex >= 0) { if (editingConditionIndex < conditions.size()) { conditions.set(editingConditionIndex, result); @@ -408,8 +389,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } protected void applyToAbility() { -// ability.getConditions().clear(); -// for (Condition c : conditions) ability.addCondition(c); + ability.getConditions().clear(); + for (AbilityCondition c : conditions) ability.addCondition(c); } public void loadAbility(Ability loadedAbility) { @@ -418,7 +399,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi nbt.setString("typeId", ability.getTypeId()); ability.readNBT(nbt); -// this.conditions = new ArrayList<>(ability.getConditions()); + this.conditions = new ArrayList<>(ability.getConditions()); this.fieldDefs = ability.getAllDefinitions(); discoverCustomTabs(); initGui(); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index 35b9e9f7c..9783bb9a7 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -6,7 +6,6 @@ import kamkeel.npcs.controllers.data.ability.AbilityAction; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.ChainedAbility; import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry; -import kamkeel.npcs.controllers.data.ability.Condition; import kamkeel.npcs.controllers.data.ability.AbilityIconData; import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; import kamkeel.npcs.controllers.data.ability.UserType; @@ -14,7 +13,6 @@ import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import net.minecraft.client.gui.GuiButton; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.builder.GuiFieldBuilder; @@ -23,16 +21,12 @@ import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.GuiScrollWindow; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityAction; -import kamkeel.npcs.controllers.data.ability.ChainedAbility; import noppes.npcs.client.gui.util.*; import java.util.ArrayList; import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; -import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; @@ -94,7 +88,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText private List fieldDefs; private List entries; -// private List conditions; + private List conditions; // Dynamic tabs injected by field providers (e.g., "Icon") private List extraTabs = new ArrayList<>(); @@ -133,7 +127,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText this.readOnlyEntries = readOnlyEntries; this.npcSlots = npcSlots; this.entries = new ArrayList<>(chain.getEntries()); -// this.conditions = new ArrayList<>(chain.getConditions()); + this.conditions = new ArrayList<>(chain.getConditions()); buildFieldDefs(); @@ -429,50 +423,31 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) { -// y += 3; -// sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); -// y += 15; -// -// for (int i = 0; i < conditions.size() && i < 3; i++) { -// Condition cond = conditions.get(i); -// String condName = getConditionDisplayName(cond); -// sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); -// sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); -// sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); -// y += 22; -// } -// -// if (conditions.size() < 3) { -// sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); -// y += ROW_H; -// } + y += 3; + sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); + y += 15; + + for (int i = 0; i < conditions.size() && i < 3; i++) { + AbilityCondition cond = conditions.get(i); + String condName = getConditionDisplayName(cond); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); + y += 22; + } + + if (conditions.size() < 3) { + sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); + y += ROW_H; + } return y; } - private String getConditionDisplayName(Condition cond) { + private String getConditionDisplayName(AbilityCondition cond) { if (cond == null) return "None"; - String typeId = cond.getTypeId(); - switch (typeId) { - case "hp_above": - return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hp_below": - return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_above": - return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_below": - return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hit_count": - Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; - return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; - default: - return typeId; - } - } - - private float getConditionThreshold(Condition cond) { - NBTTagCompound nbt = cond.writeNBT(); - return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; + String name = cond.getName(); + return StatCollector.translateToLocal(name); } // ═══════════════════════════════════════════════════════════════════════════ @@ -623,29 +598,29 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private boolean handleConditionButton(int id) { -// if (id >= COND_BASE && id < COND_END) { -// int condIndex = (id - COND_BASE) / COND_STRIDE; -// int action = (id - COND_BASE) % COND_STRIDE; -// if (action == 0 || action == 1) { -// if (condIndex < conditions.size()) { -// editingConditionIndex = condIndex; -// setSubGui(new SubGuiConditionEdit(conditions.get(condIndex))); -// } -// } else if (action == 2) { -// if (condIndex < conditions.size()) { -// conditions.remove(condIndex); -// initGui(); -// } -// } -// return true; -// } -// if (id == BTN_ADD_COND) { -// if (conditions.size() < 3) { -// editingConditionIndex = conditions.size(); -// setSubGui(new SubGuiConditionEdit(null)); -// } -// return true; -// } + if (id >= COND_BASE && id < COND_END) { + int condIndex = (id - COND_BASE) / COND_STRIDE; + int action = (id - COND_BASE) % COND_STRIDE; + if (action == 0 || action == 1) { + if (condIndex < conditions.size()) { + editingConditionIndex = condIndex; + setSubGui(new SubGuiConditionEdit(conditions.get(condIndex))); + } + } else if (action == 2) { + if (condIndex < conditions.size()) { + conditions.remove(condIndex); + initGui(); + } + } + return true; + } + if (id == BTN_ADD_COND) { + if (conditions.size() < 3) { + editingConditionIndex = conditions.size(); + setSubGui(new SubGuiConditionEdit(null)); + } + return true; + } return false; } @@ -850,14 +825,14 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private void handleConditionEditClosed(SubGuiConditionEdit gui) { -// Condition result = gui.getResult(); -// if (result != null && editingConditionIndex >= 0) { -// if (editingConditionIndex < conditions.size()) { -// conditions.set(editingConditionIndex, result); -// } else { -// conditions.add(result); -// } -// } + AbilityCondition result = gui.getResult(); + if (result != null && editingConditionIndex >= 0) { + if (editingConditionIndex < conditions.size()) { + conditions.set(editingConditionIndex, result); + } else { + conditions.add(result); + } + } editingConditionIndex = -1; } @@ -895,10 +870,10 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } // Conditions -// chain.getConditions().clear(); -// for (Condition c : conditions) { -// chain.getConditions().add(c); -// } + chain.getConditions().clear(); + for (AbilityCondition c : conditions) { + chain.getConditions().add(c); + } // Remove consumed NPC slots (descending order to preserve indices) if (npcSlots != null && !consumedSlotIndices.isEmpty()) { diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java index d941f19ec..d90f0b6d6 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java @@ -1,190 +1,159 @@ package noppes.npcs.client.gui.advanced; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import net.minecraft.client.gui.GuiButton; -import noppes.npcs.client.gui.util.GuiNpcButton; -import noppes.npcs.client.gui.util.GuiNpcLabel; -import noppes.npcs.client.gui.util.GuiNpcTextField; -import noppes.npcs.client.gui.util.ITextfieldListener; -import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.util.*; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; /** - * SubGui for editing a single ability condition. - * Allows selecting condition type and configuring its parameters. + * SubGui for editing a single AbilityCondition. + * + * Type selection stays manual (we need to swap the condition object). + * Field rendering is fully delegated to AbilityCondition#getAbilityDefinitions(), + * mirroring the pattern used in SubGuiAbilityConfig. */ -public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener { +public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { - // Condition types - private static final String[] CONDITION_TYPES = { - "condition.hp_above", - "condition.hp_below", - "condition.target_hp_above", - "condition.target_hp_below", - "condition.hit_count" - }; + private static final int DECLARATIVE_ID_START = 1000; + private static final int CLEAR_ID_START = 2000; + private static final int LABEL_ID_START = 3000; - private static final String[] CONDITION_TYPE_IDS = { - "hp_above", - "hp_below", - "target_hp_above", - "target_hp_below", - "hit_count" - }; + private static final int BTN_TYPE = 1; + private static final int BTN_CANCEL = 10; + private static final int BTN_DONE = 11; - // Current condition being edited - private Condition condition; - private Condition result; + private AbilityCondition condition; + private AbilityCondition result; - // State + private final String[] conditionTypeIds; + private final String[] conditionTypeNames; private int selectedTypeIndex = 0; - private float threshold = 0.5f; // For HP conditions (0.0-1.0) - private int requiredHits = 3; // For hit_count - private int withinTicks = 60; // For hit_count - public SubGuiConditionEdit(Condition existing) { - this.condition = existing; + private AbilityFieldBuilder builder; + + public SubGuiConditionEdit(AbilityCondition existing) { this.result = null; + conditionTypeIds = AbilityController.Instance.getConditionTypes(); + conditionTypeNames = new String[conditionTypeIds.length]; + for (int i = 0; i < conditionTypeIds.length; i++) { + Supplier factory = AbilityController.Instance.getConditionType(conditionTypeIds[i]); + conditionTypeNames[i] = factory != null ? factory.get().getName() : conditionTypeIds[i]; + } + if (existing != null) { - String typeId = existing.getTypeId(); - for (int i = 0; i < CONDITION_TYPE_IDS.length; i++) { - if (CONDITION_TYPE_IDS[i].equals(typeId)) { + for (int i = 0; i < conditionTypeIds.length; i++) { + if (conditionTypeIds[i].equals(existing.getTypeId())) { selectedTypeIndex = i; break; } } - loadFromCondition(existing); + this.condition = existing; + } else { + this.condition = spawnCondition(selectedTypeIndex); } setBackground("menubg.png"); - xSize = 220; - ySize = 140; + xSize = 240; + ySize = 180; } - private void loadFromCondition(Condition cond) { - String typeId = cond.getTypeId(); - if (typeId.equals("hit_count")) { - Condition.ConditionHitCount hitCount = (Condition.ConditionHitCount) cond; - requiredHits = hitCount.getRequiredHits(); - withinTicks = hitCount.getWithinTicks(); - } else { - // HP-based conditions - net.minecraft.nbt.NBTTagCompound nbt = cond.writeNBT(); - threshold = nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; - } + private AbilityCondition spawnCondition(int typeIndex) { + if (typeIndex < 0 || typeIndex >= conditionTypeIds.length) return null; + Supplier factory = AbilityController.Instance.getConditionType(conditionTypeIds[typeIndex]); + return factory != null ? factory.get() : null; } @Override public void initGui() { + GuiNpcTextField.unfocus(); super.initGui(); - int y = guiTop + 8; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 90; + int swX = guiLeft + 4; + int swY = guiTop + 5; + int swW = xSize - 8; + int swH = ySize - 35; - // Title - addLabel(new GuiNpcLabel(0, "condition.edit", labelX, y)); - y += 18; - - // Condition Type selector - addLabel(new GuiNpcLabel(1, "gui.type", labelX, y + 5)); - GuiNpcButton typeBtn = new GuiNpcButton(1, fieldX, y, 115, 20, CONDITION_TYPES, selectedTypeIndex); - typeBtn.setHoverText("condition.hover.type"); + int labelY = guiTop + 8; + addLabel(new GuiNpcLabel(0, "gui.type", guiLeft + 8, labelY + 5)); + GuiNpcButton typeBtn = new GuiNpcButton(BTN_TYPE, guiLeft + 80, labelY, 155, 20, conditionTypeNames, selectedTypeIndex); addButton(typeBtn); - y += 26; - // Type-specific fields - String typeId = CONDITION_TYPE_IDS[selectedTypeIndex]; - if (typeId.equals("hit_count")) { - // Hit count fields - addLabel(new GuiNpcLabel(2, "condition.hits", labelX, y + 5)); - GuiNpcTextField hitsField = new GuiNpcTextField(2, this, fontRendererObj, fieldX, y, 40, 20, "" + requiredHits); - hitsField.setIntegersOnly(); - hitsField.setMinMaxDefault(1, 100, 3); - hitsField.setHoverText("condition.hover.hits"); - addTextField(hitsField); - y += 24; + swY += 26; + swH -= 26; - addLabel(new GuiNpcLabel(3, "condition.within", labelX, y + 5)); - GuiNpcTextField ticksField = new GuiNpcTextField(3, this, fontRendererObj, fieldX, y, 40, 20, "" + withinTicks); - ticksField.setIntegersOnly(); - ticksField.setMinMaxDefault(1, 1200, 60); - ticksField.setHoverText("condition.hover.within"); - addTextField(ticksField); - } else { - // HP threshold field (as percentage) - addLabel(new GuiNpcLabel(2, "condition.percent", labelX, y + 5)); - int percent = (int) (threshold * 100); - GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, "" + percent); - thresholdField.setIntegersOnly(); - thresholdField.setMinMaxDefault(1, 99, 50); - thresholdField.setHoverText("condition.hover.threshold"); - addTextField(thresholdField); - addLabel(new GuiNpcLabel(4, "%", fieldX + 45, y + 5)); + List fields = new ArrayList<>(); + if (condition != null) { + fields = condition.getAllDefinitions(); } - // Bottom buttons - addButton(new GuiNpcButton(10, guiLeft + 8, guiTop + ySize - 28, 60, 20, "gui.cancel")); - addButton(new GuiNpcButton(11, guiLeft + xSize - 68, guiTop + ySize - 28, 60, 20, "gui.done")); + builder = new AbilityFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); + builder.startY(5); + + builder.buildScrollWindow(fields, swX, swY, swW, swH); + + int btnY = guiTop + ySize - 26; + addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + 8, btnY, 60, 20, "gui.cancel")); + addButton(new GuiNpcButton(BTN_DONE, guiLeft + xSize - 68, btnY, 60, 20, "gui.done")); } @Override public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - if (id == 1) { - // Type changed - selectedTypeIndex = ((GuiNpcButton) guibutton).getValue(); + if (id == BTN_TYPE) { + int newIndex = ((GuiNpcButton) guibutton).getValue(); + if (newIndex != selectedTypeIndex) { + selectedTypeIndex = newIndex; + condition = spawnCondition(selectedTypeIndex); + } initGui(); - } else if (id == 10) { - // Cancel - close without saving + return; + } + + if (id == BTN_CANCEL) { result = null; close(); - } else if (id == 11) { - // Done - create condition and close - result = createCondition(); + return; + } + + if (id == BTN_DONE) { + result = condition; close(); + return; + } + + if (builder != null && builder.handleButtonEvent(id, guibutton)) { + if (!hasSubGui()) { + initGui(); + } } } @Override public void unFocused(GuiNpcTextField textField) { - int id = textField.id; - - if (id == 2) { - requiredHits = textField.getInteger(); - } else if (id == 3) { - withinTicks = textField.getInteger(); - } else if (id == 4) { - int percent = textField.getInteger(); - threshold = percent / 100.0f; + if (textField.id < DECLARATIVE_ID_START) return; + if (builder != null && builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); } } - private Condition createCondition() { - String typeId = CONDITION_TYPE_IDS[selectedTypeIndex]; - - switch (typeId) { - case "hp_above": - return new Condition.ConditionHPAbove(threshold); - case "hp_below": - return new Condition.ConditionHPBelow(threshold); - case "target_hp_above": - return new Condition.ConditionTargetHPAbove(threshold); - case "target_hp_below": - return new Condition.ConditionTargetHPBelow(threshold); - case "hit_count": - return new Condition.ConditionHitCount(requiredHits, withinTicks); - default: - return null; + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (builder != null && builder.handleSubGuiClosed(subgui)) { + initGui(); } } - /** - * Get the resulting condition after dialog closes. - * Returns null if cancelled or no valid condition. - */ - public Condition getResult() { + public AbilityCondition getResult() { return result; } } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 55e94b72d..c6d745706 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2079,14 +2079,18 @@ gui.players=Players # Conditions condition.edit=Edit Condition -condition.hp_above=NPC HP Above -condition.hp_below=NPC HP Below -condition.target_hp_above=Target HP Above -condition.target_hp_below=Target HP Below +condition.filter=Filter Type +condition.filter.target=Target +condition.filter.caster=Caster +condition.filter.both=Both condition.hit_count=Hit Count -condition.percent=Threshold -condition.hits=Required Hits -condition.within=Within (ticks) +condition.hp_threshold=HP Threshold +condition.hp_above=HP Above +condition.hp_below=HP Below +condition.threshold=Threshold +condition.threshold_type=Threshold Type +condition.required_hits=Required Hits +condition.within_ticks=Within (ticks) # Condition Hover Tooltips condition.hover.type=Condition type that must be met for ability to activate From 0a85bb5a7ba0c3ffb0267dc76931b1912eed7313 Mon Sep 17 00:00:00 2001 From: luisc Date: Fri, 20 Feb 2026 19:36:45 -0600 Subject: [PATCH 22/51] - fixed dome collisions - changed dome alpha rendering - removed open container check for abilities --- .../client/renderer/RenderEnergyDome.java | 2 +- .../kamkeel/npcs/entity/EntityEnergyDome.java | 45 ++++++++++--------- .../packets/player/SpecialKeyStatePacket.java | 3 -- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java index 7388d7ec2..3e05168d9 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java @@ -51,7 +51,7 @@ public class RenderEnergyDome extends RenderEnergyBarrier { GL11.glDepthMask(true); // Render inner dome (depth write enabled so inner sphere properly occludes) - renderSphere(dome.getInnerColor(), dome.getInnerAlpha(), radius * innerScale, 8); + renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8); GL11.glPopMatrix(); restoreRenderState(); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 2d2a0ce34..0ad5a4844 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -29,6 +29,8 @@ public class EntityEnergyDome extends EntityEnergyBarrier { public EntityEnergyDome(World world) { super(world); + this.noClip = true; + this.stepHeight = 0.0F; this.setSize(1.0f, 1.0f); } @@ -36,8 +38,10 @@ public class EntityEnergyDome extends EntityEnergyBarrier { float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, EnergyBarrierData barrier) { this(world); + this.noClip = true; + this.stepHeight = 0.0F; this.ownerEntityId = owner.getEntityId(); - this.domeRadius = domeRadius; + this.setDomeRadius(domeRadius); this.displayData = display; this.lightningData = lightning; this.barrierData = barrier; @@ -45,25 +49,23 @@ public class EntityEnergyDome extends EntityEnergyBarrier { this.setPosition(x, y, z); } - protected void setSize(float width, float height){ - super.setSize(width, height); - - this.ySize = 0.0F; - this.yOffset = this.height * 0.5F; - } - - // ==================== POSITION / BOUNDING BOX ==================== - /** - * Override setPosition to maintain dome-sized bounding box. - * MC's default setPosition() resets BB based on width/height fields. - * Network sync calls setPosition(), which would shrink the BB. - * This ensures melee targeting always works against the full dome sphere. - */ @Override - public void setPosition(double x, double y, double z) { - super.setPosition(x, y, z); + protected void setSize(float width, float height) { + if (width != this.width || height != this.height) { + this.width = width; + this.height = height; + this.boundingBox.maxX = this.boundingBox.minX + (double) this.width; + this.boundingBox.maxZ = this.boundingBox.minZ + (double) this.width; + this.boundingBox.maxY = this.boundingBox.minY + (double) this.height; + } + this.ySize = 0.0F; + this.yOffset = -this.height * 0.5F; + } + + @Override + public void applyEntityCollision(Entity entityIn) { } @Override @@ -90,7 +92,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { if (isCharging()) { chargeTick++; float progress = getChargeProgress(); - this.domeRadius = targetDomeRadius * progress; + this.setDomeRadius(targetDomeRadius * progress); // Refresh BB for current charge radius this.setPosition(posX, posY, posZ); return; // Don't tick duration/death during charging @@ -196,7 +198,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { @Override public void setupCharging(int duration) { this.targetDomeRadius = this.domeRadius; - this.domeRadius = 0.01f; + this.setDomeRadius(0.01f); this.chargeDuration = duration; this.chargeTick = 0; setCharging(true); @@ -204,7 +206,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { @Override public void finishCharging() { - this.domeRadius = targetDomeRadius; + this.setDomeRadius(this.targetDomeRadius); setCharging(false); } @@ -412,6 +414,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { public void setDomeRadius(float radius) { this.domeRadius = Math.max(0.1f, radius); + this.setSize(this.domeRadius * 2, this.domeRadius * 2); } public boolean isFollowCaster() { @@ -427,7 +430,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { readBarrierBaseNBT(nbt); - this.domeRadius = sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS); + this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS)); this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); } diff --git a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java index a58b896f4..212e816b4 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -60,9 +60,6 @@ public final class SpecialKeyStatePacket extends AbstractPacket { // Trigger ability activation on key press (rising edge) if (keyDown && !wasDown) { // Don't activate if player has a GUI open (not the default inventory) - if (player.openContainer != null && !(player.openContainer instanceof net.minecraft.inventory.ContainerPlayer)) { - return; - } // Don't activate if player is riding an entity (mount) if (player.ridingEntity != null) { From 42b7d7e42eedd47a6117eb50c9b46f16e5988d8e Mon Sep 17 00:00:00 2001 From: Vidal Date: Fri, 20 Feb 2026 22:48:59 -0300 Subject: [PATCH 23/51] A few orb and beam changes and rotation sync for body and head during animations --- .../data/ability/type/energy/AbilityBeam.java | 4 +- .../data/ability/type/energy/AbilityOrb.java | 3 + .../controllers/data/PlayerAbilityData.java | 13 + .../animations/Ability_OrbBarrage_Active.json | 380 +++++++++--------- .../animations/Ability_OrbDual_Active.json | 4 +- 5 files changed, 210 insertions(+), 194 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java index 10643e7f2..0feda043a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java @@ -48,8 +48,8 @@ public class AbilityBeam extends AbilityEnergyProjectile impl this.cooldownTicks = 0; this.windUpTicks = 40; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; - this.rotationMode = RotationMode.TRACK; - this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.LOCKED; + this.rotationPhase = LockMovementType.ACTIVE; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; this.windUpAnimationName = "Ability_Beam_Windup"; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java index 8dd7125e6..90e0360e0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java @@ -115,6 +115,9 @@ public class AbilityOrb extends AbilityEnergyProjectile implem orb.setDamage(4.0f); orb.setKnockback(0.0f); orb.setKnockbackUp(0.0f); + orb.setProjectileCount(2); + orb.setFireDelay(2); + a.setLockMovement(LockMovementType.WINDUP_AND_ACTIVE); a.setMaxRange(75.0f); a.setBurstEnabled(true); a.setBurstAmount(15); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 0e32a37e7..1762a24c5 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -23,6 +23,7 @@ import net.minecraft.util.DamageSource; import noppes.npcs.AbstractDataAbilities; import noppes.npcs.EventHooks; import noppes.npcs.LogWriter; +import noppes.npcs.NoppesUtilPlayer; import noppes.npcs.api.ability.IPlayerAbilityData; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.controllers.ScriptController; @@ -297,6 +298,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA // Apply rotation and position locks after ability tick applyRotationControl(player); applyPositionLock(player); + applyAnimationRotationSync(player); // Sync lock state to client (only sends when flags change) syncAbilityStateIfNeeded(player); @@ -844,6 +846,17 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } } + private void applyAnimationRotationSync(EntityPlayer player) { + if (rotationLocked || currentAbility == null) return; + if (currentAbility.getPhase() == AbilityPhase.IDLE || currentAbility.getPhase() == AbilityPhase.DAZED) + return; + + // TODO This is a temporary duct-tape solution to fix the animation not rotating with head rotation + if (!currentAbility.isRotationLockedForCurrentPhase() && player instanceof EntityPlayerMP) { + NoppesUtilPlayer.swingPlayerArm((EntityPlayerMP) player); + } + } + // ═══════════════════════════════════════════════════════════════════ // POSITION LOCKING (Player-specific application) // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json index 0a0ba828c..e34dd5d21 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json @@ -1,196 +1,196 @@ { - "Loop": 1, + "Loop": 2, "Speed": 1.0f, "Frames": [ - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": -7.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": -31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -6.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "LEFT_ARM", - "Rotation1": -25.0f, - "Rotation0": -90.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": -25.0f - } - ], - "Smooth": 0b, - "Duration": 2 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": -7.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": -31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": -1.0f, - "Part": "RIGHT_ARM", - "Rotation1": 25.0f, - "Rotation0": -90.0f, - "Pivot0": 1.0f, - "Pivot1": 1.0f, - "Rotation2": 25.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -6.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -7.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 5 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": -7.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": -31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -6.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "LEFT_ARM", - "Rotation1": -25.0f, - "Rotation0": -90.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": -25.0f - } - ], - "Smooth": 0b, - "Duration": 5 - } + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 25.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 25.0f + }, + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } ], "CurrentFrameTime": 0, "CurrentFrame": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json index 58a305e78..c632afc9c 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json @@ -1,5 +1,5 @@ { - "Loop": 3, + "Loop": -1, "Speed": 1.0f, "Frames": [ { @@ -252,7 +252,7 @@ } ], "Smooth": 0b, - "Duration": 3 + "Duration": 20 } ], "CurrentFrameTime": 0, From fb938c2b7d7493777a9e4e0bb78e82188bc96ac9 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 21 Feb 2026 01:12:30 -0300 Subject: [PATCH 24/51] Fixed charge and orb active anim --- .../npcs/controllers/data/ability/type/AbilityCharge.java | 2 +- .../assets/customnpcs/animations/Ability_Orb_Active.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index 79c16b21e..bc2da7cae 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -52,7 +52,7 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { this.windUpSound = "mob.zombie.wood"; this.activeSound = "mob.zombie.attack"; this.windUpAnimationName = "Ability_Charge_Windup"; - this.activeAnimationName = "Ability_Active_Windup"; + this.activeAnimationName = "Ability_Charge_Active"; } @Override diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json index 994e2190c..cb8973971 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json @@ -1,11 +1,11 @@ { - "Loop": 0, + "Loop": -1, "Speed": 1.0f, "Frames": [ { "ColorMarker": 16777215, "Comment": "", - "Speed": 0.5f, + "Speed": 1.0f, "FrameParts": [ { "Pivot2": 0.0f, @@ -63,7 +63,7 @@ } ], "Smooth": 0b, - "Duration": 30 + "Duration": 20 } ], "CurrentFrameTime": 0, From 36babe51cc22e2916305c603cd628f9c479e880d Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 21 Feb 2026 01:12:57 -0300 Subject: [PATCH 25/51] Added ConditionItem and increased the max amount of conditions an ability can hold to 5 --- .../npcs/controllers/AbilityController.java | 2 + .../ability/conditions/AbilityCondition.java | 4 +- .../ability/conditions/ConditionItem.java | 201 ++++++++++++++++++ .../gui/advanced/SubGuiAbilityConfig.java | 30 ++- .../advanced/SubGuiChainedAbilityConfig.java | 11 +- .../assets/customnpcs/lang/en_US.lang | 14 +- 6 files changed, 244 insertions(+), 18 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index f226a505c..1da844451 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -4,6 +4,7 @@ import kamkeel.npcs.controllers.data.ability.*; import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold; import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionItem; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; @@ -152,6 +153,7 @@ public class AbilityController implements IAbilityHandler { private void registerBuiltinConditionTypes() { registerCondition(ConditionHPThreshold::new); registerCondition(ConditionHitCount::new); + registerCondition(ConditionItem::new); } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java index 95d38bf9b..6fc7b8a12 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -14,6 +14,8 @@ import java.util.List; import java.util.function.Supplier; public abstract class AbilityCondition { + public static final int MAX_CONDITIONS = 5; + protected String typeId = ""; protected String name = ""; protected UserType userType = UserType.BOTH; @@ -69,7 +71,7 @@ public abstract class AbilityCondition { nbt.setString("typeId", getTypeId()); nbt.setString("name", getName()); nbt.setInteger("userType", getUserType().ordinal()); - nbt.setInteger("filter", getUserType().ordinal()); + nbt.setInteger("filter", getFilter().ordinal()); writeTypeNBT(nbt); return nbt; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java new file mode 100644 index 000000000..14b751d29 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -0,0 +1,201 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +public class ConditionItem extends AbilityCondition { + + public enum UsageType { + ARMOR, HOLDING, AMMO, OFFHAND; + + public static UsageType fromOrdinal(int ordinal) { + UsageType[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : HOLDING; + } + } + + public enum ArmorSlot { + BOOTS, LEGS, CHEST, HELMET; + + public static ArmorSlot fromOrdinal(int ordinal) { + ArmorSlot[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : BOOTS; + } + } + + // Shared + private UsageType usageType = UsageType.HOLDING; + private String itemName = ""; + + // ARMOR only + private ArmorSlot armorSlot = ArmorSlot.BOOTS; + private boolean fullArmorSet = false; + + // AMMO + PLAYER only + private int requiredCount = 1; + + public ConditionItem() { + this.typeId = "condition.cnpc.item"; + this.name = "condition.item"; + } + + @Override + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + switch (getFilter()) { + case CASTER: + return checkEntity(caster); + case TARGET: + return target != null && checkEntity(target); + case BOTH: + return checkEntity(caster) && (target != null && checkEntity(target)); + default: + return checkEntity(caster); + } + } + + private boolean checkEntity(EntityLivingBase entity) { + switch (usageType) { + case HOLDING: + return checkHolding(entity); + case ARMOR: + return checkArmor(entity); + case AMMO: + return checkAmmo(entity); + case OFFHAND: + return checkOffhand(entity); + default: + return false; + } + } + + private boolean checkHolding(EntityLivingBase entity) { + ItemStack held = entity.getHeldItem(); + return matchesItem(held); + } + + private boolean checkArmor(EntityLivingBase entity) { + // MC getEquipmentInSlot: 1=boots, 2=legs, 3=chest, 4=helmet + int slot = armorSlot.ordinal() + 1; // BOOTS=0, LEGS=1, CHEST=2, HELMET=3 + return matchesItem(entity.getEquipmentInSlot(slot)); + } + + private boolean checkFullArmor(EntityLivingBase entity) { + for (int i = 0; i < 4; i++) { + int slot = i + 1; + if (!matchesItem(i, entity.getEquipmentInSlot(slot))) + return false; + } + + return true; + } + + private boolean checkAmmo(EntityLivingBase entity) { + if (entity instanceof EntityPlayer) { + return checkPlayerInventoryCount((EntityPlayer) entity); + } + if (entity instanceof EntityNPCInterface) { + return checkNPCProjectile((EntityNPCInterface) entity); + } + + return false; + } + + private boolean checkOffhand(EntityLivingBase entity) { + // No offhand for players + if (entity instanceof EntityPlayer) return false; + + ItemStack item = ((EntityNPCInterface) entity).getOffHand(); + return matchesItem(item); + } + + private boolean checkPlayerInventoryCount(EntityPlayer player) { + int count = 0; + for (ItemStack stack : player.inventory.mainInventory) { + if (matchesItem(stack)) { + count += stack.stackSize; + } + } + return count >= requiredCount; + } + + private boolean checkNPCProjectile(EntityNPCInterface npc) { + ItemStack projectile = npc.inventory.getProjectile(); + return matchesItem(projectile); + } + + private boolean matchesItem(ItemStack stack) { + return matchesItem(0, stack); + } + + private boolean matchesItem(int index, ItemStack stack) { + if (stack == null || itemName == null || itemName.isEmpty()) return false; + String registryName = net.minecraft.item.Item.itemRegistry.getNameForObject(stack.getItem()); + return itemName.equals(registryName); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.enumField("condition.usage_type", UsageType.class, + this::getUsageType, this::setUsageType)); + + defs.add(FieldDef.stringField("condition.item_name", + this::getItemName, this::setItemName)); +// .hover("condition.hover.item_name")); + + + + defs.add(FieldDef.enumField("condition.armor_slot", ArmorSlot.class, + this::getArmorSlot, this::setArmorSlot) + .visibleWhen(() -> usageType == UsageType.ARMOR)); +// .hover("condition.hover.armor_slots")); + + defs.add(FieldDef.intField("condition.item_count", + this::getRequiredCount, this::setRequiredCount) + .range(1, 64) + .visibleWhen(() -> usageType == UsageType.AMMO && userType.allowsPlayer())); +// .hover("condition.hover.required_count")); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setString("itemName", itemName); + nbt.setInteger("usageType", usageType.ordinal()); + nbt.setInteger("armorSlot", armorSlot.ordinal()); + nbt.setInteger("requiredCount", requiredCount); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + itemName = nbt.getString("itemName"); + usageType = UsageType.fromOrdinal(nbt.getInteger("usageType")); + armorSlot = ArmorSlot.fromOrdinal(nbt.getInteger("armorSlot")); + requiredCount = nbt.getInteger("requiredCount"); + } + + + public UsageType getUsageType() { return usageType; } + public void setUsageType(UsageType usageType) { this.usageType = usageType; } + + public String getItemName() { return itemName; } + public void setItemName(String itemName) { this.itemName = itemName; } + + public ArmorSlot getArmorSlot() { return armorSlot; } + public void setArmorSlot(ArmorSlot armorSlot) { this.armorSlot = armorSlot; } + + public boolean isFullArmorSet() { + return fullArmorSet; + } + + public void setFullArmorSet(boolean fullArmorSet) { + this.fullArmorSet = fullArmorSet; + } + + public int getRequiredCount() { return requiredCount; } + public void setRequiredCount(int requiredCount) { this.requiredCount = Math.max(1, requiredCount); } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index b611e4e6b..a3cee0443 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -20,6 +20,8 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; import java.util.List; +import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS; + public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { private static final int DECLARATIVE_ID_START = 1000; @@ -42,6 +44,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi private static final int L_LABEL_X = 5; private static final int ROW_H = 24; + // Condition buttons + private static final int COND_BASE = 50; + private static final int COND_STRIDE = 10; + private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10 + private static final int BTN_ADD_COND = COND_END; + private final Ability ability; private final IAbilityConfigCallback callback; private int activeTab = TAB_GENERAL; @@ -234,17 +242,17 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); y += 15; - for (int i = 0; i < conditions.size() && i < 3; i++) { + for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { AbilityCondition cond = conditions.get(i); String condName = getConditionDisplayName(cond); - sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); - sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); - sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); y += 22; } - if (conditions.size() < 3) { - sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); + if (conditions.size() < MAX_CONDITIONS) { + sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));; y += ROW_H; } @@ -312,9 +320,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } private boolean handleConditionButton(int id) { - if (id >= 50 && id < 80) { - int condIndex = (id - 50) / 10; - int action = (id - 50) % 10; + if (id >= COND_BASE && id < COND_END) { + int condIndex = (id - COND_BASE) / COND_STRIDE; + int action = (id - COND_BASE) % COND_STRIDE; if (action == 0 || action == 1) { if (condIndex < conditions.size()) { editingConditionIndex = condIndex; @@ -328,8 +336,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } return true; } - if (id == 80) { - if (conditions.size() < 3) { + if (id == BTN_ADD_COND) { + if (conditions.size() < MAX_CONDITIONS) { editingConditionIndex = conditions.size(); setSubGui(new SubGuiConditionEdit(null)); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index 9783bb9a7..d1946e2e2 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -32,6 +32,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS; /** * SubGui for editing a {@link ChainedAbility}. @@ -70,9 +71,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText // Actual ID = COND_BASE + i * COND_STRIDE + offset // offset 0 = name/click, 1 = edit, 2 = delete private static final int COND_BASE = 50; - private static final int COND_END = 80; private static final int COND_STRIDE = 10; - private static final int BTN_ADD_COND = 80; + private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10 + private static final int BTN_ADD_COND = COND_END; // ── Layout constants ────────────────────────────────────────────────────── private static final int L_LABEL_X = 5; @@ -427,7 +428,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); y += 15; - for (int i = 0; i < conditions.size() && i < 3; i++) { + for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { AbilityCondition cond = conditions.get(i); String condName = getConditionDisplayName(cond); sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); @@ -436,7 +437,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText y += 22; } - if (conditions.size() < 3) { + if (conditions.size() < MAX_CONDITIONS) { sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); y += ROW_H; } @@ -615,7 +616,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText return true; } if (id == BTN_ADD_COND) { - if (conditions.size() < 3) { + if (conditions.size() < MAX_CONDITIONS) { editingConditionIndex = conditions.size(); setSubGui(new SubGuiConditionEdit(null)); } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index c6d745706..d32b62471 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2083,15 +2083,27 @@ condition.filter=Filter Type condition.filter.target=Target condition.filter.caster=Caster condition.filter.both=Both -condition.hit_count=Hit Count + +# Condition HP Threshold condition.hp_threshold=HP Threshold condition.hp_above=HP Above condition.hp_below=HP Below condition.threshold=Threshold condition.threshold_type=Threshold Type + +# Condition Hit Count +condition.hit_count=Hit Count condition.required_hits=Required Hits condition.within_ticks=Within (ticks) +# Condition Item +condition.item=Has Item +condition.usage_type=Usage Type +condition.armor_slot=Armor Slot +condition.full_armor=Full Armor +condition.item_count=Item Count +condition.item_name=Item Name + # Condition Hover Tooltips condition.hover.type=Condition type that must be met for ability to activate condition.hover.hpAbove=Activates when NPC health is above this percentage From acb99b5c48f53ea568cc6745b3347277d82e343d Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 21 Feb 2026 01:21:33 -0300 Subject: [PATCH 26/51] Added percent option to ConditionHPThreshold and added EQUAL comparison type --- .../conditions/ConditionHPThreshold.java | 52 +++++++++++++------ .../assets/customnpcs/lang/en_US.lang | 2 + 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java index 803fc978c..5eed753fa 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -8,19 +8,26 @@ import java.util.List; public class ConditionHPThreshold extends AbilityCondition{ private float threshold = 0.5f; // 50% + private boolean percent = true; private ThresholdType thresholdType = ThresholdType.ABOVE; public enum ThresholdType { ABOVE { @Override public boolean test(float value, float threshold) { - return value >= threshold; + return value > threshold; } }, BELOW { @Override public boolean test(float value, float threshold) { - return value <= threshold; + return value < threshold; + } + }, + EQUAL { + @Override + public boolean test(float value, float threshold) { + return value == threshold; } }; @@ -41,6 +48,8 @@ public class ConditionHPThreshold extends AbilityCondition{ return "condition.hp_above"; case BELOW: return "condition.hp_below"; + case EQUAL: + return "condition.hp_equal"; default: return name(); } @@ -54,8 +63,8 @@ public class ConditionHPThreshold extends AbilityCondition{ @Override public boolean check(EntityLivingBase caster, EntityLivingBase target) { - float casterHP = caster.getHealth() / caster.getMaxHealth(); - float targetHP = target.getHealth() / target.getMaxHealth(); + float casterHP = isPercent() ? caster.getHealth() / caster.getMaxHealth() : caster.getHealth(); + float targetHP = isPercent() ? target.getHealth() / target.getMaxHealth() : target.getHealth(); return compare(casterHP, targetHP); @@ -75,6 +84,24 @@ public class ConditionHPThreshold extends AbilityCondition{ } } + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.floatField("condition.threshold", this::getThreshold, this::setThreshold).min(0)); + defs.add(FieldDef.boolField("condition.percent", this::isPercent, this::setIsPercent)); + defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, + this::getThresholdType, this::setThresholdType)); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("threshold", threshold); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + threshold = nbt.getFloat("threshold"); + } + public float getThreshold() { return threshold; } @@ -91,20 +118,11 @@ public class ConditionHPThreshold extends AbilityCondition{ this.thresholdType = thresholdType; } - @Override - public void getConditionDefinitions(List defs) { - defs.add(FieldDef.floatField("condition.threshold", this::getThreshold, this::setThreshold).min(0)); - defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, - this::getThresholdType, this::setThresholdType)); + public boolean isPercent() { + return percent; } - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("threshold", threshold); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - threshold = nbt.getFloat("threshold"); + public void setIsPercent(boolean percent) { + this.percent = percent; } } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index d32b62471..b3e09b08f 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2088,7 +2088,9 @@ condition.filter.both=Both condition.hp_threshold=HP Threshold condition.hp_above=HP Above condition.hp_below=HP Below +condition.hp_equal=HP Equal condition.threshold=Threshold +condition.percent=Use Percent condition.threshold_type=Threshold Type # Condition Hit Count From e711a9012b7c7ee1c7ca8b92fb55b1ed7ed865bf Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 20 Feb 2026 23:55:32 -0500 Subject: [PATCH 27/51] Fix barrier solid/knockback behavior and dome melee targeting - Rewrite solid system to use reactive crossing detection (prevPos comparison) instead of prediction-based teleportation that caused client rubber-banding - Reduce knockback force (0.06 multiplier) so it pushes without fully blocking - Add client-side solid prediction for smooth movement blocking (local player only) - Fix dome melee from inside: canBeCollidedWith returns false when player is inside - Fix dome melee from outside: getCollisionBorderSize set to 0 to prevent raycast from returning far exit point beyond reach distance - Clean up dome bounding box: use setPosition/updateBoundingBox instead of custom setSize Co-Authored-By: Claude Opus 4.6 --- .../kamkeel/npcs/entity/EntityEnergyDome.java | 221 +++++++++++------- .../npcs/entity/EntityEnergyPanel.java | 125 ++++++---- 2 files changed, 214 insertions(+), 132 deletions(-) diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 0ad5a4844..e4fb4a158 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -7,10 +7,12 @@ import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; +import noppes.npcs.CustomNpcs; import java.util.List; @@ -53,15 +55,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { @Override protected void setSize(float width, float height) { - if (width != this.width || height != this.height) { - this.width = width; - this.height = height; - this.boundingBox.maxX = this.boundingBox.minX + (double) this.width; - this.boundingBox.maxZ = this.boundingBox.minZ + (double) this.width; - this.boundingBox.maxY = this.boundingBox.minY + (double) this.height; - } - this.ySize = 0.0F; - this.yOffset = -this.height * 0.5F; + super.setSize(width, height); } @Override @@ -102,9 +96,11 @@ public class EntityEnergyDome extends EntityEnergyBarrier { if (updateBarrierTick()) return; - // Knockback velocity push every tick - if (!worldObj.isRemote && barrierData.knockbackEnabled) { - knockbackEntities(); + // Process entity physics every tick + // Server: solid + knockback for all entities + // Client: solid prediction for local player only (smooth movement blocking) + if (barrierData.solid || barrierData.knockbackEnabled) { + processEntityPhysics(); } } @@ -210,49 +206,50 @@ public class EntityEnergyDome extends EntityEnergyBarrier { setCharging(false); } - // ==================== KNOCKBACK (DBO-style motion prediction) ==================== + // ==================== ENTITY PHYSICS (Solid + Knockback) ==================== /** - * DBO Ki Shield style knockback — unified algorithm with geometric jail: + * Processes entity physics for the dome barrier. Two independent systems: *

- * When jailEnabled = false (default): - * - OUTSIDE entities: predict future position, if it would cross into dome push outward. - * If close and approaching, apply soft outward push. Full motion replacement. - * - INSIDE entities: NOT affected (free movement). Dome only blocks entry. + * SOLID: Hard wall — entities cannot cross the dome boundary in either direction. + * Uses reactive crossing detection: compares current position to previous tick + * to detect boundary crossings, then teleports back and applies velocity correction. + * Also preemptively cancels inward velocity when near the surface. *

- * When jailEnabled = true: - * - OUTSIDE entities: pushed outward (same as above, prevents entry). - * - INSIDE entities: pushed inward when near edge (geometric containment). - * Any entity inside stays inside, any entity outside stays outside. + * KNOCKBACK: Repulsion force — entities near the dome surface get pushed away. + * This is a push effect only; entities can still pass through with enough effort. + * Does NOT prevent passthrough — use solid for that. *

* For moving domes (followCaster), dome velocity is accounted for by using - * relative velocity (entity motion minus dome motion) for predictions. + * the dome's previous position for previous-tick distance calculations. */ @Override @SuppressWarnings("unchecked") - protected void knockbackEntities() { - float margin = 2.0f; + protected void processEntityPhysics() { float r = domeRadius; + boolean solid = barrierData.solid; + boolean knockback = barrierData.knockbackEnabled; float strength = barrierData.knockbackStrength; - boolean jail = barrierData.jailEnabled; - float jailThresh = barrierData.jailThreshold; - // Dome velocity for moving domes (followCaster) - double domeVelX = posX - prevPosX; - double domeVelY = posY - prevPosY; - double domeVelZ = posZ - prevPosZ; + float solidMargin = 1.5f; // Zone around surface for preemptive velocity correction + float knockbackMargin = 2.0f; // Zone around surface for knockback push AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - r - margin, posY - r - margin, posZ - r - margin, - posX + r + margin, posY + r + margin, posZ + r + margin + posX - r - knockbackMargin, posY - r - knockbackMargin, posZ - r - knockbackMargin, + posX + r + knockbackMargin, posY + r + knockbackMargin, posZ + r + knockbackMargin ); + // On client, identify local player for client-side solid prediction + EntityPlayer localPlayer = worldObj.isRemote ? CustomNpcs.proxy.getPlayer() : null; + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); for (EntityLivingBase ent : entities) { if (ent.getEntityId() == ownerEntityId) continue; - if (!isKnockbackTarget(ent)) continue; if (isAllyOfOwner(ent)) continue; + // Client-side: only process local player for solid prediction + if (worldObj.isRemote && (localPlayer == null || ent != localPlayer)) continue; + // Current position relative to dome center double dx = ent.posX - posX; double dy = (ent.posY + ent.height * 0.5) - posY; @@ -265,71 +262,76 @@ public class EntityEnergyDome extends EntityEnergyBarrier { double ny = dy / dist; double nz = dz / dist; - // Entity velocity relative to dome (accounts for moving domes) - double relVelX = ent.motionX - domeVelX; - double relVelY = ent.motionY - domeVelY; - double relVelZ = ent.motionZ - domeVelZ; - boolean isInside = dist < r; - if (isInside && jail) { - // --- INSIDE + JAIL ENABLED: push toward center when near dome edge --- - if (dist > r * jailThresh) { - double overshoot = dist - r * jailThresh; - double force = (overshoot + 0.1) * strength * 0.2; - // Set motion to dome velocity + inward push (keeps entity moving with dome) - ent.motionX = domeVelX - nx * force; - ent.motionY = domeVelY - ny * force; - ent.motionZ = domeVelZ - nz * force; + // --- SOLID: hard wall preventing boundary crossing --- + if (solid) { + // Previous tick: entity position relative to dome's previous position + double prevDx = ent.prevPosX - prevPosX; + double prevDy = (ent.prevPosY + ent.height * 0.5) - prevPosY; + double prevDz = ent.prevPosZ - prevPosZ; + double prevDist = Math.sqrt(prevDx * prevDx + prevDy * prevDy + prevDz * prevDz); + boolean wasInside = prevDist < r; + + // Radial velocity (positive = moving outward from dome center) + double radialVel = ent.motionX * nx + ent.motionY * ny + ent.motionZ * nz; + + if (wasInside != isInside) { + // Entity crossed the boundary this tick — push back to original side + double pushDist = wasInside ? (r - 0.3) : (r + 0.3); + double surfaceX = posX + nx * pushDist; + double surfaceY = posY + ny * pushDist - ent.height * 0.5; + double surfaceZ = posZ + nz * pushDist; + teleportEntity(ent, surfaceX, surfaceY, surfaceZ); + + // Cancel radial velocity and add corrective push + ent.motionX -= radialVel * nx; + ent.motionY -= radialVel * ny; + ent.motionZ -= radialVel * nz; + double pushForce = wasInside ? -0.15 : 0.15; + ent.motionX += nx * pushForce; + ent.motionZ += nz * pushForce; ent.velocityChanged = true; } else { - // Predict if entity would escape next tick (relative to dome) - double futDx = dx + relVelX; - double futDy = dy + relVelY; - double futDz = dz + relVelZ; - double futDist = Math.sqrt(futDx * futDx + futDy * futDy + futDz * futDz); - if (futDist >= r) { - // Would escape: cancel outward motion, match dome velocity - double radialVel = relVelX * nx + relVelY * ny + relVelZ * nz; - if (radialVel > 0) { + // Preemptive: near surface and moving toward it — cancel radial velocity + double surfaceDist = Math.abs(dist - r); + if (surfaceDist < solidMargin) { + boolean movingTowardSurface = (!isInside && radialVel < -0.01) + || (isInside && radialVel > 0.01); + if (movingTowardSurface) { ent.motionX -= radialVel * nx; ent.motionY -= radialVel * ny; ent.motionZ -= radialVel * nz; + double pushForce = isInside ? -0.05 : 0.05; + ent.motionX += nx * pushForce; + ent.motionZ += nz * pushForce; ent.velocityChanged = true; } } } - } else if (!isInside) { - // --- OUTSIDE: push outward (prevent entry) --- + } - // Predicted future distance from center (relative to dome movement) - double futDx = dx + relVelX; - double futDy = dy + relVelY; - double futDz = dz + relVelZ; - double futDist = Math.sqrt(futDx * futDx + futDy * futDy + futDz * futDz); + // --- KNOCKBACK: repulsion push (server only, synced via velocityChanged) --- + if (!worldObj.isRemote && knockback) { + double surfaceDist = Math.abs(dist - r); + if (surfaceDist < knockbackMargin) { + double proximity = 1.0 - (surfaceDist / knockbackMargin); + double force = proximity * strength * 0.06; - // Radial velocity relative to dome (positive = moving away) - double radialVel = relVelX * nx + relVelY * ny + relVelZ * nz; - - if (futDist < r) { - // Would cross INTO dome: hard push outward proportional to overshoot - double overshoot = r - futDist; - double force = (overshoot * 2.0 + 0.05) * strength * 0.1; - ent.motionX = domeVelX + nx * force; - ent.motionY = domeVelY + ny * force * 0.5; - ent.motionZ = domeVelZ + nz * force; - ent.velocityChanged = true; - } else if (radialVel < 0 && dist < r + margin) { - // Close and approaching: soft push outward proportional to proximity - double proximity = 1.0 - ((dist - r) / margin); - double force = proximity * strength * 0.1; - ent.motionX = domeVelX + nx * force; - ent.motionY = domeVelY + ny * force * 0.5; - ent.motionZ = domeVelZ + nz * force; + if (isInside) { + // Push toward center (away from surface) + ent.motionX += -nx * force; + ent.motionY += -ny * force * 0.5; + ent.motionZ += -nz * force; + } else { + // Push outward (away from surface) + ent.motionX += nx * force; + ent.motionY += ny * force * 0.5; + ent.motionZ += nz * force; + } ent.velocityChanged = true; } } - // else: INSIDE + no jail → do nothing (free movement) } } @@ -346,6 +348,24 @@ public class EntityEnergyDome extends EntityEnergyBarrier { // ==================== MELEE (spherical check) ==================== + /** + * On the client side, the dome's large bounding box intercepts all raycasts from inside, + * preventing the player from targeting mobs within the dome. To fix this, return false + * when the local player is inside the dome so the raycast passes through to other entities. + * Players outside the dome can still target it for melee normally. + */ + @Override + public boolean canBeCollidedWith() { + if (!barrierData.meleeEnabled) return false; + if (worldObj.isRemote) { + EntityPlayer player = CustomNpcs.proxy.getPlayer(); + if (player != null && isEntityInside(player)) { + return false; + } + } + return true; + } + /** * Reject melee hits that land on the cubic bounding box but are outside the actual sphere. * Uses distance from the sphere surface (not center) for accurate spherical rejection. @@ -368,13 +388,14 @@ public class EntityEnergyDome extends EntityEnergyBarrier { // ==================== BOUNDING BOX ==================== /** - * Small expansion on top of the dome-sized bounding box for comfortable - * melee targeting. The actual BB is already dome-sized (set in onUpdate), - * so this only adds a small reach margin for crosshair ray-testing. + * No expansion needed — the bounding box is already dome-sized. + * Returning 0 ensures players outside the dome sphere are also outside the + * ray-testing BB, so MC's raycast returns the near-face hit (within reach) + * rather than the far exit point (beyond reach). */ @Override public float getCollisionBorderSize() { - return 1.0f; + return 0.0f; } @Override @@ -414,7 +435,7 @@ public class EntityEnergyDome extends EntityEnergyBarrier { public void setDomeRadius(float radius) { this.domeRadius = Math.max(0.1f, radius); - this.setSize(this.domeRadius * 2, this.domeRadius * 2); + this.setPosition(this.posX, this.posY, this.posZ); } public boolean isFollowCaster() { @@ -425,6 +446,30 @@ public class EntityEnergyDome extends EntityEnergyBarrier { this.followCaster = follow; } + @Override + @SideOnly(Side.CLIENT) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int increments) { + // Don't do the vanilla "push up out of blocks" logic. + this.setPosition(x, y, z); + this.setRotation(yaw, pitch); + } + + @Override + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + updateBoundingBox(); + } + + protected void updateBoundingBox() { + float r = this.domeRadius; + this.boundingBox.setBounds( + this.posX - r, this.posY - r, this.posZ - r, + this.posX + r, this.posY + r, this.posZ + r + ); + } + // ==================== NBT ==================== @Override diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index cd33f6460..1ef8dc370 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -13,6 +13,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; +import noppes.npcs.CustomNpcs; import noppes.npcs.NpcDamageSource; import noppes.npcs.entity.EntityNPCInterface; @@ -119,9 +120,11 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { if (updateBarrierTick()) return; - // Knockback velocity push every tick (not during launched mode) - if (!worldObj.isRemote && barrierData.knockbackEnabled && mode != PanelMode.LAUNCHED) { - knockbackEntities(); + // Process entity physics every tick (not during launched mode) + // Server: solid + knockback for all entities + // Client: solid prediction for local player only (smooth movement blocking) + if ((barrierData.solid || barrierData.knockbackEnabled) && mode != PanelMode.LAUNCHED) { + processEntityPhysics(); } // Mode-specific updates @@ -365,21 +368,28 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { setCharging(false); } - // ==================== KNOCKBACK (DBO-style motion prediction) ==================== + // ==================== ENTITY PHYSICS (Solid + Knockback) ==================== /** - * DBO-inspired planar knockback: - * - Predict future position from current motion - * - Detect crossing or proximity to panel surface - * - Apply counter-force via full motion replacement - * - No separate phases — single unified algorithm + * Processes entity physics for the panel barrier. Two independent systems: + *

+ * SOLID: Hard wall — entities cannot cross the panel plane within its bounds. + * Uses reactive crossing detection: compares current side to previous tick + * to detect plane crossings, then teleports back and applies velocity correction. + * Also preemptively cancels normal velocity when near the plane. + *

+ * KNOCKBACK: Repulsion force — entities near the panel surface get pushed away. + * This is a push effect only; entities can still pass through with enough effort. + * Does NOT prevent passthrough — use solid for that. */ @Override @SuppressWarnings("unchecked") - protected void knockbackEntities() { + protected void processEntityPhysics() { float halfW = panelData.panelWidth * 0.5f; float halfH = panelData.panelHeight * 0.5f; - float searchExtension = 5.0f; + float searchExtension = 3.0f; + boolean solid = barrierData.solid; + boolean knockback = barrierData.knockbackEnabled; float strength = barrierData.knockbackStrength; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( @@ -387,6 +397,9 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { posX + halfW + searchExtension, posY + halfH + searchExtension, posZ + halfW + searchExtension ); + // On client, identify local player for client-side solid prediction + EntityPlayer localPlayer = worldObj.isRemote ? CustomNpcs.proxy.getPlayer() : null; + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); float yawRad = (float) Math.toRadians(panelYaw); float normalX = -(float) Math.sin(yawRad); @@ -394,9 +407,11 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { for (EntityLivingBase ent : entities) { if (ent.getEntityId() == ownerEntityId) continue; - if (!isKnockbackTarget(ent)) continue; if (isAllyOfOwner(ent)) continue; + // Client-side: only process local player for solid prediction + if (worldObj.isRemote && (localPlayer == null || ent != localPlayer)) continue; + // Current position relative to panel center double dx = ent.posX - posX; double dy = (ent.posY + ent.height * 0.5) - posY; @@ -407,45 +422,67 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { float localRight = (float) (dx * (-normalZ) + dz * normalX); // Skip if outside panel bounds (with margin) - if (Math.abs(localRight) > halfW + searchExtension) continue; - if (Math.abs(dy) > halfH + searchExtension) continue; - if (Math.abs(localForward) > searchExtension) continue; - - // Skip if outside panel width/height bounds (no wall to push against) if (Math.abs(localRight) > halfW + 1.0f) continue; if (Math.abs(dy) > halfH + 1.0f) continue; - - // Predicted future position - double futDx = (ent.posX + ent.motionX) - posX; - double futDz = (ent.posZ + ent.motionZ) - posZ; - float futLocalForward = (float) (futDx * normalX + futDz * normalZ); - - // Normal velocity component (positive = moving in normal direction) - double normalVel = ent.motionX * normalX + ent.motionZ * normalZ; + if (Math.abs(localForward) > searchExtension) continue; // Determine which side the entity is on float side = localForward >= 0 ? 1.0f : -1.0f; - boolean movingTowardPanel = (localForward >= 0 && normalVel < 0) || (localForward < 0 && normalVel > 0); - // Check if predicted position would cross the plane (sign change) - boolean wouldCross = (localForward > 0 && futLocalForward <= 0) || (localForward < 0 && futLocalForward >= 0); + // Check if within panel width/height bounds + boolean inBounds = Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH; - if (wouldCross && Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH) { - // Hard block: full motion replacement to prevent crossing - // Push back along normal, proportional to how far past the surface they'd go - double overshoot = Math.abs(futLocalForward); - double pushForce = (overshoot + 0.05) * strength * 0.1; - ent.motionX = normalX * side * pushForce; - ent.motionZ = normalZ * side * pushForce; - ent.velocityChanged = true; - } else if (Math.abs(localForward) < 1.0 && movingTowardPanel - && Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH) { - // Soft push: entity is close and approaching, apply proportional force - double proximity = 1.0 - Math.abs(localForward); - double pushForce = proximity * strength * 0.1; - ent.motionX = normalX * side * pushForce; - ent.motionZ = normalZ * side * pushForce; - ent.velocityChanged = true; + // --- SOLID: hard wall preventing plane crossing --- + if (solid && inBounds) { + // Previous tick: entity position relative to panel + double prevDx = ent.prevPosX - prevPosX; + double prevDz = ent.prevPosZ - prevPosZ; + float prevLocalForward = (float) (prevDx * normalX + prevDz * normalZ); + float prevSide = prevLocalForward >= 0 ? 1.0f : -1.0f; + + // Normal velocity component (positive = moving in normal direction) + double normalVel = ent.motionX * normalX + ent.motionZ * normalZ; + + if (prevSide != side) { + // Entity crossed the panel plane this tick — push back to original side + double pushDist = 0.3; + double newX = posX + normalX * prevSide * pushDist + (localRight * (-normalZ)); + double newZ = posZ + normalZ * prevSide * pushDist + (localRight * normalX); + teleportEntity(ent, newX, ent.posY, newZ); + + // Cancel normal velocity and add corrective push + ent.motionX -= normalVel * normalX; + ent.motionZ -= normalVel * normalZ; + ent.motionX += normalX * prevSide * 0.15; + ent.motionZ += normalZ * prevSide * 0.15; + ent.velocityChanged = true; + } else { + // Preemptive: near the plane and moving toward it — cancel normal velocity + double absDist = Math.abs(localForward); + if (absDist < 1.5) { + boolean movingToward = (side > 0 && normalVel < -0.01) + || (side < 0 && normalVel > 0.01); + if (movingToward) { + ent.motionX -= normalVel * normalX; + ent.motionZ -= normalVel * normalZ; + ent.motionX += normalX * side * 0.05; + ent.motionZ += normalZ * side * 0.05; + ent.velocityChanged = true; + } + } + } + } + + // --- KNOCKBACK: repulsion push (server only, synced via velocityChanged) --- + if (!worldObj.isRemote && knockback && inBounds) { + double absDist = Math.abs(localForward); + if (absDist < searchExtension) { + double proximity = 1.0 - (absDist / searchExtension); + double force = proximity * strength * 0.06; + ent.motionX += normalX * side * force; + ent.motionZ += normalZ * side * force; + ent.velocityChanged = true; + } } } } From b3357a27512e9e6bb935f403c78026693dd9e29c Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 00:57:49 -0500 Subject: [PATCH 28/51] Fix dome melee for all radii with server-side tick detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MC's processUseEntity uses player.getDistanceSqToEntity(dome) for reach validation, which computes center-to-center distance. For domes with radius > 5, this always exceeds the 36-block threshold, making melee impossible regardless of how close the player is to the surface. Fix: server-side processMeleeHits() in onUpdate detects swinging players near the dome surface via ray-sphere intersection, then calls attackTargetEntityWithCurrentItem directly — bypassing MC's broken reach check while preserving full damage calculation (enchantments, crits, etc). Also adds adjustMeleeBoundingBox for client-side entity picking (places a small 2x2x2 BB at the nearest sphere surface point toward the player), and allows melee targeting from both inside and outside the dome. Co-Authored-By: Claude Opus 4.6 --- .../kamkeel/npcs/entity/EntityEnergyDome.java | 151 ++++++++++++++++-- 1 file changed, 138 insertions(+), 13 deletions(-) diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index e4fb4a158..3d4fabe44 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -11,9 +11,11 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.CustomNpcs; +import java.util.HashSet; import java.util.List; /** @@ -29,6 +31,10 @@ public class EntityEnergyDome extends EntityEnergyBarrier { protected float targetDomeRadius = 5.0f; protected boolean followCaster = false; + // Server-side melee detection state + private boolean inTickMelee = false; + private final HashSet processedMeleeSwings = new HashSet<>(); + public EntityEnergyDome(World world) { super(world); this.noClip = true; @@ -96,12 +102,25 @@ public class EntityEnergyDome extends EntityEnergyBarrier { if (updateBarrierTick()) return; + // Server-side: detect and apply melee hits from nearby players. + // Bypasses MC's processUseEntity reach check (which uses center-to-center + // distance and fails for domes with radius > 5). + if (!worldObj.isRemote && barrierData.meleeEnabled) { + processMeleeHits(); + } + // Process entity physics every tick // Server: solid + knockback for all entities // Client: solid prediction for local player only (smooth movement blocking) if (barrierData.solid || barrierData.knockbackEnabled) { processEntityPhysics(); } + + // Client-side: adjust BB for accurate melee targeting at all approach angles. + // Must run AFTER all position/BB updates and BEFORE getMouseOver() in the render phase. + if (worldObj.isRemote && barrierData.meleeEnabled && !isCharging()) { + adjustMeleeBoundingBox(); + } } // ==================== INCOMING CHECK ==================== @@ -349,29 +368,74 @@ public class EntityEnergyDome extends EntityEnergyBarrier { // ==================== MELEE (spherical check) ==================== /** - * On the client side, the dome's large bounding box intercepts all raycasts from inside, - * preventing the player from targeting mobs within the dome. To fix this, return false - * when the local player is inside the dome so the raycast passes through to other entities. - * Players outside the dome can still target it for melee normally. + * Controls whether MC's entity picking (crosshair raycast) can target this dome. + * Returns false when melee is disabled or the dome is still charging. + *

+ * Inside players CAN target the dome because adjustMeleeBoundingBox places a small BB + * at the nearest surface point, allowing mobs in other directions to still be targeted. */ @Override public boolean canBeCollidedWith() { if (!barrierData.meleeEnabled) return false; - if (worldObj.isRemote) { - EntityPlayer player = CustomNpcs.proxy.getPlayer(); - if (player != null && isEntityInside(player)) { - return false; - } - } + if (isCharging()) return false; return true; } /** - * Reject melee hits that land on the cubic bounding box but are outside the actual sphere. - * Uses distance from the sphere surface (not center) for accurate spherical rejection. + * Client-side: Repositions the bounding box to a small cube at the nearest sphere surface + * point toward the player. This fixes melee targeting at diagonal approach angles where the + * player would otherwise be inside the dome-sized cubic BB but outside the actual sphere, + * causing MC's AABB raycast to return the far exit point (beyond reach distance). + *

+ * With a small BB (2x2x2) at the surface point, even if the player is inside it at close + * range, the exit point is at most ~1.7 blocks away — well within melee reach. + */ + private void adjustMeleeBoundingBox() { + EntityPlayer player = CustomNpcs.proxy.getPlayer(); + if (player == null) { + updateBoundingBox(); + return; + } + + double dx = player.posX - posX; + double dy = (player.posY + player.getEyeHeight()) - posY; + double dz = player.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + // Only adjust when player is within reasonable melee range of dome surface + if (dist < 0.01 || dist > domeRadius + 6.0) { + updateBoundingBox(); + return; + } + + // Nearest point on sphere surface toward player + double nx = dx / dist; + double ny = dy / dist; + double nz = dz / dist; + double surfX = posX + nx * domeRadius; + double surfY = posY + ny * domeRadius; + double surfZ = posZ + nz * domeRadius; + + float s = 1.0f; + this.boundingBox.setBounds( + surfX - s, surfY - s, surfZ - s, + surfX + s, surfY + s, surfZ + s + ); + } + + /** + * Player melee is handled by processMeleeHits (server-side tick detection) to bypass + * MC's processUseEntity reach check which uses center-to-center distance. + * Direct player melee ("player" damage type) is rejected unless inTickMelee is set, + * preventing double-hits when both the C02 path and tick detection fire. + * Non-player melee (mobs) and all other damage sources pass through with sphere validation. */ @Override public boolean attackEntityFrom(DamageSource source, float amount) { + // Player melee: only allow from tick-based detection + if (!inTickMelee && "player".equals(source.damageType)) { + return false; + } if (source.getEntity() != null) { Entity attacker = source.getEntity(); double dx = attacker.posX - this.posX; @@ -379,12 +443,73 @@ public class EntityEnergyDome extends EntityEnergyBarrier { double dz = attacker.posZ - this.posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); double surfaceDist = Math.abs(dist - domeRadius); - // Allow hit only if attacker is within melee reach of the sphere surface if (surfaceDist > 5.0) return false; } return super.attackEntityFrom(source, amount); } + /** + * Server-side melee detection. Each tick, finds players near the dome surface who are + * swinging and looking at the dome, then applies the attack via attackTargetEntityWithCurrentItem + * (preserving enchantments, crits, fire aspect, etc.). This bypasses MC's processUseEntity + * reach check which uses center-to-center distance and fails for large domes. + */ + @SuppressWarnings("unchecked") + private void processMeleeHits() { + float r = domeRadius; + float maxReach = 6.0f; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - r - maxReach, posY - r - maxReach, posZ - r - maxReach, + posX + r + maxReach, posY + r + maxReach, posZ + r + maxReach + ); + + List players = worldObj.getEntitiesWithinAABB(EntityPlayer.class, searchBox); + for (EntityPlayer player : players) { + if (player.getEntityId() == ownerEntityId) continue; + if (isAllyOfOwner(player)) continue; + + int playerId = player.getEntityId(); + + if (!player.isSwingInProgress) { + processedMeleeSwings.remove(playerId); + continue; + } + + if (processedMeleeSwings.contains(playerId)) continue; + + // Check surface distance + double dx = player.posX - posX; + double dy = (player.posY + 1.62) - posY; + double dz = player.posZ - posZ; + double distSq = dx * dx + dy * dy + dz * dz; + double dist = Math.sqrt(distSq); + double surfaceDist = Math.abs(dist - r); + if (surfaceDist > maxReach) continue; + + // Ray-sphere intersection: check if look direction hits the dome + Vec3 look = player.getLook(1.0f); + double b = 2.0 * (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord); + double c = distSq - (double)(r * r); + double discriminant = b * b - 4.0 * c; + if (discriminant < 0) continue; + + double sqrtDisc = Math.sqrt(discriminant); + double t1 = (-b - sqrtDisc) / 2.0; + double t2 = (-b + sqrtDisc) / 2.0; + + // Outside: t1 is entry distance. Inside: t1 < 0, t2 is exit distance. + double hitDist = t1 >= 0 ? t1 : t2; + if (hitDist < 0 || hitDist > maxReach) continue; + + // Apply the attack with full MC damage calculation + processedMeleeSwings.add(playerId); + inTickMelee = true; + player.attackTargetEntityWithCurrentItem(this); + inTickMelee = false; + } + } + // ==================== BOUNDING BOX ==================== /** From a18503dfe97698478a2aab66e2b76ad5b4106ad8 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 01:09:39 -0500 Subject: [PATCH 29/51] Fix Domes --- .../data/ability/data/EnergyBarrierData.java | 63 ++++++------------- .../data/ability/type/energy/AbilityDome.java | 9 --- .../type/energy/AbilityEnergyBarrier.java | 61 ++++++------------ .../npcs/entity/EntityEnergyBarrier.java | 52 ++++++--------- .../java/noppes/npcs/ServerEventsHandler.java | 8 +-- .../scripted/entity/ScriptEnergyBarrier.java | 16 +++-- .../assets/customnpcs/lang/en_US.lang | 15 ++--- 7 files changed, 80 insertions(+), 144 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java index 6f3610376..d54f205cc 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java @@ -8,10 +8,14 @@ import java.util.Map; /** * Groups barrier properties shared by energy barrier abilities (Dome, Wall, Shield). * Handles health/durability, duration, and per-projectile-type damage multipliers. + * + * Properties: + * - Solid: Hard wall — entities cannot pass through the barrier boundary (either direction) + * - Knockback: Repulsion field — entities near the surface get pushed away + * - Absorbing: Caster's incoming damage is redirected to the barrier + * - Allows Melee: Barrier can be hit by melee attacks (punching) */ public class EnergyBarrierData { - // Knockback target display keys - private static final String[] KNOCKBACK_TARGET_KEYS = {"gui.both", "gui.players", "gui.npcs"}; public float maxHealth = 100.0f; public boolean useHealth = true; @@ -19,23 +23,20 @@ public class EnergyBarrierData { public boolean useDuration = true; public float defaultMultiplier = 1.0f; - // Knockback settings + // Solid: entities cannot pass through the barrier boundary + public boolean solid = false; + + // Knockback: repulsion field pushing entities away from surface public boolean knockbackEnabled = false; public float knockbackStrength = 1.0f; - /** - * 0=Both, 1=Player only, 2=NPC only - */ - public int knockbackTarget = 0; - // Melee settings + // Absorbing: caster's damage is redirected to the barrier + public boolean absorbing = false; + + // Melee: barrier can be hit by melee attacks public boolean meleeEnabled = false; public float meleeDamageMultiplier = 1.0f; - // Jail settings (dome only - captures entities inside at spawn) - public boolean jailEnabled = false; - public boolean damageProtection = false; - public float jailThreshold = 0.9f; - /** * Per-projectile-type damage multipliers. * Key is the ability typeId (e.g., "ability.cnpc.orb", "ability.cnpc.beam"). @@ -118,24 +119,6 @@ public class EnergyBarrierData { this.defaultMultiplier = defaultMultiplier; } - // Knockback target key helpers - public static String[] getKnockbackTargetKeys() { - return KNOCKBACK_TARGET_KEYS; - } - - public String getKnockbackTargetKey() { - return KNOCKBACK_TARGET_KEYS[Math.max(0, Math.min(knockbackTarget, 2))]; - } - - public void setKnockbackTargetFromKey(String key) { - for (int i = 0; i < KNOCKBACK_TARGET_KEYS.length; i++) { - if (KNOCKBACK_TARGET_KEYS[i].equals(key)) { - knockbackTarget = i; - return; - } - } - } - // ==================== NBT ==================== public void writeNBT(NBTTagCompound nbt) { @@ -144,14 +127,12 @@ public class EnergyBarrierData { nbt.setInteger("barrierDuration", durationTicks); nbt.setBoolean("barrierUseDuration", useDuration); nbt.setFloat("barrierDefaultMult", defaultMultiplier); + nbt.setBoolean("barrierSolid", solid); nbt.setBoolean("barrierKnockback", knockbackEnabled); nbt.setFloat("barrierKnockbackStr", knockbackStrength); - nbt.setInteger("barrierKnockbackTarget", knockbackTarget); + nbt.setBoolean("barrierAbsorbing", absorbing); nbt.setBoolean("barrierMelee", meleeEnabled); nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier); - nbt.setBoolean("barrierJail", jailEnabled); - nbt.setBoolean("barrierDmgProtect", damageProtection); - nbt.setFloat("barrierJailThreshold", jailThreshold); NBTTagCompound multNbt = new NBTTagCompound(); for (Map.Entry entry : damageMultipliers.entrySet()) { @@ -166,14 +147,12 @@ public class EnergyBarrierData { durationTicks = nbt.hasKey("barrierDuration") ? nbt.getInteger("barrierDuration") : 200; useDuration = !nbt.hasKey("barrierUseDuration") || nbt.getBoolean("barrierUseDuration"); defaultMultiplier = nbt.hasKey("barrierDefaultMult") ? nbt.getFloat("barrierDefaultMult") : 1.0f; + solid = nbt.hasKey("barrierSolid") && nbt.getBoolean("barrierSolid"); knockbackEnabled = nbt.hasKey("barrierKnockback") && nbt.getBoolean("barrierKnockback"); knockbackStrength = nbt.hasKey("barrierKnockbackStr") ? nbt.getFloat("barrierKnockbackStr") : 1.0f; - knockbackTarget = nbt.hasKey("barrierKnockbackTarget") ? nbt.getInteger("barrierKnockbackTarget") : 0; + absorbing = nbt.hasKey("barrierAbsorbing") && nbt.getBoolean("barrierAbsorbing"); meleeEnabled = nbt.hasKey("barrierMelee") && nbt.getBoolean("barrierMelee"); meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f; - jailEnabled = nbt.hasKey("barrierJail") && nbt.getBoolean("barrierJail"); - damageProtection = nbt.hasKey("barrierDmgProtect") && nbt.getBoolean("barrierDmgProtect"); - jailThreshold = nbt.hasKey("barrierJailThreshold") ? nbt.getFloat("barrierJailThreshold") : 0.9f; damageMultipliers.clear(); if (nbt.hasKey("barrierMultipliers")) { @@ -189,14 +168,12 @@ public class EnergyBarrierData { public EnergyBarrierData copy() { EnergyBarrierData copy = new EnergyBarrierData(maxHealth, useHealth, durationTicks, useDuration); copy.defaultMultiplier = defaultMultiplier; + copy.solid = solid; copy.knockbackEnabled = knockbackEnabled; copy.knockbackStrength = knockbackStrength; - copy.knockbackTarget = knockbackTarget; + copy.absorbing = absorbing; copy.meleeEnabled = meleeEnabled; copy.meleeDamageMultiplier = meleeDamageMultiplier; - copy.jailEnabled = jailEnabled; - copy.damageProtection = damageProtection; - copy.jailThreshold = jailThreshold; copy.damageMultipliers = new HashMap<>(damageMultipliers); return copy; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java index cdb8f6f2f..78a317cc2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -135,14 +135,5 @@ public class AbilityDome extends AbilityEnergyBarrier { .range(1.0f, 50.0f)); defs.add(FieldDef.boolField("ability.followCaster", this::isFollowCaster, this::setFollowCaster) .hover("ability.hover.followCaster")); - - // Jail & protection section (dome-only: only enclosures can jail) - defs.add(FieldDef.section("ability.section.jail")); - defs.add(FieldDef.boolField("ability.jailEnabled", this::isJailEnabled, this::setJailEnabled) - .hover("ability.hover.jailEnabled")); - defs.add(FieldDef.floatField("ability.jailThreshold", this::getJailThreshold, this::setJailThreshold) - .range(0.1f, 1.0f).visibleWhen(this::isJailEnabled)); - defs.add(FieldDef.boolField("ability.damageProtection", this::isDamageProtection, this::setDamageProtection) - .hover("ability.hover.damageProtection")); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java index d3b543885..73f34d059 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java @@ -190,6 +190,15 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { return barrierData.getMultiplier(typeId); } + // Solid data + public boolean isSolid() { + return barrierData.solid; + } + + public void setSolid(boolean solid) { + barrierData.solid = solid; + } + // Knockback data public boolean isKnockbackEnabled() { return barrierData.knockbackEnabled; @@ -207,12 +216,13 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { barrierData.knockbackStrength = strength; } - public String getKnockbackTargetKey() { - return barrierData.getKnockbackTargetKey(); + // Absorbing data + public boolean isAbsorbing() { + return barrierData.absorbing; } - public void setKnockbackTargetKey(String key) { - barrierData.setKnockbackTargetFromKey(key); + public void setAbsorbing(boolean absorbing) { + barrierData.absorbing = absorbing; } // Melee data @@ -232,31 +242,6 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { barrierData.meleeDamageMultiplier = mult; } - // Jail data - public boolean isJailEnabled() { - return barrierData.jailEnabled; - } - - public void setJailEnabled(boolean enabled) { - barrierData.jailEnabled = enabled; - } - - public boolean isDamageProtection() { - return barrierData.damageProtection; - } - - public void setDamageProtection(boolean enabled) { - barrierData.damageProtection = enabled; - } - - public float getJailThreshold() { - return barrierData.jailThreshold; - } - - public void setJailThreshold(float threshold) { - barrierData.jailThreshold = Math.max(0.1f, Math.min(1.0f, threshold)); - } - // ==================== GUI ==================== @SideOnly(Side.CLIENT) @@ -275,19 +260,13 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { .range(1, 12000).visibleWhen(this::isUseDuration)); defs.add(FieldDef.floatField("ability.defaultMultiplier", this::getDefaultMultiplier, this::setDefaultMultiplier)); - // Knockback section - defs.add(FieldDef.section("ability.section.knockback")); + // Properties section + defs.add(FieldDef.section("ability.section.properties")); + defs.add(FieldDef.boolField("ability.solid", this::isSolid, this::setSolid)); defs.add(FieldDef.boolField("ability.knockbackEnabled", this::isKnockbackEnabled, this::setKnockbackEnabled)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.knockbackStrength", this::getKnockbackStrength, this::setKnockbackStrength) - .range(0, 10).visibleWhen(this::isKnockbackEnabled), - FieldDef.stringEnumField("ability.knockbackTarget", EnergyBarrierData.getKnockbackTargetKeys(), - this::getKnockbackTargetKey, this::setKnockbackTargetKey) - .visibleWhen(this::isKnockbackEnabled) - )); - - // Melee section - defs.add(FieldDef.section("ability.section.melee")); + defs.add(FieldDef.floatField("ability.knockbackStrength", this::getKnockbackStrength, this::setKnockbackStrength) + .range(0, 10).visibleWhen(this::isKnockbackEnabled)); + defs.add(FieldDef.boolField("ability.absorbing", this::isAbsorbing, this::setAbsorbing)); defs.add(FieldDef.boolField("ability.meleeEnabled", this::isMeleeEnabled, this::setMeleeEnabled)); defs.add(FieldDef.floatField("ability.meleeDamageMultiplier", this::getMeleeDamageMultiplier, this::setMeleeDamageMultiplier) .range(0, 10).visibleWhen(this::isMeleeEnabled)); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java index 1027fe93e..2db51fd14 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -4,7 +4,6 @@ import kamkeel.npcs.controllers.data.ability.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; @@ -94,9 +93,10 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { public abstract void finishCharging(); /** - * Push entities away from the barrier surface. + * Process entity physics for this barrier. + * Handles solid wall (entity repositioning) and knockback (repulsion force). */ - protected abstract void knockbackEntities(); + protected abstract void processEntityPhysics(); /** * Get the maximum extent of this barrier for distance pre-filtering. @@ -203,6 +203,16 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return barrierData.meleeEnabled; } + @Override + public boolean isEntityInsideOpaqueBlock() { + return false; + } + + @Override + protected boolean func_145771_j(double x, double y, double z) { + return false; + } + @Override public boolean attackEntityFrom(DamageSource source, float amount) { if (worldObj.isRemote || !barrierData.meleeEnabled) return false; @@ -324,20 +334,9 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return this.dataWatcher.getWatchableObjectFloat(DW_HEALTH_PERCENT); } - protected boolean isKnockbackTarget(EntityLivingBase entity) { - switch (barrierData.knockbackTarget) { - case 1: - return entity instanceof EntityPlayer; - case 2: - return entity instanceof EntityNPCInterface; - default: - return entity instanceof EntityPlayer || entity instanceof EntityNPCInterface; - } - } - /** * Check if an entity is an ally of this barrier's owner. - * Allies should not be knocked back by barriers. + * Allies are not affected by barrier physics. */ protected boolean isAllyOfOwner(EntityLivingBase entity) { Entity owner = getOwnerEntity(); @@ -345,7 +344,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return AbilityTargetHelper.isAlly((EntityLivingBase) owner, entity); } - // ==================== CONTAINMENT & PROTECTION ==================== + // ==================== CONTAINMENT & ABSORBING ==================== /** * Check if an entity is geometrically inside this barrier's protected zone. @@ -356,27 +355,16 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { } /** - * Check if a damage source originates from outside this barrier. - * Uses geometry-specific containment check via isEntityInside(). + * Find a barrier that would absorb damage for the given entity (its caster). + * Returns the barrier if: absorbing is enabled AND entity is the barrier's owner. */ - public boolean isDamageFromOutside(DamageSource source) { - Entity attacker = source.getEntity(); - if (attacker == null) return true; // Environmental damage treated as outside - return !isEntityInside(attacker); - } - - /** - * Find a barrier that would protect the given entity from outside damage. - * Returns the barrier if: damageProtection is enabled AND entity is inside. - * Any entity inside a dome with damageProtection gets redirected damage. - */ - public static EntityEnergyBarrier getProtectingBarrier(Entity entity) { + public static EntityEnergyBarrier getAbsorbingBarrier(Entity entity) { if (entity == null || entity.worldObj == null) return null; List barriers = getActiveBarriers(entity.worldObj); for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead) continue; - if (!barrier.barrierData.damageProtection) continue; - if (barrier.isEntityInside(entity)) { + if (!barrier.barrierData.absorbing) continue; + if (barrier.ownerEntityId == entity.getEntityId()) { return barrier; } } diff --git a/src/main/java/noppes/npcs/ServerEventsHandler.java b/src/main/java/noppes/npcs/ServerEventsHandler.java index fb2ea3d13..a13384ada 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -153,13 +153,13 @@ public class ServerEventsHandler { } @SubscribeEvent - public void barrierDamageProtection(LivingAttackEvent event) { + public void barrierAbsorbDamage(LivingAttackEvent event) { if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote) return; - EntityEnergyBarrier barrier = EntityEnergyBarrier.getProtectingBarrier(event.entityLiving); - if (barrier != null && barrier.isDamageFromOutside(event.source)) { - // Redirect the damage to the barrier instead of preventing it + EntityEnergyBarrier barrier = EntityEnergyBarrier.getAbsorbingBarrier(event.entityLiving); + if (barrier != null) { + // Redirect the caster's damage to their barrier barrier.absorbDamage(event.ammount); event.setCanceled(true); } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java index 29f330ff7..6669bde50 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java @@ -89,6 +89,14 @@ public class ScriptEnergyBarrier extends ScriptEn entity.getBarrierData().defaultMultiplier = multiplier; } + public boolean isSolid() { + return entity.getBarrierData().solid; + } + + public void setSolid(boolean solid) { + entity.getBarrierData().solid = solid; + } + public boolean isKnockbackEnabled() { return entity.getBarrierData().knockbackEnabled; } @@ -105,12 +113,12 @@ public class ScriptEnergyBarrier extends ScriptEn entity.getBarrierData().knockbackStrength = strength; } - public int getKnockbackTarget() { - return entity.getBarrierData().knockbackTarget; + public boolean isAbsorbing() { + return entity.getBarrierData().absorbing; } - public void setKnockbackTarget(int target) { - entity.getBarrierData().knockbackTarget = target; + public void setAbsorbing(boolean absorbing) { + entity.getBarrierData().absorbing = absorbing; } public int getBarrierType() { diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index c6d745706..c0ae3f376 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2019,7 +2019,7 @@ ability.cnpc.shield=Shield ability.cnpc.slicer=Slicer ability.section.barrier=Barrier -ability.section.knockback=Knockback +ability.section.properties=Properties ability.section.panel=Panel ability.section.launch=Launch ability.section.slicer=Slicer @@ -2032,23 +2032,16 @@ ability.defaultMultiplier=Default Multiplier ability.innerAlpha=Inner Alpha ability.heightOffset=Height Offset +ability.solid=Solid ability.knockbackEnabled=Knockback ability.knockbackStrength=Knockback Strength -ability.knockbackTarget=Target - -ability.section.melee=Melee -ability.meleeEnabled=Melee Attackable +ability.absorbing=Absorbing +ability.meleeEnabled=Allows Melee ability.meleeDamageMultiplier=Melee Multiplier ability.followCaster=Follow Caster ability.hover.followCaster=Dome stays centered on the caster as they move -ability.section.jail=Jail & Protection -ability.jailEnabled=Jail Mode -ability.hover.jailEnabled=Entities inside stay inside, entities outside stay outside -ability.jailThreshold=Jail Threshold -ability.damageProtection=Damage Protection -ability.hover.damageProtection=Outside attacks on entities inside are redirected to the dome ability.variant.small=Small ability.variant.large=Large From 94c4e76823cfecf8df195bab8b8361cc9fcf0c88 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 01:09:47 -0500 Subject: [PATCH 30/51] Update api --- src/api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api b/src/api index 72718c360..96799f68e 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 72718c36016c526b00681ea2ba8c506030aca555 +Subproject commit 96799f68ecc1f529ab287b426052048695332e87 From 8648e019a95ac36658c6014227ffcba5500a1fd2 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 21 Feb 2026 03:24:27 -0300 Subject: [PATCH 31/51] Changed some logic on conditions for automatically checking all filters --- .../ability/conditions/AbilityCondition.java | 22 ++++++++++------ .../conditions/ConditionHPThreshold.java | 25 +++---------------- .../ability/conditions/ConditionItem.java | 15 +---------- 3 files changed, 19 insertions(+), 43 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java index 6fc7b8a12..6f5299ca4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -21,14 +21,20 @@ public abstract class AbilityCondition { protected UserType userType = UserType.BOTH; protected ConditionFilter conditionFilter = ConditionFilter.CASTER; - /** - * Check if this condition is met. - * - * @param caster The entity that would use the ability (NPC or Player) - * @param target The current target (may be null for self-targeting abilities or players) - * @return true if the condition is satisfied - */ - public abstract boolean check(EntityLivingBase caster, EntityLivingBase target); + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + switch (getFilter()) { + case CASTER: + return checkEntity(caster); + case TARGET: + return target != null && checkEntity(target); + case BOTH: + return checkEntity(caster) && (target != null && checkEntity(target)); + default: + return checkEntity(caster); + } + } + + protected abstract boolean checkEntity(EntityLivingBase entity); public boolean requiresTarget() { return false; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java index 5eed753fa..fe77de17d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -6,7 +6,7 @@ import noppes.npcs.client.gui.builder.FieldDef; import java.util.List; -public class ConditionHPThreshold extends AbilityCondition{ +public class ConditionHPThreshold extends AbilityCondition { private float threshold = 0.5f; // 50% private boolean percent = true; private ThresholdType thresholdType = ThresholdType.ABOVE; @@ -62,26 +62,9 @@ public class ConditionHPThreshold extends AbilityCondition{ } @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - float casterHP = isPercent() ? caster.getHealth() / caster.getMaxHealth() : caster.getHealth(); - float targetHP = isPercent() ? target.getHealth() / target.getMaxHealth() : target.getHealth(); - - - return compare(casterHP, targetHP); - } - - public boolean compare(float casterHp, float targetHp) { - boolean casterCheck = thresholdType.test(casterHp, threshold); - boolean targetCheck = thresholdType.test(targetHp, threshold); - - switch (getFilter()) { - case BOTH: - return casterCheck && targetCheck; - case CASTER: - return casterCheck; - default: - return targetCheck; - } + protected boolean checkEntity(EntityLivingBase entity) { + float entityHP = isPercent() ? entity.getHealth() / entity.getMaxHealth() : entity.getHealth(); + return thresholdType.test(entityHP, getThreshold()); } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java index 14b751d29..d8deece10 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -46,20 +46,7 @@ public class ConditionItem extends AbilityCondition { } @Override - public boolean check(EntityLivingBase caster, EntityLivingBase target) { - switch (getFilter()) { - case CASTER: - return checkEntity(caster); - case TARGET: - return target != null && checkEntity(target); - case BOTH: - return checkEntity(caster) && (target != null && checkEntity(target)); - default: - return checkEntity(caster); - } - } - - private boolean checkEntity(EntityLivingBase entity) { + protected boolean checkEntity(EntityLivingBase entity) { switch (usageType) { case HOLDING: return checkHolding(entity); From 606bc093df39ca544490efd5fab84604594331c9 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 02:36:41 -0500 Subject: [PATCH 32/51] Condition Registry [1/2] --- .../npcs/controllers/AbilityController.java | 22 ++ .../ability/conditions/ConditionHitCount.java | 6 + src/main/java/kamkeel/npcs/util/Register.java | 33 +++ .../gui/advanced/SubGuiConditionEdit.java | 219 ++++++++++++++---- 4 files changed, 232 insertions(+), 48 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 1da844451..a2a4d8b33 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -903,6 +903,28 @@ public class AbilityController implements IAbilityHandler { return conditionTypes.keySet().toArray(new String[0]); } + public List getConditionNamespaces() { + LinkedHashSet seen = new LinkedHashSet<>(); + for (String typeId : conditionTypes.keySet()) { + String[] parts = typeId.split("\\.", 3); + if (parts.length >= 2) { + seen.add(parts[1]); + } + } + return new ArrayList<>(seen); + } + + public String[] getConditionTypesByNamespace(String namespace) { + String prefix = "condition." + namespace + "."; + List result = new ArrayList<>(); + for (String typeId : conditionTypes.keySet()) { + if (typeId.startsWith(prefix)) { + result.add(typeId); + } + } + return result.toArray(new String[0]); + } + public void registerFlightChecker(Predicate checker) { flightCheckers.add(checker); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java index 22465b593..1c8dfaabf 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -18,6 +18,12 @@ public class ConditionHitCount extends AbilityCondition { this.userType = UserType.NPC_ONLY; } + @Override + protected boolean checkEntity(EntityLivingBase entity) { + // Not used — this condition overrides check() directly + return false; + } + @Override public boolean check(EntityLivingBase caster, EntityLivingBase target) { if (caster instanceof EntityNPCInterface) { diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index eab517ce9..75184778d 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -4,6 +4,7 @@ import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.IEffectAction; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import noppes.npcs.LogWriter; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; @@ -207,4 +208,36 @@ public class Register { return new Register.EffectActions(namespace); } } + + public static class Conditions extends Register { + + private Conditions(String namespace) { + super("condition", namespace); + } + + public AbilityCondition register(String name, Supplier factory) { + entries.put(registryKey + "." + namespace + "." + name, factory); + return factory.get(); + } + + public void register() { + for (Map.Entry> entry : entries.entrySet()) { + AbilityController.Instance.registerCondition(entry.getValue()); + } + } + + public static Register.Conditions create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("condition")) + REGISTERED_NAMESPACES.put("condition", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("condition").contains(namespace)) { + LogWriter.error("REGISTER CONDITIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("condition").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.Conditions(namespace); + } + } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java index d90f0b6d6..bca83c150 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java @@ -2,12 +2,15 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.resources.I18n; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.util.*; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; @@ -15,59 +18,138 @@ import java.util.function.Supplier; /** * SubGui for editing a single AbilityCondition. * - * Type selection stays manual (we need to swap the condition object). - * Field rendering is fully delegated to AbilityCondition#getAbilityDefinitions(), - * mirroring the pattern used in SubGuiAbilityConfig. + * Split-panel layout: + * Left – Mod namespace filter + scrollable condition type list + * Right – FieldDef configuration for the selected condition */ -public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { +public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, ICustomScrollListener { private static final int DECLARATIVE_ID_START = 1000; private static final int CLEAR_ID_START = 2000; private static final int LABEL_ID_START = 3000; - private static final int BTN_TYPE = 1; + private static final int BTN_NAMESPACE = 1; private static final int BTN_CANCEL = 10; private static final int BTN_DONE = 11; + // Left panel + private static final int LEFT_WIDTH = 110; + private static final int LEFT_MARGIN = 5; + + // Right panel + private static final int RIGHT_GAP = 5; + private AbilityCondition condition; private AbilityCondition result; + private String selectedTypeId; - private final String[] conditionTypeIds; - private final String[] conditionTypeNames; - private int selectedTypeIndex = 0; + // Namespace filter + private int namespaceFilter = 0; // 0 = ALL, 1 = cnpc, 2+ = modded namespaces + private List modNamespaces; + + // Type list + private GuiCustomScroll scroll; + private final HashMap displayNameToTypeId = new HashMap<>(); + private String[] filteredTypeIds; private AbilityFieldBuilder builder; public SubGuiConditionEdit(AbilityCondition existing) { this.result = null; - - conditionTypeIds = AbilityController.Instance.getConditionTypes(); - conditionTypeNames = new String[conditionTypeIds.length]; - for (int i = 0; i < conditionTypeIds.length; i++) { - Supplier factory = AbilityController.Instance.getConditionType(conditionTypeIds[i]); - conditionTypeNames[i] = factory != null ? factory.get().getName() : conditionTypeIds[i]; - } + this.modNamespaces = getModNamespaces(); if (existing != null) { - for (int i = 0; i < conditionTypeIds.length; i++) { - if (conditionTypeIds[i].equals(existing.getTypeId())) { - selectedTypeIndex = i; - break; - } - } this.condition = existing; + this.selectedTypeId = existing.getTypeId(); + // Set namespace filter to match existing condition + setNamespaceForTypeId(selectedTypeId); } else { - this.condition = spawnCondition(selectedTypeIndex); + // Default to first available condition + String[] allTypes = AbilityController.Instance.getConditionTypes(); + if (allTypes.length > 0) { + this.selectedTypeId = allTypes[0]; + this.condition = spawnCondition(selectedTypeId); + } } - setBackground("menubg.png"); - xSize = 240; - ySize = 180; + setBackground("menubg.png", 217); + xSize = 356; + ySize = 200; } - private AbilityCondition spawnCondition(int typeIndex) { - if (typeIndex < 0 || typeIndex >= conditionTypeIds.length) return null; - Supplier factory = AbilityController.Instance.getConditionType(conditionTypeIds[typeIndex]); + private List getModNamespaces() { + List result = new ArrayList<>(); + List registered = Register.REGISTERED_NAMESPACES.get("condition"); + if (registered != null) { + result.addAll(registered); + } + return result; + } + + private void setNamespaceForTypeId(String typeId) { + if (typeId == null) return; + String[] parts = typeId.split("\\.", 3); + if (parts.length < 2) return; + String ns = parts[1]; + + if ("cnpc".equals(ns)) { + namespaceFilter = 1; + } else { + for (int i = 0; i < modNamespaces.size(); i++) { + if (modNamespaces.get(i).equals(ns)) { + namespaceFilter = 2 + i; + return; + } + } + namespaceFilter = 0; // Fallback to ALL + } + } + + private String getNamespaceFilterLabel() { + if (namespaceFilter == 0) return "ALL"; + if (namespaceFilter == 1) return "CNPC"; + int modIdx = namespaceFilter - 2; + if (modIdx >= 0 && modIdx < modNamespaces.size()) { + String ns = modNamespaces.get(modIdx); + String display = Register.NAMESPACE_DISPLAY_NAMES.get(ns); + return display != null ? display : ns.toUpperCase(); + } + return "ALL"; + } + + private void cycleNamespaceFilter() { + namespaceFilter++; + // 0=ALL, 1=CNPC, 2..2+N-1=mod namespaces, then wrap + int max = 2 + modNamespaces.size(); + if (namespaceFilter >= max) { + namespaceFilter = 0; + } + // Skip empty mod namespace slots + if (namespaceFilter >= 2) { + int modIdx = namespaceFilter - 2; + if (modIdx >= modNamespaces.size()) { + namespaceFilter = 0; + } + } + } + + private String[] getFilteredTypes() { + if (namespaceFilter == 0) { + return AbilityController.Instance.getConditionTypes(); + } else if (namespaceFilter == 1) { + return AbilityController.Instance.getConditionTypesByNamespace("cnpc"); + } else { + int modIdx = namespaceFilter - 2; + if (modIdx >= 0 && modIdx < modNamespaces.size()) { + return AbilityController.Instance.getConditionTypesByNamespace(modNamespaces.get(modIdx)); + } + return AbilityController.Instance.getConditionTypes(); + } + } + + private AbilityCondition spawnCondition(String typeId) { + if (typeId == null) return null; + Supplier factory = AbilityController.Instance.getConditionType(typeId); return factory != null ? factory.get() : null; } @@ -76,18 +158,45 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi GuiNpcTextField.unfocus(); super.initGui(); - int swX = guiLeft + 4; - int swY = guiTop + 5; - int swW = xSize - 8; - int swH = ySize - 35; + int y = guiTop + 5; - int labelY = guiTop + 8; - addLabel(new GuiNpcLabel(0, "gui.type", guiLeft + 8, labelY + 5)); - GuiNpcButton typeBtn = new GuiNpcButton(BTN_TYPE, guiLeft + 80, labelY, 155, 20, conditionTypeNames, selectedTypeIndex); - addButton(typeBtn); + // Namespace filter button (full width at top) + addButton(new GuiNpcButton(BTN_NAMESPACE, guiLeft + LEFT_MARGIN, y, xSize - LEFT_MARGIN * 2, 20, getNamespaceFilterLabel())); + y += 24; - swY += 26; - swH -= 26; + // Build filtered type list + filteredTypeIds = getFilteredTypes(); + displayNameToTypeId.clear(); + List scrollList = new ArrayList<>(); + for (String typeId : filteredTypeIds) { + Supplier factory = AbilityController.Instance.getConditionType(typeId); + String displayName = factory != null ? I18n.format(factory.get().getName()) : typeId; + scrollList.add(displayName); + displayNameToTypeId.put(displayName, typeId); + } + + // Left panel: condition type scroll list + int scrollHeight = ySize - 58; + scroll = new GuiCustomScroll(this, 0); + scroll.guiLeft = guiLeft + LEFT_MARGIN; + scroll.guiTop = y; + scroll.setSize(LEFT_WIDTH, scrollHeight); + scroll.setUnsortedList(scrollList); + + // Pre-select current condition type in scroll + if (selectedTypeId != null) { + for (int i = 0; i < filteredTypeIds.length; i++) { + if (filteredTypeIds[i].equals(selectedTypeId)) { + scroll.selected = i; + break; + } + } + } + addScroll(scroll); + + // Right panel: condition config via FieldDef + int rightX = guiLeft + LEFT_MARGIN + LEFT_WIDTH + RIGHT_GAP; + int rightW = xSize - LEFT_MARGIN * 2 - LEFT_WIDTH - RIGHT_GAP; List fields = new ArrayList<>(); if (condition != null) { @@ -97,24 +206,20 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi builder = new AbilityFieldBuilder(this, fontRendererObj); builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); builder.startY(5); + builder.buildScrollWindow(fields, rightX, y, rightW, scrollHeight); - builder.buildScrollWindow(fields, swX, swY, swW, swH); - + // Bottom buttons int btnY = guiTop + ySize - 26; - addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + 8, btnY, 60, 20, "gui.cancel")); - addButton(new GuiNpcButton(BTN_DONE, guiLeft + xSize - 68, btnY, 60, 20, "gui.done")); + addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + LEFT_MARGIN, btnY, 60, 20, "gui.cancel")); + addButton(new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done")); } @Override public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - if (id == BTN_TYPE) { - int newIndex = ((GuiNpcButton) guibutton).getValue(); - if (newIndex != selectedTypeIndex) { - selectedTypeIndex = newIndex; - condition = spawnCondition(selectedTypeIndex); - } + if (id == BTN_NAMESPACE) { + cycleNamespaceFilter(); initGui(); return; } @@ -138,6 +243,24 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi } } + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && scroll.hasSelected()) { + String displayName = scroll.getSelected(); + String typeId = displayNameToTypeId.get(displayName); + if (typeId != null && !typeId.equals(selectedTypeId)) { + selectedTypeId = typeId; + condition = spawnCondition(selectedTypeId); + initGui(); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + // Same as single click — user still needs to configure fields + } + @Override public void unFocused(GuiNpcTextField textField) { if (textField.id < DECLARATIVE_ID_START) return; From 75a58f7e74b4b44d793fb51059d39d631b43bc47 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:03:42 -0500 Subject: [PATCH 33/51] Condition Registry [2/2] --- .../npcs/controllers/AbilityController.java | 2 + .../ability/conditions/AbilityCondition.java | 18 ++ .../conditions/ConditionHPThreshold.java | 99 +--------- .../ability/conditions/ConditionHitCount.java | 9 +- .../ability/conditions/ConditionItem.java | 14 ++ .../conditions/ConditionQuestCompleted.java | 86 +++++++++ .../conditions/ConditionThreshold.java | 171 ++++++++++++++++++ .../gui/advanced/SubGuiAbilityConfig.java | 4 +- .../gui/advanced/SubGuiConditionEdit.java | 62 +++++-- .../client/gui/builder/GuiFieldBuilder.java | 3 + .../assets/customnpcs/lang/en_US.lang | 11 ++ 11 files changed, 367 insertions(+), 112 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index a2a4d8b33..b29bbb668 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -5,6 +5,7 @@ import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold; import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount; import kamkeel.npcs.controllers.data.ability.conditions.ConditionItem; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; @@ -154,6 +155,7 @@ public class AbilityController implements IAbilityHandler { registerCondition(ConditionHPThreshold::new); registerCondition(ConditionHitCount::new); registerCondition(ConditionItem::new); + registerCondition(ConditionQuestCompleted::new); } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java index 6f5299ca4..479776930 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -6,6 +6,7 @@ import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.UserType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; import noppes.npcs.LogWriter; import noppes.npcs.client.gui.builder.FieldDef; @@ -40,6 +41,14 @@ public abstract class AbilityCondition { return false; } + /** + * Returns true if all required fields are filled in. + * Used to disable the Done button in SubGuiConditionEdit when incomplete. + */ + public boolean isConfigured() { + return true; + } + public UserType getUserType() { return userType; } @@ -63,10 +72,19 @@ public abstract class AbilityCondition { @SideOnly(Side.CLIENT) public abstract void getConditionDefinitions(List defs); + /** + * Returns a human-readable summary of this condition's configuration. + * Used for tooltips when hovering over condition buttons. + */ + @SideOnly(Side.CLIENT) + public abstract String getConditionSummary(); + @SideOnly(Side.CLIENT) public final List getAllDefinitions() { List defs = new ArrayList<>(); + defs.add(FieldDef.labelField("ability.validFor", () -> + "\u00A7e" + StatCollector.translateToLocal("ability.userType." + getUserType().name()))); defs.add(FieldDef.enumField("condition.filter", ConditionFilter.class, this::getFilter, this::setFilter)); getConditionDefinitions(defs); return defs; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java index fe77de17d..dfb997526 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -1,60 +1,8 @@ package kamkeel.npcs.controllers.data.ability.conditions; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import noppes.npcs.client.gui.builder.FieldDef; -import java.util.List; - -public class ConditionHPThreshold extends AbilityCondition { - private float threshold = 0.5f; // 50% - private boolean percent = true; - private ThresholdType thresholdType = ThresholdType.ABOVE; - - public enum ThresholdType { - ABOVE { - @Override - public boolean test(float value, float threshold) { - return value > threshold; - } - }, - BELOW { - @Override - public boolean test(float value, float threshold) { - return value < threshold; - } - }, - EQUAL { - @Override - public boolean test(float value, float threshold) { - return value == threshold; - } - }; - - public abstract boolean test(float value, float threshold); - - public static ThresholdType fromOrdinal(int ordinal) { - ThresholdType[] values = values(); - if (ordinal >= 0 && ordinal < values.length) { - return values[ordinal]; - } - return ABOVE; - } - - @Override - public String toString() { - switch (this) { - case ABOVE: - return "condition.hp_above"; - case BELOW: - return "condition.hp_below"; - case EQUAL: - return "condition.hp_equal"; - default: - return name(); - } - } - } +public class ConditionHPThreshold extends ConditionThreshold { public ConditionHPThreshold() { this.typeId = "condition.cnpc.hp_threshold"; @@ -62,50 +10,17 @@ public class ConditionHPThreshold extends AbilityCondition { } @Override - protected boolean checkEntity(EntityLivingBase entity) { - float entityHP = isPercent() ? entity.getHealth() / entity.getMaxHealth() : entity.getHealth(); - return thresholdType.test(entityHP, getThreshold()); + protected float getEntityValue(EntityLivingBase entity) { + return entity.getHealth(); } @Override - public void getConditionDefinitions(List defs) { - defs.add(FieldDef.floatField("condition.threshold", this::getThreshold, this::setThreshold).min(0)); - defs.add(FieldDef.boolField("condition.percent", this::isPercent, this::setIsPercent)); - defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, - this::getThresholdType, this::setThresholdType)); + protected float getEntityMaxValue(EntityLivingBase entity) { + return entity.getMaxHealth(); } @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("threshold", threshold); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - threshold = nbt.getFloat("threshold"); - } - - public float getThreshold() { - return threshold; - } - - public void setThreshold(float threshold) { - this.threshold = Math.max(0, threshold); - } - - public ThresholdType getThresholdType() { - return thresholdType; - } - - public void setThresholdType(ThresholdType thresholdType) { - this.thresholdType = thresholdType; - } - - public boolean isPercent() { - return percent; - } - - public void setIsPercent(boolean percent) { - this.percent = percent; + protected String getStatName() { + return "HP"; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java index 1c8dfaabf..dbd71922b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -1,8 +1,8 @@ package kamkeel.npcs.controllers.data.ability.conditions; -import kamkeel.npcs.controllers.data.ability.UserType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.entity.EntityNPCInterface; @@ -15,7 +15,6 @@ public class ConditionHitCount extends AbilityCondition { public ConditionHitCount() { this.typeId = "condition.cnpc.hit_count"; this.name = "condition.hit_count"; - this.userType = UserType.NPC_ONLY; } @Override @@ -59,6 +58,12 @@ public class ConditionHitCount extends AbilityCondition { defs.add(FieldDef.intField("condition.within_ticks", this::getWithinTicks, this::setWithinTicks).min(0)); } + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + return "[" + filterLabel + "] Hit " + requiredHits + " times in " + withinTicks + " ticks"; + } + @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setInteger("requiredHits", requiredHits); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java index d8deece10..9bb445043 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -4,6 +4,7 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.entity.EntityNPCInterface; @@ -149,6 +150,14 @@ public class ConditionItem extends AbilityCondition { // .hover("condition.hover.required_count")); } + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String usage = usageType.name(); + String item = itemName.isEmpty() ? "None" : itemName; + return "[" + filterLabel + "] " + usage + ": " + item; + } + @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setString("itemName", itemName); @@ -166,6 +175,11 @@ public class ConditionItem extends AbilityCondition { } + @Override + public boolean isConfigured() { + return itemName != null && !itemName.isEmpty(); + } + public UsageType getUsageType() { return usageType; } public void setUsageType(UsageType usageType) { this.usageType = usageType; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java new file mode 100644 index 000000000..04c1ec16a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.select.GuiQuestSelection; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.QuestController; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.Quest; + +import java.util.List; + +public class ConditionQuestCompleted extends AbilityCondition { + private int questId = -1; + + public ConditionQuestCompleted() { + this.typeId = "condition.cnpc.quest_completed"; + this.name = "condition.quest_completed"; + this.userType = UserType.PLAYER_ONLY; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + if (!(entity instanceof EntityPlayer)) return false; + if (questId < 0) return false; + + EntityPlayer player = (EntityPlayer) entity; + return PlayerData.get(player).questData.hasFinishedQuest(questId); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.subGuiField("condition.select_quest", + () -> new GuiQuestSelection(questId), + (SubGuiInterface gui) -> { + GuiQuestSelection sel = (GuiQuestSelection) gui; + if (sel.selectedQuest != null) { + questId = sel.selectedQuest.id; + } + }) + .buttonLabel(() -> { + if (questId < 0) return "None"; + Quest q = QuestController.Instance.quests.get(questId); + return q != null ? q.title : "ID:" + questId; + }) + .clearable(() -> questId = -1)); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String questName = "None"; + if (questId >= 0) { + Quest q = QuestController.Instance.quests.get(questId); + questName = q != null ? q.title : "ID:" + questId; + } + return "[" + filterLabel + "] Quest: " + questName; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("questId", questId); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + questId = nbt.getInteger("questId"); + } + + @Override + public boolean isConfigured() { + return questId >= 0; + } + + public int getQuestId() { + return questId; + } + + public void setQuestId(int questId) { + this.questId = questId; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java new file mode 100644 index 000000000..fda42ce6a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java @@ -0,0 +1,171 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for threshold-based conditions (HP, Ki, etc.). + * Provides shared percent/flat toggle, ThresholdType enum, and FieldDef generation. + */ +public abstract class ConditionThreshold extends AbilityCondition { + + public enum ThresholdType { + ABOVE { + @Override + public boolean test(float value, float threshold) { + return value >= threshold; + } + }, + BELOW { + @Override + public boolean test(float value, float threshold) { + return value <= threshold; + } + }, + EQUAL { + @Override + public boolean test(float value, float threshold) { + return value == threshold; + } + }; + + public abstract boolean test(float value, float threshold); + + public static ThresholdType fromOrdinal(int ordinal) { + ThresholdType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return ABOVE; + } + + @Override + public String toString() { + switch (this) { + case ABOVE: + return "condition.above"; + case BELOW: + return "condition.below"; + case EQUAL: + return "condition.equal"; + default: + return name(); + } + } + } + + protected float thresholdFlat = 100f; + protected float thresholdPercent = 0.5f; + protected boolean percent = true; + protected ThresholdType thresholdType = ThresholdType.ABOVE; + + /** + * Returns the raw stat value for the entity (e.g. current HP, current Ki). + */ + protected abstract float getEntityValue(EntityLivingBase entity); + + /** + * Returns the maximum stat value for the entity (e.g. max HP, max Ki). + * Used to compute the percentage ratio. + */ + protected abstract float getEntityMaxValue(EntityLivingBase entity); + + /** + * Returns the display name for the stat being checked (e.g. "HP", "Ki"). + * Used in getConditionSummary(). + */ + protected abstract String getStatName(); + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + float value; + float threshold; + if (percent) { + float max = getEntityMaxValue(entity); + value = max > 0 ? getEntityValue(entity) / max : 0; + threshold = thresholdPercent; + } else { + value = getEntityValue(entity); + threshold = thresholdFlat; + } + return thresholdType.test(value, threshold); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.floatField("condition.threshold_flat", this::getThresholdFlat, this::setThresholdFlat) + .min(0).visibleWhen(() -> !isPercent())); + defs.add(FieldDef.floatField("condition.threshold_percent", this::getThresholdPercent, this::setThresholdPercent) + .min(0).max(1).visibleWhen(this::isPercent)); + defs.add(FieldDef.boolField("condition.percent", this::isPercent, this::setIsPercent)); + defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, + this::getThresholdType, this::setThresholdType)); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("thresholdFlat", thresholdFlat); + nbt.setFloat("thresholdPercent", thresholdPercent); + nbt.setBoolean("percent", percent); + nbt.setInteger("thresholdType", thresholdType.ordinal()); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + thresholdFlat = nbt.getFloat("thresholdFlat"); + thresholdPercent = nbt.getFloat("thresholdPercent"); + percent = nbt.getBoolean("percent"); + thresholdType = ThresholdType.fromOrdinal(nbt.getInteger("thresholdType")); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String typeName = getStatName(); + String typeLabel = StatCollector.translateToLocal(thresholdType.toString()); + String value = percent + ? String.format("%.0f%%", thresholdPercent * 100) + : String.format("%.0f", thresholdFlat); + return "[" + filterLabel + "] " + typeName + " " + typeLabel + " " + value; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public float getThresholdFlat() { + return thresholdFlat; + } + + public void setThresholdFlat(float value) { + this.thresholdFlat = Math.max(0, value); + } + + public float getThresholdPercent() { + return thresholdPercent; + } + + public void setThresholdPercent(float value) { + this.thresholdPercent = Math.max(0, Math.min(1, value)); + } + + public boolean isPercent() { + return percent; + } + + public void setIsPercent(boolean percent) { + this.percent = percent; + } + + public ThresholdType getThresholdType() { + return thresholdType; + } + + public void setThresholdType(ThresholdType type) { + this.thresholdType = type; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index a3cee0443..544a7fefd 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -245,7 +245,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { AbilityCondition cond = conditions.get(i); String condName = getConditionDisplayName(cond); - sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); + GuiNpcButton condBtn = new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName); + condBtn.hoverableText = cond.getConditionSummary(); + sw.addButton(condBtn); sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); y += 22; diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java index bca83c150..b0ed1d635 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java @@ -31,6 +31,7 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi private static final int BTN_NAMESPACE = 1; private static final int BTN_CANCEL = 10; private static final int BTN_DONE = 11; + private static final int TF_SEARCH = 12; // Left panel private static final int LEFT_WIDTH = 110; @@ -39,6 +40,8 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi // Right panel private static final int RIGHT_GAP = 5; + private String searchText = ""; + private AbilityCondition condition; private AbilityCondition result; private String selectedTypeId; @@ -158,11 +161,11 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi GuiNpcTextField.unfocus(); super.initGui(); - int y = guiTop + 5; + int leftX = guiLeft + LEFT_MARGIN; + int btnY = guiTop + ySize - 26; - // Namespace filter button (full width at top) - addButton(new GuiNpcButton(BTN_NAMESPACE, guiLeft + LEFT_MARGIN, y, xSize - LEFT_MARGIN * 2, 20, getNamespaceFilterLabel())); - y += 24; + // Namespace filter button (above left scroll only) + addButton(new GuiNpcButton(BTN_NAMESPACE, leftX, guiTop + 5, LEFT_WIDTH, 20, getNamespaceFilterLabel())); // Build filtered type list filteredTypeIds = getFilteredTypes(); @@ -171,22 +174,28 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi for (String typeId : filteredTypeIds) { Supplier factory = AbilityController.Instance.getConditionType(typeId); String displayName = factory != null ? I18n.format(factory.get().getName()) : typeId; + if (!searchText.isEmpty() && !displayName.toLowerCase().contains(searchText.toLowerCase())) continue; scrollList.add(displayName); displayNameToTypeId.put(displayName, typeId); } - // Left panel: condition type scroll list - int scrollHeight = ySize - 58; - scroll = new GuiCustomScroll(this, 0); - scroll.guiLeft = guiLeft + LEFT_MARGIN; - scroll.guiTop = y; + // Left panel: condition type scroll list (between namespace button and search bar) + int scrollTop = guiTop + 29; + int scrollBottom = btnY - 24; + int scrollHeight = scrollBottom - scrollTop; + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + } + scroll.guiLeft = leftX; + scroll.guiTop = scrollTop; scroll.setSize(LEFT_WIDTH, scrollHeight); scroll.setUnsortedList(scrollList); // Pre-select current condition type in scroll if (selectedTypeId != null) { - for (int i = 0; i < filteredTypeIds.length; i++) { - if (filteredTypeIds[i].equals(selectedTypeId)) { + for (int i = 0; i < scrollList.size(); i++) { + String typeId = displayNameToTypeId.get(scrollList.get(i)); + if (typeId != null && typeId.equals(selectedTypeId)) { scroll.selected = i; break; } @@ -194,9 +203,16 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi } addScroll(scroll); - // Right panel: condition config via FieldDef - int rightX = guiLeft + LEFT_MARGIN + LEFT_WIDTH + RIGHT_GAP; + // Search text field (below left scroll) + GuiNpcTextField searchField = new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, leftX, scrollBottom + 2, LEFT_WIDTH, 20, searchText); + searchField.setHoverText("gui.search"); + addTextField(searchField); + + // Right panel: condition config via FieldDef (full height from top to buttons) + int rightX = leftX + LEFT_WIDTH + RIGHT_GAP; int rightW = xSize - LEFT_MARGIN * 2 - LEFT_WIDTH - RIGHT_GAP; + int rightTop = guiTop + 5; + int rightHeight = btnY - rightTop - 4; List fields = new ArrayList<>(); if (condition != null) { @@ -205,13 +221,17 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi builder = new AbilityFieldBuilder(this, fontRendererObj); builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); + builder.contentRight(rightW); builder.startY(5); - builder.buildScrollWindow(fields, rightX, y, rightW, scrollHeight); + builder.buildScrollWindow(fields, rightX, rightTop, rightW, rightHeight); // Bottom buttons - int btnY = guiTop + ySize - 26; - addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + LEFT_MARGIN, btnY, 60, 20, "gui.cancel")); - addButton(new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done")); + addButton(new GuiNpcButton(BTN_CANCEL, leftX, btnY, 60, 20, "gui.cancel")); + GuiNpcButton doneBtn = new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done"); + if (condition == null || !condition.isConfigured()) { + doneBtn.setEnabled(false); + } + addButton(doneBtn); } @Override @@ -263,6 +283,14 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi @Override public void unFocused(GuiNpcTextField textField) { + if (textField.id == TF_SEARCH) { + String newText = textField.getText(); + if (!newText.equals(searchText)) { + searchText = newText; + initGui(); + } + return; + } if (textField.id < DECLARATIVE_ID_START) return; if (builder != null && builder.handleTextFieldEvent(textField.id, textField)) { initGui(); diff --git a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java index bb069b8f5..8d7d88d61 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -344,6 +344,9 @@ public class GuiFieldBuilder { String translated = StatCollector.translateToLocal(def.getLabel()); int labelW = fontRenderer.getStringWidth(translated); int fieldX = colLLabel + labelW + labelPadding; + // Clamp field width so it doesn't extend under the scrollbar + int maxW = contentRight - fieldX - 15; + if (maxW > 0 && fieldW > maxW) fieldW = maxW; renderFieldAt(def, colLLabel, fieldX, fieldW, y); } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 2e222fae7..cc3f289e0 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2099,6 +2099,17 @@ condition.full_armor=Full Armor condition.item_count=Item Count condition.item_name=Item Name +# Condition Threshold +condition.above=Above +condition.below=Below +condition.equal=Equal +condition.threshold_flat=Threshold +condition.threshold_percent=Threshold % + +# Condition Quest Completed +condition.quest_completed=Quest Completed +condition.select_quest=Select Quest + # Condition Hover Tooltips condition.hover.type=Condition type that must be met for ability to activate condition.hover.hpAbove=Activates when NPC health is above this percentage From f2ac1f1817eec93f283a7f56dc725f099796a99c Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:04:14 -0500 Subject: [PATCH 34/51] Fix Effects Height --- .../java/noppes/npcs/client/gui/SubGuiEffectGeneral.java | 2 +- src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java index cfde598de..0b21d028d 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java @@ -127,7 +127,7 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi int iconWidth = effect.getWidth(); int iconHeight = effect.getHeight(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java index a390ddfc1..29cf26134 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java @@ -80,9 +80,10 @@ public class GuiEffectBar extends GuiScreen { int iconWidth = entry.effect.getWidth(); int iconHeight = entry.effect.getHeight(); int texWidth = imageData.getTotalWidth(); + int texHeight = imageData.getTotalHeight(); // Use iconYOffset to vertically center the icon - func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texWidth); + func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight); GL11.glDisable(GL11.GL_DEPTH_TEST); Minecraft.getMinecraft().getTextureManager().bindTexture(specialIcons); @@ -190,7 +191,7 @@ public class GuiEffectBar extends GuiScreen { if (imageData != null && imageData.imageLoaded()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); imageData.bindTexture(); - func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalWidth()); + func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalHeight()); } textureManager.bindTexture(specialIcons); From 5c975a339d9321756ff3c79c43caccb8cdd24378 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:24:20 -0500 Subject: [PATCH 35/51] Show Attributes on Items in Auction House --- .../kamkeel/npcs/util/AttributeItemUtil.java | 5 ++- .../client/gui/player/GuiAuctionTrades.java | 45 +++++++------------ .../noppes/npcs/mixin/MixinItemStack.java | 9 +++- 3 files changed, 28 insertions(+), 31 deletions(-) diff --git a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java index 9cc361b5d..b3de20c9e 100644 --- a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java +++ b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java @@ -15,6 +15,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.player.GuiAuctionInterface; import noppes.npcs.controllers.MagicController; import noppes.npcs.controllers.data.Magic; import org.lwjgl.input.Keyboard; @@ -230,12 +231,12 @@ public class AttributeItemUtil { * Returns the item tooltip. */ @SideOnly(Side.CLIENT) - public static List getToolTip(List original, NBTTagCompound compound) { + public static List getToolTip(List original, NBTTagCompound compound, boolean override) { List tooltip = new ArrayList<>(original); // Get the RPGCore compound and then the Attributes compound. NBTTagCompound rpgCore = compound.hasKey(TAG_RPGCORE) ? compound.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound(); NBTTagCompound attrTag = rpgCore.hasKey(TAG_ATTRIBUTES) ? rpgCore.getCompoundTag(TAG_ATTRIBUTES) : new NBTTagCompound(); - if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode())) { + if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode()) || override) { List newTooltips = new ArrayList<>(); if (!tooltip.isEmpty()) { newTooltips.add(tooltip.get(0)); diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java index 45a527dca..05e83c5bc 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java @@ -88,10 +88,16 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); - if (listing != null && tradesContainer.isSellingAt(slot) && mouseButton == 1) { - // Right-click on own listing = show cancel - setPending(slot, PendingOp.CANCEL); - NoppesUtil.clickSound(); + if (listing != null && tradesContainer.isSellingAt(slot)) { + if (mouseButton == 0) { + // Left-click on own listing = view details + AuctionActionPacket.openBidding(listing.id); + NoppesUtil.clickSound(); + } else if (mouseButton == 1) { + // Right-click on own listing = show cancel + setPending(slot, PendingOp.CANCEL); + NoppesUtil.clickSound(); + } } else if (listing != null && tradesContainer.isBiddingAt(slot) && mouseButton == 0) { // Left-click on active bid = open bidding GUI to increase bid AuctionActionPacket.openBidding(listing.id); @@ -315,16 +321,13 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); - if (listing != null) { - if (tradesContainer.isSellingAt(slot)) { - tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.trades.activeListing")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel")); - } else if (tradesContainer.isBiddingAt(slot)) { - tooltip.add(EnumChatFormatting.AQUA + StatCollector.translateToLocal("auction.trades.activeBid")); - tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.winningBid")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToIncrease")); - } - } else if (claim != null) { + // Slots with items have tooltips handled by AuctionTooltipHandler via ItemTooltipEvent + if (listing != null) return; + if (claim != null && (claim.type == EnumClaimType.ITEM || + (claim.type == EnumClaimType.REFUND && claim.item != null))) return; + + // Non-item slots (currency claims, refund without item, unavailable) + if (claim != null) { switch (claim.type) { case CURRENCY: tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.soldClaim")); @@ -342,20 +345,6 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.outbidBy") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName); } tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName()); - // Show rebid option if item is present (active listing) - if (claim.item != null) { - tooltip.add(""); - tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund")); - return; // Skip the generic claim message - } - break; - case ITEM: - if (claim.isReturned) { - tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expiredClaim")); - } else { - tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.wonClaim")); - } break; } tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToClaim")); diff --git a/src/main/java/noppes/npcs/mixin/MixinItemStack.java b/src/main/java/noppes/npcs/mixin/MixinItemStack.java index 8615573c0..4e82147f1 100644 --- a/src/main/java/noppes/npcs/mixin/MixinItemStack.java +++ b/src/main/java/noppes/npcs/mixin/MixinItemStack.java @@ -1,9 +1,11 @@ package noppes.npcs.mixin; import kamkeel.npcs.util.AttributeItemUtil; +import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.player.GuiAuctionInterface; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -28,9 +30,14 @@ public abstract class MixinItemStack { @Inject(method = "getTooltip", at = @At("TAIL"), cancellable = true) public void getAttributeTooltip(EntityPlayer player, boolean advanced, CallbackInfoReturnable> cir) { + boolean override = false; + if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface) { + override = true; + } + List tooltip = cir.getReturnValue(); if (hasTagCompound() && getTagCompound().hasKey(TAG_RPGCORE)) { - cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound())); + cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound(), override)); } } } From 1b5584c585d4d6425e2ead88dbfb3c46a2a6b87f Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:28:16 -0500 Subject: [PATCH 36/51] Has Effect and Class Condition --- .../npcs/controllers/AbilityController.java | 2 + .../conditions/ConditionHasEffect.java | 106 ++++++++++++++++++ .../data/ability/type/AbilityCutter.java | 10 +- .../assets/customnpcs/lang/en_US.lang | 4 + 4 files changed, 116 insertions(+), 6 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index b29bbb668..02c438e62 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -5,6 +5,7 @@ import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold; import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount; import kamkeel.npcs.controllers.data.ability.conditions.ConditionItem; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect; import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; @@ -156,6 +157,7 @@ public class AbilityController implements IAbilityHandler { registerCondition(ConditionHitCount::new); registerCondition(ConditionItem::new); registerCondition(ConditionQuestCompleted::new); + registerCondition(ConditionHasEffect::new); } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java new file mode 100644 index 000000000..b0c3941ad --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java @@ -0,0 +1,106 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.util.HashMap; +import java.util.List; + +public class ConditionHasEffect extends AbilityCondition { + private int effectId = -1; + private int effectIndex = 0; + + public ConditionHasEffect() { + this.typeId = "condition.cnpc.has_effect"; + this.name = "condition.has_effect"; + this.userType = UserType.PLAYER_ONLY; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + if (!(entity instanceof EntityPlayer)) return false; + if (effectId < 0) return false; + + EntityPlayer player = (EntityPlayer) entity; + return CustomEffectController.getInstance().hasEffect(player, effectId, effectIndex); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.subGuiField("condition.select_effect", + () -> new SubGuiCustomEffectSelect(effectId, effectIndex), + (SubGuiInterface gui) -> { + SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui; + if (sel.getSelectedEffectId() >= 0) { + effectId = sel.getSelectedEffectId(); + effectIndex = sel.getSelectedIndex(); + } + }) + .buttonLabel(() -> { + if (effectId < 0) return "None"; + CustomEffect effect = getEffect(); + return effect != null ? effect.getName() : "ID:" + effectId; + }) + .clearable(() -> { + effectId = -1; + effectIndex = 0; + })); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String effectName = "None"; + if (effectId >= 0) { + CustomEffect effect = getEffect(); + effectName = effect != null ? effect.getName() : "ID:" + effectId; + } + return "[" + filterLabel + "] Effect: " + effectName; + } + + @Override + public boolean isConfigured() { + return effectId >= 0; + } + + private CustomEffect getEffect() { + HashMap map = CustomEffectController.getInstance().getEffectMap(effectIndex); + return map != null ? map.get(effectId) : null; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("effectId", effectId); + nbt.setInteger("effectIndex", effectIndex); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + effectId = nbt.getInteger("effectId"); + effectIndex = nbt.getInteger("effectIndex"); + } + + public int getEffectId() { + return effectId; + } + + public void setEffectId(int effectId) { + this.effectId = effectId; + } + + public int getEffectIndex() { + return effectIndex; + } + + public void setEffectIndex(int effectIndex) { + this.effectIndex = effectIndex; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index bdb90c951..6db0f832e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -164,12 +164,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { currentRotation = -arcAngle / 2.0f; activeSoundPlayed = false; - // Use the telegraph's locked yaw if available, so the sweep direction - // matches the telegraph the player/NPC was seeing during windup. - // The telegraph yaw is locked when entering ACTIVE phase via lockPosition(). - if (!telegraphInstances.isEmpty()) { - sweepBaseYaw = telegraphInstances.get(0).getYaw(); - } else if (target != null) { + // Compute sweep direction from caster/target at execution time. + // Server-side telegraph instances are not ticked, so their yaw is stale + // from windup start — use the caster's current rotation instead. + if (target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; if (dx * dx + dz * dz > 0.0001) { diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index cc3f289e0..40bf70930 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2110,6 +2110,10 @@ condition.threshold_percent=Threshold % condition.quest_completed=Quest Completed condition.select_quest=Select Quest +# Condition Has Effect +condition.has_effect=Has Effect +condition.select_effect=Select Effect + # Condition Hover Tooltips condition.hover.type=Condition type that must be met for ability to activate condition.hover.hpAbove=Activates when NPC health is above this percentage From 9dac3d01d9b5d071e01653ab565b3b8cb20c1ab1 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:31:44 -0500 Subject: [PATCH 37/51] Show Attributes on Items in Auction House --- src/main/java/kamkeel/npcs/util/AttributeItemUtil.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java index b3de20c9e..74061d29c 100644 --- a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java +++ b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java @@ -238,7 +238,7 @@ public class AttributeItemUtil { NBTTagCompound attrTag = rpgCore.hasKey(TAG_ATTRIBUTES) ? rpgCore.getCompoundTag(TAG_ATTRIBUTES) : new NBTTagCompound(); if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode()) || override) { List newTooltips = new ArrayList<>(); - if (!tooltip.isEmpty()) { + if (!tooltip.isEmpty() && !override) { newTooltips.add(tooltip.get(0)); } @@ -326,7 +326,11 @@ public class AttributeItemUtil { newTooltips.addAll(buildSection(reqEntries)); } - tooltip = newTooltips; + if(override){ + tooltip.addAll(newTooltips); + } else { + tooltip = newTooltips; + } } else { String keyName = Keyboard.getKeyName(ClientProxy.NPCButton.getKeyCode()); tooltip.add(EnumChatFormatting.YELLOW + "" + EnumChatFormatting.ITALIC + From f538cebd03a50d97e344502fd8fa1e5863e3a9b6 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:33:54 -0500 Subject: [PATCH 38/51] Fix Custom Effects Preview with Height --- .../java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java index 21ecb1b8d..57df39d20 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java @@ -173,7 +173,7 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro int iconWidth = effect.getWidth(); int iconHeight = effect.getHeight(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); From 6369cb2b651336e683873659129325ecb73ad326 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 03:48:50 -0500 Subject: [PATCH 39/51] Better Animation Snapping --- .../noppes/npcs/AnimationMixinFunctions.java | 40 ++++++++++++------- .../controllers/data/PlayerAbilityData.java | 12 ------ 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/src/main/java/noppes/npcs/AnimationMixinFunctions.java b/src/main/java/noppes/npcs/AnimationMixinFunctions.java index 4a6eb1db5..e5c6d2089 100644 --- a/src/main/java/noppes/npcs/AnimationMixinFunctions.java +++ b/src/main/java/noppes/npcs/AnimationMixinFunctions.java @@ -209,21 +209,31 @@ public class AnimationMixinFunctions { return null; } - public static void playerFullModel_head(Entity p_78088_1_, CallbackInfo callbackInfo) { - if (!DBCAddon.IsAvailable() && ClientCacheHandler.playerAnimations.containsKey(p_78088_1_.getUniqueID())) { - AnimationData animData = ClientCacheHandler.playerAnimations.get(p_78088_1_.getUniqueID()); - if (animData != null && animData.isActive()) { - Frame frame = (Frame) animData.animation.currentFrame(); - if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) { - FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); - part.interpolateOffset(); - part.interpolateAngles(); - float pi = 180 / (float) Math.PI; - GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]); - GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0); - GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0); - GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1); - } + public static void playerFullModel_head(Entity entity, CallbackInfo callbackInfo) { + if (!ClientCacheHandler.playerAnimations.containsKey(entity.getUniqueID())) return; + + AnimationData animData = ClientCacheHandler.playerAnimations.get(entity.getUniqueID()); + if (animData == null || !animData.isActive()) return; + + // Snap body rotation to head so animations face the look direction + if (entity instanceof EntityLivingBase) { + EntityLivingBase living = (EntityLivingBase) entity; + living.renderYawOffset = living.rotationYaw; + living.prevRenderYawOffset = living.prevRotationYaw; + } + + // FULL_MODEL GL transforms (non-DBC only) + if (!DBCAddon.IsAvailable()) { + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) { + FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); + part.interpolateOffset(); + part.interpolateAngles(); + float pi = 180 / (float) Math.PI; + GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]); + GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0); + GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0); + GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1); } } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 1762a24c5..b8958d24a 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -298,7 +298,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA // Apply rotation and position locks after ability tick applyRotationControl(player); applyPositionLock(player); - applyAnimationRotationSync(player); // Sync lock state to client (only sends when flags change) syncAbilityStateIfNeeded(player); @@ -846,17 +845,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } } - private void applyAnimationRotationSync(EntityPlayer player) { - if (rotationLocked || currentAbility == null) return; - if (currentAbility.getPhase() == AbilityPhase.IDLE || currentAbility.getPhase() == AbilityPhase.DAZED) - return; - - // TODO This is a temporary duct-tape solution to fix the animation not rotating with head rotation - if (!currentAbility.isRotationLockedForCurrentPhase() && player instanceof EntityPlayerMP) { - NoppesUtilPlayer.swingPlayerArm((EntityPlayerMP) player); - } - } - // ═══════════════════════════════════════════════════════════════════ // POSITION LOCKING (Player-specific application) // ═══════════════════════════════════════════════════════════════════ From 4dde214f948d79865b6f55d06d6bd9de0d41b295 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:11:28 -0500 Subject: [PATCH 40/51] Fix Persistent Ability Entities --- .../npcs/entity/EntityAbilitySweeper.java | 40 +----- .../npcs/entity/EntityAbilityZone.java | 122 +----------------- .../kamkeel/npcs/entity/EntityEnergyDome.java | 10 +- .../npcs/entity/EntityEnergyPanel.java | 18 +-- .../npcs/entity/EntityEnergyProjectile.java | 6 +- 5 files changed, 10 insertions(+), 186 deletions(-) diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index 4323141f5..f1a591760 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -366,47 +366,11 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - readEnergyBaseNBT(nbt); - this.beamLength = sanitize(nbt.getFloat("BeamLength"), 10.0f, MAX_ENTITY_SIZE); - this.beamWidth = sanitize(nbt.getFloat("BeamWidth"), 0.3f, MAX_ENTITY_SIZE); - this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 1.0f, MAX_ENTITY_SIZE); - this.sweepSpeed = nbt.hasKey("SweepSpeed") ? nbt.getFloat("SweepSpeed") : 3.0f; - if (Float.isNaN(sweepSpeed) || Float.isInfinite(sweepSpeed) || sweepSpeed <= 0) sweepSpeed = 3.0f; - this.numberOfRotations = nbt.hasKey("NumRotations") ? nbt.getInteger("NumRotations") : 2; - if (numberOfRotations <= 0) numberOfRotations = 1; - this.completedRotations = nbt.getInteger("CompletedRotations"); - this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 400; - if (maxTicks <= 0) maxTicks = 400; - this.targetEntityId = nbt.getInteger("TargetId"); - this.currentAngle = nbt.getFloat("CurrentAngle"); - this.prevAngle = currentAngle; - this.baseYaw = nbt.getFloat("BaseYaw"); - this.deathWorldTime = nbt.getLong("DeathWorldTime"); - this.damage = nbt.hasKey("Damage") ? nbt.getFloat("Damage") : 5.0f; - if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 5.0f; - this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 5; - if (damageInterval <= 0) damageInterval = 1; - this.piercing = !nbt.hasKey("Piercing") || nbt.getBoolean("Piercing"); - this.lockOnTarget = nbt.getBoolean("LockOnTarget"); + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { - writeEnergyBaseNBT(nbt); - nbt.setFloat("BeamLength", beamLength); - nbt.setFloat("BeamWidth", beamWidth); - nbt.setFloat("BeamHeight", beamHeight); - nbt.setFloat("SweepSpeed", sweepSpeed); - nbt.setInteger("NumRotations", numberOfRotations); - nbt.setInteger("CompletedRotations", completedRotations); - nbt.setInteger("MaxTicks", maxTicks); - nbt.setInteger("TargetId", targetEntityId); - nbt.setFloat("CurrentAngle", currentAngle); - nbt.setFloat("BaseYaw", baseYaw); - nbt.setLong("DeathWorldTime", deathWorldTime); - nbt.setFloat("Damage", damage); - nbt.setInteger("DamageInterval", damageInterval); - nbt.setBoolean("Piercing", piercing); - nbt.setBoolean("LockOnTarget", lockOnTarget); + // Intentionally empty — ability entities are transient (not saved to world) } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java index a3aa494b4..2a5988847 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -716,130 +716,12 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - int zoneTypeOrd = nbt.getInteger("ZoneType"); - this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; - try { - this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); - } catch (Exception e) { - this.shape = ZoneShape.CIRCLE; - } - - this.ownerEntityId = nbt.getInteger("OwnerId"); - this.radius = nbt.hasKey("Radius") ? nbt.getFloat("Radius") : 4.0f; - this.durationTicks = nbt.hasKey("Duration") ? nbt.getInteger("Duration") : 200; - this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 200; - this.innerColor = nbt.hasKey("InnerColor") ? nbt.getInteger("InnerColor") : 0xFF6600; - this.outerColor = nbt.hasKey("OuterColor") ? nbt.getInteger("OuterColor") : 0xFF0000; - this.outerColorEnabled = !nbt.hasKey("OuterColorEnabled") || nbt.getBoolean("OuterColorEnabled"); - this.zoneHeight = nbt.hasKey("ZoneHeight") ? nbt.getFloat("ZoneHeight") : 2.0f; - this.particleDensity = nbt.hasKey("ParticleDensity") ? nbt.getFloat("ParticleDensity") : 1.0f; - this.particleScale = nbt.hasKey("ParticleScale") ? nbt.getFloat("ParticleScale") : 1.0f; - this.animSpeed = nbt.hasKey("AnimSpeed") ? nbt.getFloat("AnimSpeed") : 1.0f; - this.lightningDensity = nbt.hasKey("LightningDensity") ? nbt.getFloat("LightningDensity") : 1.0f; - this.deathWorldTime = nbt.getLong("DeathWorldTime"); - - // Visual layer fields - this.groundFill = nbt.getBoolean("GroundFill"); - this.groundAlpha = nbt.getFloat("GroundAlpha"); - this.rings = nbt.getBoolean("Rings"); - this.ringCount = nbt.getInteger("RingCount"); - this.border = nbt.getBoolean("Border"); - this.borderSpeed = nbt.getFloat("BorderSpeed"); - this.accents = nbt.getBoolean("Accents"); - this.accentStyle = nbt.getInteger("AccentStyle"); - this.lightning = nbt.getBoolean("Lightning"); - this.particles = nbt.getBoolean("Particles"); - this.particleMotion = nbt.getInteger("ParticleMotion"); - this.particleDir = nbt.getString("ParticleDir"); - this.particleSize = nbt.getInteger("ParticleSize"); - this.particleGlow = nbt.getBoolean("ParticleGlow"); - - // Trap - this.armTime = nbt.getInteger("ArmTime"); - this.triggerRadius = nbt.getFloat("TriggerRadius"); - this.maxTriggers = nbt.getInteger("MaxTriggers"); - this.triggerCooldown = nbt.getInteger("TriggerCooldown"); - this.damage = nbt.getFloat("Damage"); - this.damageRadius = nbt.getFloat("DamageRadius"); - this.knockback = nbt.getFloat("Knockback"); - this.visible = nbt.getBoolean("Visible"); - - // Hazard - this.damagePerSecond = nbt.hasKey("DamagePerSecond") ? nbt.getFloat("DamagePerSecond") : 1.0f; - this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 20; - if (damageInterval <= 0) damageInterval = 1; - this.ignoreInvulnFrames = nbt.getBoolean("IgnoreInvuln"); - this.affectsCaster = nbt.getBoolean("AffectsCaster"); - - // Effects - effects.clear(); - if (nbt.hasKey("Effects")) { - NBTTagList effectList = nbt.getTagList("Effects", 10); - for (int i = 0; i < effectList.tagCount(); i++) { - AbilityPotionEffect effect = AbilityPotionEffect.fromNBT(effectList.getCompoundTagAt(i)); - if (effect != null && effect.isValid()) { - effects.add(effect); - } - } - } + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { - nbt.setInteger("ZoneType", zoneType.ordinal()); - nbt.setString("ShapeName", shape.name()); - nbt.setInteger("OwnerId", ownerEntityId); - nbt.setFloat("Radius", radius); - nbt.setInteger("Duration", durationTicks); - nbt.setInteger("MaxTicks", maxTicks); - nbt.setInteger("InnerColor", innerColor); - nbt.setInteger("OuterColor", outerColor); - nbt.setBoolean("OuterColorEnabled", outerColorEnabled); - nbt.setFloat("ZoneHeight", zoneHeight); - nbt.setFloat("ParticleDensity", particleDensity); - nbt.setFloat("ParticleScale", particleScale); - nbt.setFloat("AnimSpeed", animSpeed); - nbt.setFloat("LightningDensity", lightningDensity); - nbt.setLong("DeathWorldTime", deathWorldTime); - - // Visual layer fields - nbt.setBoolean("GroundFill", groundFill); - nbt.setFloat("GroundAlpha", groundAlpha); - nbt.setBoolean("Rings", rings); - nbt.setInteger("RingCount", ringCount); - nbt.setBoolean("Border", border); - nbt.setFloat("BorderSpeed", borderSpeed); - nbt.setBoolean("Accents", accents); - nbt.setInteger("AccentStyle", accentStyle); - nbt.setBoolean("Lightning", lightning); - nbt.setBoolean("Particles", particles); - nbt.setInteger("ParticleMotion", particleMotion); - nbt.setString("ParticleDir", particleDir); - nbt.setInteger("ParticleSize", particleSize); - nbt.setBoolean("ParticleGlow", particleGlow); - - // Trap - nbt.setInteger("ArmTime", armTime); - nbt.setFloat("TriggerRadius", triggerRadius); - nbt.setInteger("MaxTriggers", maxTriggers); - nbt.setInteger("TriggerCooldown", triggerCooldown); - nbt.setFloat("Damage", damage); - nbt.setFloat("DamageRadius", damageRadius); - nbt.setFloat("Knockback", knockback); - nbt.setBoolean("Visible", visible); - - // Hazard - nbt.setFloat("DamagePerSecond", damagePerSecond); - nbt.setInteger("DamageInterval", damageInterval); - nbt.setBoolean("IgnoreInvuln", ignoreInvulnFrames); - nbt.setBoolean("AffectsCaster", affectsCaster); - - // Effects - NBTTagList effectList = new NBTTagList(); - for (AbilityPotionEffect effect : effects) { - effectList.appendTag(effect.writeNBT()); - } - nbt.setTag("Effects", effectList); + // Intentionally empty — ability entities are transient (not saved to world) } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 3d4fabe44..1697d6d9b 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -599,17 +599,11 @@ public class EntityEnergyDome extends EntityEnergyBarrier { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - readBarrierBaseNBT(nbt); - this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS)); - this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); - this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { - writeBarrierBaseNBT(nbt); - nbt.setFloat("DomeRadius", domeRadius); - nbt.setFloat("TargetDomeRadius", targetDomeRadius); - nbt.setBoolean("FollowCaster", followCaster); + // Intentionally empty — ability entities are transient (not saved to world) } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index 1ef8dc370..8c8e2288b 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -556,25 +556,11 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - readBarrierBaseNBT(nbt); - this.panelYaw = nbt.getFloat("PanelYaw"); - int modeOrdinal = nbt.getInteger("PanelMode"); - this.mode = (modeOrdinal >= 0 && modeOrdinal < PanelMode.values().length) - ? PanelMode.values()[modeOrdinal] : PanelMode.PLACED; - panelData.readNBT(nbt); - panelData.panelWidth = sanitize(panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); - panelData.panelHeight = sanitize(panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); - this.targetPanelWidth = sanitize(nbt.hasKey("TargetPanelWidth") ? nbt.getFloat("TargetPanelWidth") : panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); - this.targetPanelHeight = sanitize(nbt.hasKey("TargetPanelHeight") ? nbt.getFloat("TargetPanelHeight") : panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { - writeBarrierBaseNBT(nbt); - nbt.setFloat("PanelYaw", panelYaw); - nbt.setInteger("PanelMode", mode.ordinal()); - nbt.setFloat("TargetPanelWidth", targetPanelWidth); - nbt.setFloat("TargetPanelHeight", targetPanelHeight); - panelData.writeNBT(nbt); + // Intentionally empty — ability entities are transient (not saved to world) } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index 5b741cc0b..89d537552 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -926,14 +926,12 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - readBaseNBT(nbt); - readProjectileNBT(nbt); + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { - writeBaseNBT(nbt); - writeProjectileNBT(nbt); + // Intentionally empty — ability entities are transient (not saved to world) } /** From 5b52c817d788f5d29e144cea1f8d1787913ff3c6 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:11:39 -0500 Subject: [PATCH 41/51] Add New Dash Directional --- .../data/ability/type/AbilityDash.java | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java index fffbf6ca5..b5342e3d8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -26,7 +26,8 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { */ public enum DashMode { AGGRESSIVE, - DEFENSIVE; + DEFENSIVE, + DIRECTIONAL; @Override public String toString() { @@ -35,6 +36,8 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { return "ability.dash.aggressive"; case DEFENSIVE: return "ability.dash.defensive"; + case DIRECTIONAL: + return "ability.dash.directional"; default: return name(); } @@ -124,16 +127,22 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { public void onExecute(EntityLivingBase caster, EntityLivingBase target) { initMovement(caster, dashDistance, dashSpeed); - // Choose random direction based on mode - DashDirection[] directions = dashMode == DashMode.AGGRESSIVE - ? AGGRESSIVE_DIRECTIONS - : DEFENSIVE_DIRECTIONS; - chosenDirection = directions[RANDOM.nextInt(directions.length)]; + if (dashMode == DashMode.DIRECTIONAL) { + // Dash straight in the caster's look direction + chosenDirection = DashDirection.FORWARD; + setDirectionFromYaw(caster.rotationYaw); + } else { + // Choose random direction based on mode + DashDirection[] directions = dashMode == DashMode.AGGRESSIVE + ? AGGRESSIVE_DIRECTIONS + : DEFENSIVE_DIRECTIONS; + chosenDirection = directions[RANDOM.nextInt(directions.length)]; - // Calculate direction: base yaw (toward target or look dir) + direction offset - float baseYaw = getBaseYaw(caster, target); - float dashYaw = baseYaw + chosenDirection.getAngleOffset(); - setDirectionFromYaw(dashYaw); + // Calculate direction: base yaw (toward target or look dir) + direction offset + float baseYaw = getBaseYaw(caster, target); + float dashYaw = baseYaw + chosenDirection.getAngleOffset(); + setDirectionFromYaw(dashYaw); + } // Small upward impulse for a skip/hop arc (gravity handles the descent) caster.motionY = 0.2; From aa58cf804184f8f414cc6998e5bef3bf0b9eec60 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:41:14 -0500 Subject: [PATCH 42/51] Fix DBC Turbo Bounceback in Liquid and Lava --- .../data/ability/type/AbilityCharge.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index bc2da7cae..4f7021705 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -66,26 +66,25 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { } /** - * Called on the first tick of windup - lock direction here so it matches telegraph. + * During windup, NPCs face toward their target for animation purposes. + * Players aim freely — the telegraph follows their look direction on the client, + * and direction is locked at the end of windup in onExecute(). */ @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { - if (tick == 1) { - lockDirection(caster, target); + if (!isPlayerCaster(caster) && target != null) { + lockDirectionToTarget(caster, target); + enforceLockedRotation(caster); } - enforceLockedRotation(caster); } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // Lock final direction at end of windup so it matches the telegraph + lockDirection(caster, target); initMovement(caster, maxRange, chargeSpeed); hitEntities.clear(); - // If direction wasn't set during windup (shouldn't happen), set it now - if (movementDirection == null) { - lockDirection(caster, target); - } - enforceLockedRotation(caster); } From e210bac2bfb7c6a9fb6573805882951710a24eeb Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:41:51 -0500 Subject: [PATCH 43/51] Fix Caster Positoning and Lock / Movement Dashing Abilities --- .../controllers/data/ability/Ability.java | 12 ++++-- .../data/ability/type/AbilityMovement.java | 38 +++++++++++++++++-- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 5d793f5ec..5517caef2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -863,11 +863,17 @@ public abstract class Ability implements IAbility, IAbilityAction { // AOE_SELF abilities: telegraph follows caster during windup instance.setEntityIdToFollow(caster.getEntityId()); - // For LINE/CONE telegraphs: track target direction during windup + // For LINE/CONE telegraphs: track direction during windup // Only track if rotation is NOT locked during windup (NPC can still turn) - if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { + if (telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) { if (!isRotationLockedDuringWindup()) { - instance.setTargetEntityId(target.getEntityId()); + if (target != null) { + // Face the target entity + instance.setTargetEntityId(target.getEntityId()); + } else { + // No target (AOE_SELF etc.): track caster's own rotationYaw + instance.setTrackFollowedEntityYaw(true); + } } // If rotation is locked, yaw stays fixed at creation time } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java index b54056146..331b91920 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java @@ -2,6 +2,8 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.play.server.S12PacketEntityVelocity; import net.minecraft.util.Vec3; /** @@ -213,6 +215,24 @@ public abstract class AbilityMovement extends Ability { // VELOCITY APPLICATION // ═══════════════════════════════════════════════════════════════════ + /** + * Send an authoritative velocity packet to a player. + *

+ * The ability tick runs BEFORE moveEntityWithHeading (at PlayerTickEvent.START). + * If we use velocityChanged, the entity tracker sends S12 AFTER friction has + * reduced the motion (~55% of set value). The client then moves at reduced speed, + * reports a short position via C04, and the server resets to the client's position. + *

+ * By sending S12 manually here — before friction — the client receives the full + * velocity and moves at the correct speed. + */ + private void sendPlayerVelocity(EntityLivingBase caster) { + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } + } + /** * Apply movement velocity to the caster (horizontal only, Y unchanged). */ @@ -220,7 +240,11 @@ public abstract class AbilityMovement extends Ability { caster.motionX = movementDirection.xCoord * speed; caster.motionZ = movementDirection.zCoord * speed; if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } } } @@ -233,7 +257,11 @@ public abstract class AbilityMovement extends Ability { caster.motionY = 0; caster.motionZ = movementDirection.zCoord * speed; if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } } } @@ -244,7 +272,11 @@ public abstract class AbilityMovement extends Ability { caster.motionX = 0; caster.motionZ = 0; if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } } } From 3921b3e6542d555d5fc5e842c0648a5ee0d6fa45 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:42:00 -0500 Subject: [PATCH 44/51] Dash Directional Key --- src/main/resources/assets/customnpcs/lang/en_US.lang | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 40bf70930..8e2aa437c 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1562,6 +1562,7 @@ ability.sweep.spin=Spin # Dash Mode ability.dash.aggressive=Aggressive ability.dash.defensive=Defensive +ability.dash.directional=Directional # Counter Type ability.counter.flat=Flat @@ -1995,7 +1996,7 @@ ability.hover.speed=Movement speed of projectile ability.hover.lifetime=Maximum ticks before despawning ability.hover.knockback=Push force applied to targets ability.hover.boomerang=Projectile returns to caster after reaching max distance -ability.hover.dashMode=Aggressive dashes toward target, Defensive dashes away +ability.hover.dashMode=Aggressive dashes toward target, Defensive dashes away, Directional dashes in looking direction ability.hover.aoe=Affects all valid targets in range instead of just one ability.hover.dmgOnPull=Deal damage continuously while pulling targets ability.hover.lineOfSight=Requires clear line of sight to the target From 06809933edb8beddaf866a63b520187fd9088334 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:42:07 -0500 Subject: [PATCH 45/51] Update API --- src/api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api b/src/api index 96799f68e..a9c77d20e 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 96799f68ecc1f529ab287b426052048695332e87 +Subproject commit a9c77d20eb83be6a3168480c0d62fa78419e9469 From 12c50d5f6a7dbe31bbe8b510527f32b9b0384c83 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 04:56:53 -0500 Subject: [PATCH 46/51] Whoops Forgot to Sync NBTs --- .../npcs/entity/EntityAbilitySweeper.java | 46 +++++++++++++++++++ .../npcs/entity/EntityAbilityZone.java | 14 +++--- .../npcs/entity/EntityEnergyAbility.java | 27 +++++++++-- .../kamkeel/npcs/entity/EntityEnergyDome.java | 16 +++++++ .../npcs/entity/EntityEnergyPanel.java | 24 ++++++++++ .../npcs/entity/EntityEnergyProjectile.java | 12 +++++ 6 files changed, 128 insertions(+), 11 deletions(-) diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index f1a591760..f08ffeb2a 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -373,4 +373,50 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { protected void writeEntityToNBT(NBTTagCompound nbt) { // Intentionally empty — ability entities are transient (not saved to world) } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + nbt.setFloat("BeamLength", beamLength); + nbt.setFloat("BeamWidth", beamWidth); + nbt.setFloat("BeamHeight", beamHeight); + nbt.setFloat("SweepSpeed", sweepSpeed); + nbt.setInteger("NumRotations", numberOfRotations); + nbt.setInteger("CompletedRotations", completedRotations); + nbt.setInteger("MaxTicks", maxTicks); + nbt.setInteger("TargetId", targetEntityId); + nbt.setFloat("CurrentAngle", currentAngle); + nbt.setFloat("BaseYaw", baseYaw); + nbt.setLong("DeathWorldTime", deathWorldTime); + nbt.setFloat("Damage", damage); + nbt.setInteger("DamageInterval", damageInterval); + nbt.setBoolean("Piercing", piercing); + nbt.setBoolean("LockOnTarget", lockOnTarget); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + this.beamLength = sanitize(nbt.getFloat("BeamLength"), 10.0f, MAX_ENTITY_SIZE); + this.beamWidth = sanitize(nbt.getFloat("BeamWidth"), 0.3f, MAX_ENTITY_SIZE); + this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 1.0f, MAX_ENTITY_SIZE); + this.sweepSpeed = nbt.hasKey("SweepSpeed") ? nbt.getFloat("SweepSpeed") : 3.0f; + if (Float.isNaN(sweepSpeed) || Float.isInfinite(sweepSpeed) || sweepSpeed <= 0) sweepSpeed = 3.0f; + this.numberOfRotations = nbt.hasKey("NumRotations") ? nbt.getInteger("NumRotations") : 2; + if (numberOfRotations <= 0) numberOfRotations = 1; + this.completedRotations = nbt.getInteger("CompletedRotations"); + this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 400; + if (maxTicks <= 0) maxTicks = 400; + this.targetEntityId = nbt.getInteger("TargetId"); + this.currentAngle = nbt.getFloat("CurrentAngle"); + this.prevAngle = currentAngle; + this.baseYaw = nbt.getFloat("BaseYaw"); + this.deathWorldTime = nbt.getLong("DeathWorldTime"); + this.damage = nbt.hasKey("Damage") ? nbt.getFloat("Damage") : 5.0f; + if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 5.0f; + this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 5; + if (damageInterval <= 0) damageInterval = 1; + this.piercing = !nbt.hasKey("Piercing") || nbt.getBoolean("Piercing"); + this.lockOnTarget = nbt.getBoolean("LockOnTarget"); + } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java index 2a5988847..a5225d620 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -1,6 +1,6 @@ package kamkeel.npcs.entity; -import cpw.mods.fml.common.network.ByteBufUtils; +import kamkeel.npcs.util.ByteBufUtils; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -731,7 +731,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override public void writeSpawnData(ByteBuf buffer) { buffer.writeInt(zoneType.ordinal()); - ByteBufUtils.writeUTF8String(buffer, shape.name()); + ByteBufUtils.writeString(buffer, shape.name()); buffer.writeInt(ownerEntityId); buffer.writeFloat(radius); buffer.writeInt(durationTicks); @@ -757,7 +757,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD buffer.writeBoolean(lightning); buffer.writeBoolean(particles); buffer.writeInt(particleMotion); - ByteBufUtils.writeUTF8String(buffer, particleDir); + ByteBufUtils.writeString(buffer, particleDir); buffer.writeInt(particleSize); buffer.writeBoolean(particleGlow); @@ -772,14 +772,14 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD effectList.appendTag(effect.writeNBT()); } effectsNbt.setTag("Effects", effectList); - ByteBufUtils.writeTag(buffer, effectsNbt); + ByteBufUtils.writeNBT(buffer, effectsNbt); } @Override public void readSpawnData(ByteBuf buffer) { int zoneTypeOrd = buffer.readInt(); this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; - String shapeName = ByteBufUtils.readUTF8String(buffer); + String shapeName = ByteBufUtils.readString(buffer); try { this.shape = ZoneShape.valueOf(shapeName); } catch (Exception e) { @@ -810,7 +810,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.lightning = buffer.readBoolean(); this.particles = buffer.readBoolean(); this.particleMotion = buffer.readInt(); - this.particleDir = ByteBufUtils.readUTF8String(buffer); + this.particleDir = ByteBufUtils.readString(buffer); this.particleSize = buffer.readInt(); this.particleGlow = buffer.readBoolean(); @@ -818,7 +818,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.visible = buffer.readBoolean(); // Effects - NBTTagCompound effectsNbt = ByteBufUtils.readTag(buffer); + NBTTagCompound effectsNbt = ByteBufUtils.readNBT(buffer); effects.clear(); if (effectsNbt != null && effectsNbt.hasKey("Effects")) { NBTTagList effectList = effectsNbt.getTagList("Effects", 10); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java index 2546fb8a2..585eadc7d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java @@ -7,6 +7,7 @@ import io.netty.buffer.ByteBuf; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; +import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -314,12 +315,30 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit // ==================== SPAWN DATA ==================== + /** + * Write entity data for client sync. Subclasses override this + * to serialize their fields. Separate from writeEntityToNBT + * which is intentionally empty (entities are transient, not saved to world). + */ + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + } + + /** + * Read entity data from client sync. Subclasses override this + * to deserialize their fields. Separate from readEntityFromNBT + * which is intentionally empty (entities are transient, not saved to world). + */ + protected void readSpawnNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + } + @Override public void writeSpawnData(ByteBuf buffer) { try { NBTTagCompound compound = new NBTTagCompound(); - this.writeEntityToNBT(compound); - cpw.mods.fml.common.network.ByteBufUtils.writeTag(buffer, compound); + this.writeSpawnNBT(compound); + ByteBufUtils.writeNBT(buffer, compound); } catch (Exception e) { noppes.npcs.LogWriter.error("Error writing energy ability spawn data", e); } @@ -328,9 +347,9 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit @Override public void readSpawnData(ByteBuf buffer) { try { - NBTTagCompound compound = cpw.mods.fml.common.network.ByteBufUtils.readTag(buffer); + NBTTagCompound compound = ByteBufUtils.readNBT(buffer); if (compound != null) { - this.readEntityFromNBT(compound); + this.readSpawnNBT(compound); } } catch (Exception e) { noppes.npcs.LogWriter.error("Error reading energy ability spawn data", e); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 1697d6d9b..68fa9ec8b 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -606,4 +606,20 @@ public class EntityEnergyDome extends EntityEnergyBarrier { protected void writeEntityToNBT(NBTTagCompound nbt) { // Intentionally empty — ability entities are transient (not saved to world) } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBarrierBaseNBT(nbt); + nbt.setFloat("DomeRadius", domeRadius); + nbt.setFloat("TargetDomeRadius", targetDomeRadius); + nbt.setBoolean("FollowCaster", followCaster); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBarrierBaseNBT(nbt); + this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS)); + this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); + this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); + } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index 8c8e2288b..1ef117d94 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -563,4 +563,28 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { protected void writeEntityToNBT(NBTTagCompound nbt) { // Intentionally empty — ability entities are transient (not saved to world) } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBarrierBaseNBT(nbt); + nbt.setFloat("PanelYaw", panelYaw); + nbt.setInteger("PanelMode", mode.ordinal()); + nbt.setFloat("TargetPanelWidth", targetPanelWidth); + nbt.setFloat("TargetPanelHeight", targetPanelHeight); + panelData.writeNBT(nbt); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBarrierBaseNBT(nbt); + this.panelYaw = nbt.getFloat("PanelYaw"); + int modeOrdinal = nbt.getInteger("PanelMode"); + this.mode = (modeOrdinal >= 0 && modeOrdinal < PanelMode.values().length) + ? PanelMode.values()[modeOrdinal] : PanelMode.PLACED; + panelData.readNBT(nbt); + panelData.panelWidth = sanitize(panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); + panelData.panelHeight = sanitize(panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); + this.targetPanelWidth = sanitize(nbt.hasKey("TargetPanelWidth") ? nbt.getFloat("TargetPanelWidth") : panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); + this.targetPanelHeight = sanitize(nbt.hasKey("TargetPanelHeight") ? nbt.getFloat("TargetPanelHeight") : panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); + } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index 89d537552..f3a203001 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -934,6 +934,18 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { // Intentionally empty — ability entities are transient (not saved to world) } + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBaseNBT(nbt); + writeProjectileNBT(nbt); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBaseNBT(nbt); + readProjectileNBT(nbt); + } + /** * Read base projectile properties from NBT. */ From 3e58013ad66f219e6e4cba322523d6c1f32ba0e6 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 05:09:00 -0500 Subject: [PATCH 47/51] =?UTF-8?q?Various=20Fixes=20=F0=9F=90=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../client/renderer/RenderEnergyPanel.java | 14 ++++- .../controllers/data/ability/Ability.java | 55 +++++++++++++++++- .../data/ability/type/AbilityZone.java | 17 ++++++ .../type/energy/AbilityEnergyBarrier.java | 16 ++++++ .../type/energy/AbilityEnergyProjectile.java | 19 +++++++ .../ability/type/energy/AbilitySweeper.java | 21 +++++++ .../npcs/entity/EntityAbilityZone.java | 13 ++++- .../npcs/entity/EntityEnergyPanel.java | 7 +++ .../packets/player/SpecialKeyStatePacket.java | 11 ++-- .../noppes/npcs/AbstractDataAbilities.java | 56 +++++++++++++++++++ .../controllers/data/PlayerAbilityData.java | 47 ++++++++++++++++ .../assets/customnpcs/lang/en_US.lang | 2 + 12 files changed, 268 insertions(+), 10 deletions(-) diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java index 38bdd57b2..24c9ea241 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java @@ -21,9 +21,17 @@ public class RenderEnergyPanel extends RenderEnergyBarrier { float width = panel.getPanelData().panelWidth; float height = panel.getPanelData().panelHeight; - float panelYaw = panel.getPanelYaw(); float healthPercent = panel.getHealthPercent(); + // Interpolate panel yaw for smooth rotation between ticks + float prevYaw = panel.getPrevPanelYaw(); + float currentYaw = panel.getPanelYaw(); + float yawDelta = currentYaw - prevYaw; + // Wrap angle delta to -180..180 for shortest rotation path + while (yawDelta > 180.0f) yawDelta -= 360.0f; + while (yawDelta < -180.0f) yawDelta += 360.0f; + float renderYaw = prevYaw + yawDelta * partialTicks; + setupRenderState(); GL11.glPushMatrix(); @@ -34,8 +42,8 @@ public class RenderEnergyPanel extends RenderEnergyBarrier { renderAttachedLightning(panel, 0.9f, Math.max(width, height) * 0.5f); } - // Rotate panel to face the correct direction - GL11.glRotatef(-panelYaw, 0.0f, 1.0f, 0.0f); + // Rotate panel to face the correct direction (interpolated) + GL11.glRotatef(-renderYaw, 0.0f, 1.0f, 0.0f); // Hit flash float flashAlpha = computeFlashAlpha(panel); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 5517caef2..d7ca77eac 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -114,6 +114,10 @@ public abstract class Ability implements IAbility, IAbilityAction { // instead of sharing the global cooldown with other abilities protected boolean perAbilityCooldown = false; + // Free on Cast: if true, ability enters cooldown immediately after entities are spawned, + // allowing the caster to use other abilities while summoned entities remain active + protected boolean freeOnCast = false; + // ═══════════════════════════════════════════════════════════════════ // BUILT-IN (set in constructor via configureAsBuiltIn, NOT persisted) // ═══════════════════════════════════════════════════════════════════ @@ -255,6 +259,22 @@ public abstract class Ability implements IAbility, IAbilityAction { return false; } + /** + * Whether this ability type supports the Free on Cast option. + * Override to return true for abilities that spawn persistent entities (projectiles, barriers, zones, sweeper). + */ + public boolean allowFreeOnCast() { + return false; + } + + /** + * Detach all spawned entities (let them live independently) without killing them. + * Called during signalCompletion() when freeOnCast is enabled. + * Override in subclasses to null entity references without calling setDead(). + */ + public void detach() { + } + // ═══════════════════════════════════════════════════════════════════ // TOGGLE CALLBACKS (optional overrides for toggleable abilities) // ═══════════════════════════════════════════════════════════════════ @@ -612,6 +632,10 @@ public abstract class Ability implements IAbility, IAbilityAction { FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks).range(0, 10000), FieldDef.boolField("ability.perAbilityCooldown", this::isPerAbilityCooldown, this::setPerAbilityCooldown) ).tab("General")); + if (allowFreeOnCast()) { + defs.add(FieldDef.boolField("ability.freeOnCast", this::isFreeOnCast, this::setFreeOnCast) + .tab("General").hover("ability.hover.freeOnCast")); + } defs.add(FieldDef.section("ability.section.movement").tab("General")); defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), () -> this.getLockMovement().getDisplayKey(), @@ -1072,7 +1096,12 @@ public abstract class Ability implements IAbility, IAbilityAction { // Final completion - let burst entities die naturally (don't force-kill) burstEntities.clear(); - cleanup(); + if (freeOnCast) { + // Free on Cast: detach entities (let them live independently) instead of killing + detach(); + } else { + cleanup(); + } phase = AbilityPhase.IDLE; currentTick = 0; return true; @@ -1101,6 +1130,20 @@ public abstract class Ability implements IAbility, IAbilityAction { telegraphInstances.clear(); } + /** + * Cancel this ability (voluntary player action). Goes directly to IDLE, skipping DAZED. + * Entities are killed via cleanup(). Unlike interrupt(), this never enters DAZED phase. + */ + public void cancel() { + cleanupBurstEntities(); + cleanup(); + phase = AbilityPhase.IDLE; + currentTick = 0; + burstIndex = 0; + currentTarget = null; + telegraphInstances.clear(); + } + /** * Check if executing */ @@ -1298,6 +1341,7 @@ public abstract class Ability implements IAbility, IAbilityAction { nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); nbt.setBoolean("perAbilityCooldown", perAbilityCooldown); + nbt.setBoolean("freeOnCast", freeOnCast); // Toggle nbt.setInteger("toggleStates", toggleStates); @@ -1380,6 +1424,7 @@ public abstract class Ability implements IAbility, IAbilityAction { allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); ignoreCooldown = nbt.getBoolean("ignoreCooldown"); perAbilityCooldown = nbt.getBoolean("perAbilityCooldown"); + freeOnCast = nbt.getBoolean("freeOnCast"); // Toggle toggleStates = nbt.getInteger("toggleStates"); @@ -1976,6 +2021,14 @@ public abstract class Ability implements IAbility, IAbilityAction { this.perAbilityCooldown = perAbilityCooldown; } + public boolean isFreeOnCast() { + return freeOnCast; + } + + public void setFreeOnCast(boolean freeOnCast) { + this.freeOnCast = freeOnCast; + } + public boolean isToggleable() { return toggleStates > 0; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java index 7f2a92329..a1d1af290 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -75,6 +75,17 @@ public abstract class AbilityZone extends Ability { return false; } + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + activeEntities.clear(); + preCalculatedPositions.clear(); + } + @Override public boolean isTargetingModeLocked() { return true; @@ -130,6 +141,12 @@ public abstract class AbilityZone extends Ability { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + // Free on Cast: complete immediately — zones live independently + if (isFreeOnCast()) { + signalCompletion(); + return; + } + Iterator it = activeEntities.iterator(); while (it.hasNext()) { EntityAbilityZone entity = it.next(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java index 73f34d059..3366290e9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java @@ -63,6 +63,16 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { return false; // Barriers are defensive } + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + barrierEntity = null; + } + @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (caster.worldObj.isRemote) return; @@ -97,6 +107,12 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { return; } + // Free on Cast: complete immediately after barrier becomes active + if (isFreeOnCast()) { + signalCompletion(); + return; + } + // Duration tracked by entity itself, but check here too as a failsafe if (barrierData.useDuration && tick >= barrierData.durationTicks) { cleanup(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java index da3e95c81..50b68554e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java @@ -244,6 +244,16 @@ public abstract class AbilityEnergyProjectile return true; } + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + entities = null; + } + @Override public boolean isReadyForBurstCompletion(int activeTick) { return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); @@ -338,6 +348,15 @@ public abstract class AbilityEnergyProjectile } } + // Free on Cast: complete once all projectiles have been fired + if (isFreeOnCast()) { + int lastFireTick = fireDelay > 0 ? fireDelay * (projectileCount - 1) : 0; + if (tick >= lastFireTick) { + signalCompletion(); + return; + } + } + // Check if all entities are dead or unreachable boolean allDead = true; for (E entity : entities) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java index a1340ae39..2cc64bde4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -62,6 +62,21 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { return false; } + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + activeEntity = null; + } + @Override public boolean isTargetingModeLocked() { return true; @@ -97,6 +112,12 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { if (activeEntity == null || activeEntity.isDead) { activeEntity = null; signalCompletion(); + return; + } + + // Free on Cast: complete immediately — sweeper lives independently + if (isFreeOnCast()) { + signalCompletion(); } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java index a5225d620..129b87495 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -772,7 +772,11 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD effectList.appendTag(effect.writeNBT()); } effectsNbt.setTag("Effects", effectList); - ByteBufUtils.writeNBT(buffer, effectsNbt); + try { + ByteBufUtils.writeNBT(buffer, effectsNbt); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error writing zone effects spawn data", e); + } } @Override @@ -818,7 +822,12 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.visible = buffer.readBoolean(); // Effects - NBTTagCompound effectsNbt = ByteBufUtils.readNBT(buffer); + NBTTagCompound effectsNbt = null; + try { + effectsNbt = ByteBufUtils.readNBT(buffer); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error reading zone effects spawn data", e); + } effects.clear(); if (effectsNbt != null && effectsNbt.hasKey("Effects")) { NBTTagList effectList = effectsNbt.getTagList("Effects", 10); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index 1ef117d94..1afc1f2bc 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -36,6 +36,7 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { protected EnergyPanelData panelData = new EnergyPanelData(); protected PanelMode mode = PanelMode.PLACED; protected float panelYaw = 0.0f; // Rotation of the panel face (degrees) + protected float prevPanelYaw = 0.0f; // Previous tick yaw for smooth interpolation // ==================== CHARGING (panel-specific targets) ==================== protected float targetPanelWidth; @@ -54,6 +55,7 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { this.setPosition(x, y + panel.heightOffset, z); this.ownerEntityId = owner.getEntityId(); this.panelYaw = yaw; + this.prevPanelYaw = yaw; this.mode = mode; this.displayData = display; this.lightningData = lightning; @@ -99,6 +101,7 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; + this.prevPanelYaw = this.panelYaw; super.onUpdate(); @@ -548,6 +551,10 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { return panelYaw; } + public float getPrevPanelYaw() { + return prevPanelYaw; + } + public EnergyPanelData getPanelData() { return panelData; } diff --git a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java index 212e816b4..3592e1a9a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -57,16 +57,19 @@ public final class SpecialKeyStatePacket extends AbstractPacket { boolean wasDown = data.isSpecialKeyDown(); data.setSpecialKeyDown(keyDown); - // Trigger ability activation on key press (rising edge) + // Trigger ability activation or cancel on key press (rising edge) if (keyDown && !wasDown) { - // Don't activate if player has a GUI open (not the default inventory) - // Don't activate if player is riding an entity (mount) if (player.ridingEntity != null) { return; } - data.abilityData.activateAbility(player); + // If currently executing an ability, try to cancel via double-press + if (data.abilityData.isExecutingAbility() || data.abilityData.isExecutingChain()) { + data.abilityData.tryCancelAbility(); + } else { + data.abilityData.activateAbility(player); + } } } } diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java index b78ca37e7..b63481c21 100644 --- a/src/main/java/noppes/npcs/AbstractDataAbilities.java +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -1034,6 +1034,62 @@ public abstract class AbstractDataAbilities { protected void onInterruptComplete() { } + /** + * Cancel the currently executing ability (voluntary player action). + * Unlike interrupt, this always goes directly to IDLE (never DAZED), + * immediately rolls cooldown, and clears state. + * Also handles cancellation during chain delay (between chain entries). + */ + public void cancelCurrentAbility() { + boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting(); + boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0; + + if (!hasExecutingAbility && !isInChainDelay) return; + + if (hasExecutingAbility) { + AbilityPhase phase = currentAbility.getPhase(); + // Cannot cancel during DAZED (already interrupted) + if (phase == AbilityPhase.DAZED) return; + // Only allow cancel during active phases + if (phase != AbilityPhase.WINDUP && phase != AbilityPhase.ACTIVE + && phase != AbilityPhase.BURST_DELAY) return; + + // Remove telegraph + removeTelegraph(currentAbility); + + // Fire extender complete hook (cancelled = interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, getEntity(), getTarget(), true); + + // Fire interrupt event (source=null, damage=0 for voluntary cancel) + fireInterruptEvent(currentAbility, getTarget(), null, 0); + + // Cancel the ability (cleanup + go directly to IDLE, no DAZED) + currentAbility.onInterrupt(getEntity(), null, 0); + currentAbility.cancel(); + + // Release locks and stop animation + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + } + + // Roll cooldown + if (currentChain != null) { + rollChainCooldown(currentChain); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + } else if (currentAbility != null) { + rollCooldown(currentAbility); + } + + // Interrupt all concurrent slots + interruptConcurrentSlots(); + + // Clear state via the normal completion path + onAbilityComplete(); + } + // ═══════════════════════════════════════════════════════════════════ // CHAINED ABILITY EXECUTION // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index b8958d24a..79890baeb 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -91,6 +91,16 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA */ private transient byte lastSyncedFlags = 0; + /** + * World time when the last ability was activated (for double-press cancel detection). + */ + private transient long lastAbilityActivationTime = -1; + + /** + * Ticks after activation during which a second key press will cancel the ability. + */ + private static final int CANCEL_WINDOW_TICKS = 10; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -258,6 +268,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = null; currentAbilityKey = null; currentTarget = null; + lastAbilityActivationTime = -1; syncAbilityStateClear(playerData.player); } @@ -273,6 +284,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = null; currentAbilityKey = null; currentTarget = null; + lastAbilityActivationTime = -1; syncAbilityStateClear(playerData.player); } @@ -378,6 +390,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbilityKey = key; currentTarget = null; + lastAbilityActivationTime = getWorldTime(); return startChain((ChainedAbility) action, null); } @@ -413,6 +426,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = ability; currentAbilityKey = key; currentTarget = null; // Players don't have auto-targets + lastAbilityActivationTime = getWorldTime(); ability.start(null); if (ability.getPhase() == AbilityPhase.ACTIVE) { @@ -662,6 +676,38 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA interruptCurrentAbility(null, 0); } + /** + * Try to cancel the current ability via double-press. + * Only succeeds if within the cancel window and not in DAZED phase. + * Also handles cancellation during chain delay (between chain entries). + * + * @return true if the ability was cancelled + */ + public boolean tryCancelAbility() { + boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting(); + boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0; + + if (!hasExecutingAbility && !isInChainDelay) return false; + + // Don't allow cancel during DAZED + if (hasExecutingAbility) { + AbilityPhase phase = currentAbility.getPhase(); + if (phase == AbilityPhase.DAZED) return false; + if (phase != AbilityPhase.WINDUP && phase != AbilityPhase.ACTIVE + && phase != AbilityPhase.BURST_DELAY) return false; + } + + long worldTime = getWorldTime(); + if (lastAbilityActivationTime < 0 || (worldTime - lastAbilityActivationTime) > CANCEL_WINDOW_TICKS) { + // Outside cancel window — update time so a quick follow-up press can cancel + lastAbilityActivationTime = worldTime; + return false; + } + + cancelCurrentAbility(); + return true; + } + // ═══════════════════════════════════════════════════════════════════ // ENTITY RECONSTRUCTION RESET // ═══════════════════════════════════════════════════════════════════ @@ -701,6 +747,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = null; currentAbilityKey = null; currentTarget = null; + lastAbilityActivationTime = -1; if (clearCooldowns) { cooldownEndTime = 0; diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 8e2aa437c..dbe0442cd 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1674,6 +1674,8 @@ ability.weight=Weight ability.windUpTicks=Wind Up ability.cooldownTicks=Cooldown ability.perAbilityCooldown=Per-Ability +ability.freeOnCast=Free on Cast +ability.hover.freeOnCast=Ability enters cooldown immediately after entities are spawned, allowing the caster to use other abilities while summoned entities remain active ability.lockMovement=Lock Movement ability.rotationMode=Rotation ability.rotationPhase=Phase From 04679a34062b873c8854a7d5e147e169a7b883af Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 05:24:33 -0500 Subject: [PATCH 48/51] Disable Projectile and Slicer --- .../java/kamkeel/npcs/controllers/AbilityController.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 02c438e62..572303052 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -124,19 +124,23 @@ public class AbilityController implements IAbilityHandler { private void registerBuiltinTypes() { registerType("cnpc:slam", AbilitySlam::new); + registerType("cnpc:charge", AbilityCharge::new); + registerType("cnpc:heavy_hit", AbilityHeavyHit::new); registerType("cnpc:cutter", AbilityCutter::new); + // registerType("cnpc:projectile", AbilityProjectile::new); + registerType("cnpc:sweeper", AbilitySweeper::new); - registerType("cnpc:projectile", AbilityProjectile::new); registerType("cnpc:orb", AbilityOrb::new); registerType("cnpc:disc", AbilityDisc::new); registerType("cnpc:laser_shot", AbilityLaserShot::new); registerType("cnpc:beam", AbilityBeam::new); + // registerType("cnpc:slicer", AbilitySlicer::new); - registerType("cnpc:charge", AbilityCharge::new); registerType("cnpc:dash", AbilityDash::new); registerType("cnpc:teleport", AbilityTeleport::new); + registerType("cnpc:vortex", AbilityVortex::new); registerType("cnpc:shockwave", AbilityShockwave::new); @@ -149,7 +153,6 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:dome", AbilityDome::new); registerType("cnpc:wall", AbilityWall::new); registerType("cnpc:shield", AbilityShield::new); - registerType("cnpc:slicer", AbilitySlicer::new); } private void registerBuiltinConditionTypes() { From 72c6c004b0189f05df67172345c0d8423b2a7a9a Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 21 Feb 2026 11:58:53 -0300 Subject: [PATCH 49/51] Changed condition summary to use filter names --- .../controllers/data/ability/conditions/ConditionHasEffect.java | 2 +- .../controllers/data/ability/conditions/ConditionHitCount.java | 2 +- .../npcs/controllers/data/ability/conditions/ConditionItem.java | 2 +- .../data/ability/conditions/ConditionQuestCompleted.java | 2 +- .../controllers/data/ability/conditions/ConditionThreshold.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java index b0c3941ad..124b34bfb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java @@ -57,7 +57,7 @@ public class ConditionHasEffect extends AbilityCondition { @Override public String getConditionSummary() { - String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); String effectName = "None"; if (effectId >= 0) { CustomEffect effect = getEffect(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java index dbd71922b..8a326a16c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -60,7 +60,7 @@ public class ConditionHitCount extends AbilityCondition { @Override public String getConditionSummary() { - String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); return "[" + filterLabel + "] Hit " + requiredHits + " times in " + withinTicks + " ticks"; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java index 9bb445043..a137304ef 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -152,7 +152,7 @@ public class ConditionItem extends AbilityCondition { @Override public String getConditionSummary() { - String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); String usage = usageType.name(); String item = itemName.isEmpty() ? "None" : itemName; return "[" + filterLabel + "] " + usage + ": " + item; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java index 04c1ec16a..213358ca5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java @@ -52,7 +52,7 @@ public class ConditionQuestCompleted extends AbilityCondition { @Override public String getConditionSummary() { - String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); String questName = "None"; if (questId >= 0) { Quest q = QuestController.Instance.quests.get(questId); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java index fda42ce6a..aaa4a6b06 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java @@ -124,7 +124,7 @@ public abstract class ConditionThreshold extends AbilityCondition { @Override public String getConditionSummary() { - String filterLabel = StatCollector.translateToLocal("condition.filter." + getFilter().name().toLowerCase()); + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); String typeName = getStatName(); String typeLabel = StatCollector.translateToLocal(thresholdType.toString()); String value = percent From 7d5ad7abfe4f1f737d5e7af097ae2ad7f5f534e7 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 21 Feb 2026 13:21:16 -0300 Subject: [PATCH 50/51] Energy charge data for future implementation --- .../data/ability/data/EnergyChargingData.java | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java new file mode 100644 index 000000000..c12cec47f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java @@ -0,0 +1,83 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class EnergyChargingData { + + public int chargeDuration = 60; + public int chargeDelay = 0; + public int maxCharge = 100; + public boolean hasCharge = true; + public boolean chargeWindUpSync = true; + + public EnergyChargingData() { + } + + public EnergyChargingData(int chargeDuration, int chargeDelay, int maxCharge, boolean hasCharge, boolean chargeWindUpSync) { + this.chargeDuration = chargeDuration; + this.chargeDelay = chargeDelay; + this.maxCharge = maxCharge; + this.hasCharge = hasCharge; + this.chargeWindUpSync = chargeWindUpSync; + } + + public boolean hasCharge() { + return hasCharge; + } + + public void setHasCharge(boolean hasCharge) { + this.hasCharge = hasCharge; + } + + public boolean isChargeWindUpSync() { + return chargeWindUpSync; + } + + public void setChargeWindUpSync(boolean chargeWindUpSync) { + this.chargeWindUpSync = chargeWindUpSync; + } + + public int getChargeDuration() { + return chargeDuration; + } + + public void setChargeDuration(int chargeDuration) { + this.chargeDuration = chargeDuration; + } + + public int getChargeDelay() { + return chargeDelay; + } + + public void setChargeDelay(int chargeDelay) { + this.chargeDelay = chargeDelay; + } + + public int getMaxCharge() { + return maxCharge; + } + + public void setMaxCharge(int maxCharge) { + this.maxCharge = Math.max(0, maxCharge); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("chargeDuration", chargeDuration); + nbt.setInteger("chargeDelay", chargeDelay); + nbt.setInteger("maxCharge", maxCharge); + nbt.setBoolean("hasCharge", hasCharge); + nbt.setBoolean("chargeWindUpSync", chargeWindUpSync); + } + + public void readNBT(NBTTagCompound nbt) { + chargeDuration = nbt.hasKey("chargeDuration") ? nbt.getInteger("chargeDuration") : 60; + chargeDelay = nbt.hasKey("chargeDelay") ? nbt.getInteger("chargeDelay") : 0; + maxCharge = nbt.hasKey("maxCharge") ? nbt.getInteger("maxCharge") : 100; + hasCharge = !nbt.hasKey("hasCharge") || nbt.getBoolean("hasCharge"); + chargeWindUpSync = !nbt.hasKey("chargeWindUpSync") || nbt.getBoolean("chargeWindUpSync"); + } + + public EnergyChargingData copy() { + return new EnergyChargingData(chargeDuration, chargeDelay, maxCharge, hasCharge, chargeWindUpSync); + } +} From ecfedff9d26dc864652c789f7efa0a3f4bbf760e Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 21 Feb 2026 14:40:14 -0500 Subject: [PATCH 51/51] - Barrier Health Scaling with DBC Addon - Healing Health Scaling with DBC Addon - Ki Attacks collided with Barriers - Remove Ability Slot (Deprecated) - Refactored Naming Scheme for Barrier Abilities - Fixed Player Settings for Ignore Dex, DBC Stats, etc. --- ...EnergyDome.java => RenderAbilityDome.java} | 6 +- ...ergyPanel.java => RenderAbilityPanel.java} | 6 +- .../client/renderer/RenderEnergyBarrier.java | 4 +- .../npcs/controllers/AbilityController.java | 23 +++ .../controllers/data/ability/Ability.java | 22 +-- .../data/ability/AbilityAction.java | 2 +- .../controllers/data/ability/AbilitySlot.java | 163 ------------------ .../data/ability/IAbilityExtender.java | 28 +++ .../data/ability/type/AbilityEffect.java | 12 +- ...EnergyBarrier.java => AbilityBarrier.java} | 23 ++- .../data/ability/type/energy/AbilityDome.java | 10 +- .../ability/type/energy/AbilityShield.java | 12 +- .../data/ability/type/energy/AbilityWall.java | 16 +- ...Barrier.java => EntityAbilityBarrier.java} | 32 ++-- ...EnergyDome.java => EntityAbilityDome.java} | 12 +- .../npcs/entity/EntityAbilityLaser.java | 10 +- ...ergyPanel.java => EntityAbilityPanel.java} | 14 +- .../npcs/entity/EntityEnergyProjectile.java | 4 +- src/main/java/noppes/npcs/CustomNpcs.java | 11 +- .../java/noppes/npcs/ServerEventsHandler.java | 11 +- .../java/noppes/npcs/client/ClientProxy.java | 12 +- .../java/noppes/npcs/scripted/NpcAPI.java | 24 ++- .../scripted/entity/ScriptEnergyBarrier.java | 10 +- .../scripted/entity/ScriptEnergyDome.java | 4 +- .../scripted/entity/ScriptEnergyPanel.java | 6 +- 25 files changed, 201 insertions(+), 276 deletions(-) rename src/main/java/kamkeel/npcs/client/renderer/{RenderEnergyDome.java => RenderAbilityDome.java} (96%) rename src/main/java/kamkeel/npcs/client/renderer/{RenderEnergyPanel.java => RenderAbilityPanel.java} (96%) delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java rename src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/{AbilityEnergyBarrier.java => AbilityBarrier.java} (90%) rename src/main/java/kamkeel/npcs/entity/{EntityEnergyBarrier.java => EntityAbilityBarrier.java} (92%) rename src/main/java/kamkeel/npcs/entity/{EntityEnergyDome.java => EntityAbilityDome.java} (98%) rename src/main/java/kamkeel/npcs/entity/{EntityEnergyPanel.java => EntityAbilityPanel.java} (97%) diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java similarity index 96% rename from src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java index 3e05168d9..beebe98f3 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityDome; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; @@ -13,11 +13,11 @@ import org.lwjgl.opengl.GL11; * Optional skybox texture rendered on the interior surface. */ @SideOnly(Side.CLIENT) -public class RenderEnergyDome extends RenderEnergyBarrier { +public class RenderAbilityDome extends RenderEnergyBarrier { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { - EntityEnergyDome dome = (EntityEnergyDome) entity; + EntityAbilityDome dome = (EntityAbilityDome) entity; float radius = dome.getDomeRadius(); float healthPercent = dome.getHealthPercent(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java similarity index 96% rename from src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java index 24c9ea241..1261aaf1e 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; @@ -13,11 +13,11 @@ import org.lwjgl.opengl.GL11; * Voxel-blocky style with inner/outer layers. */ @SideOnly(Side.CLIENT) -public class RenderEnergyPanel extends RenderEnergyBarrier { +public class RenderAbilityPanel extends RenderEnergyBarrier { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { - EntityEnergyPanel panel = (EntityEnergyPanel) entity; + EntityAbilityPanel panel = (EntityAbilityPanel) entity; float width = panel.getPanelData().panelWidth; float height = panel.getPanelData().panelHeight; diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java index 6f4e1e89f..676440035 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityAbilityBarrier; /** * Intermediate renderer base for energy barrier entities (Dome, Panel). @@ -15,7 +15,7 @@ public abstract class RenderEnergyBarrier extends RenderEnergyAbility { * Compute the alpha boost from a hit flash effect. * Flash value decays from 4 to 0, producing alpha from 0.3 to 0. */ - protected float computeFlashAlpha(EntityEnergyBarrier barrier) { + protected float computeFlashAlpha(EntityAbilityBarrier barrier) { byte flash = barrier.getHitFlash(); if (flash <= 0) return 0.0f; return flash / 4.0f * 0.3f; diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 02c438e62..a908e77f2 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -1002,6 +1002,29 @@ public class AbilityController implements IAbilityHandler { return damage; } + /** + * Fire modifyBarrierHealth on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) { + float health = baseHealth; + for (IAbilityExtender ext : extenders) { + health = ext.modifyBarrierHealth(ability, caster, health); + } + return health; + } + + /** + * Fire onAbilityHeal on all extenders. Chain of responsibility — first true wins. + */ + public boolean fireOnAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) { + for (IAbilityExtender ext : extenders) { + if (ext.onAbilityHeal(ability, caster, target, healAmount)) { + return true; + } + } + return false; + } + // ═══════════════════════════════════════════════════════════════════════════ // IAbilityHandler // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index d7ca77eac..9d61188c5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -7,6 +7,9 @@ import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.telegraph.Telegraph; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -20,9 +23,6 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyDome; -import kamkeel.npcs.entity.EntityEnergyPanel; import noppes.npcs.DataAbilities; import noppes.npcs.NpcDamageSource; import noppes.npcs.api.INbt; @@ -2264,9 +2264,9 @@ public abstract class Ability implements IAbility, IAbilityAction { double maxZ = Math.max(caster.posZ, target.posZ) + searchRange; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - List barriers = world.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); + List barriers = world.getEntitiesWithinAABB(EntityAbilityBarrier.class, searchBox); - for (EntityEnergyBarrier barrier : barriers) { + for (EntityAbilityBarrier barrier : barriers) { if (barrier.isDead) continue; if (barrier.isCharging()) continue; @@ -2277,10 +2277,10 @@ public abstract class Ability implements IAbility, IAbilityAction { if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue; } - if (barrier instanceof EntityEnergyDome) { - if (isDomeBlocking((EntityEnergyDome) barrier, caster, target)) return true; - } else if (barrier instanceof EntityEnergyPanel) { - if (isPanelBlocking((EntityEnergyPanel) barrier, caster, target)) return true; + if (barrier instanceof EntityAbilityDome) { + if (isDomeBlocking((EntityAbilityDome) barrier, caster, target)) return true; + } else if (barrier instanceof EntityAbilityPanel) { + if (isPanelBlocking((EntityAbilityPanel) barrier, caster, target)) return true; } } @@ -2291,7 +2291,7 @@ public abstract class Ability implements IAbility, IAbilityAction { * Check if a dome blocks an attack from caster to target. * Blocks when caster is outside and target is inside the dome. */ - private static boolean isDomeBlocking(EntityEnergyDome dome, EntityLivingBase caster, EntityLivingBase target) { + private static boolean isDomeBlocking(EntityAbilityDome dome, EntityLivingBase caster, EntityLivingBase target) { float radius = dome.getDomeRadius(); double cdx = caster.posX - dome.posX; @@ -2312,7 +2312,7 @@ public abstract class Ability implements IAbility, IAbilityAction { * Check if a panel blocks an attack from caster to target. * Checks if the line from caster to target crosses through the panel bounds. */ - private static boolean isPanelBlocking(EntityEnergyPanel panel, EntityLivingBase caster, EntityLivingBase target) { + private static boolean isPanelBlocking(EntityAbilityPanel panel, EntityLivingBase caster, EntityLivingBase target) { float halfW = panel.getPanelData().panelWidth * 0.5f; float halfH = panel.getPanelData().panelHeight * 0.5f; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java index 77370b58c..60a64369d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java @@ -5,7 +5,7 @@ import net.minecraft.nbt.NBTTagCompound; /** * Unified slot for storing any combat action: inline ability, ability reference, or chain reference. - * Replaces {@link AbilitySlot} with support for all {@link IAbilityAction} types. + * Support for all {@link IAbilityAction} types. *

* References are lazy-resolved via their respective controllers and cached until * the controller revision changes. diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java deleted file mode 100644 index 1afbf0906..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java +++ /dev/null @@ -1,163 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import kamkeel.npcs.controllers.AbilityController; -import net.minecraft.nbt.NBTTagCompound; - -/** - * Wrapper that stores either an inline ability (full NBT) or a reference - * to a built-in/custom ability (by name or UUID). - *

- * References are lazy-resolved via {@link AbilityController#resolveAbility(String)} - * and cached until the controller version changes. - * - * @deprecated Use {@link AbilityAction} instead, which supports abilities and chained abilities. - */ -@Deprecated -public class AbilitySlot { - - private Ability inlineAbility; - private String referenceId; - - /** - * Per-slot enabled override for reference slots (null = use master's default). - */ - private Boolean enabledOverride; - - private transient Ability cachedAbility; - private transient int cachedVersion = -1; - - private AbilitySlot() { - } - - /** - * Create a slot with an inline (embedded) ability. - */ - public static AbilitySlot inline(Ability ability) { - AbilitySlot slot = new AbilitySlot(); - slot.inlineAbility = ability; - slot.referenceId = null; - return slot; - } - - /** - * Create a slot that references a built-in ability (by name) or custom ability (by name). - */ - public static AbilitySlot reference(String referenceId) { - AbilitySlot slot = new AbilitySlot(); - slot.inlineAbility = null; - slot.referenceId = referenceId; - return slot; - } - - public boolean isReference() { - return referenceId != null; - } - - public String getReferenceId() { - return referenceId; - } - - /** - * Get the resolved ability. For inline slots, returns the ability directly. - * For reference slots, lazily resolves from AbilityController and caches. - * Returns null if the reference cannot be resolved (broken ref). - */ - public Ability getAbility() { - if (!isReference()) { - return inlineAbility; - } - - // Lazy resolve with version-based cache invalidation - AbilityController controller = AbilityController.Instance; - if (controller == null) return null; - - int currentVersion = controller.getCustomAbilityRevision(); - if (cachedAbility != null && cachedVersion == currentVersion) { - return cachedAbility; - } - - cachedAbility = controller.resolveAbility(referenceId); - // Apply per-slot enabled override so NPC-specific enable/disable persists - if (cachedAbility != null && enabledOverride != null) { - cachedAbility.setEnabled(enabledOverride); - } - cachedVersion = currentVersion; - return cachedAbility; - } - - /** - * Set the per-slot enabled override for reference slots. - * For inline slots, delegates directly to the ability. - */ - public void setEnabled(boolean enabled) { - if (!isReference()) { - if (inlineAbility != null) { - inlineAbility.setEnabled(enabled); - } - } else { - this.enabledOverride = enabled; - // Also update the cached ability immediately if present - if (cachedAbility != null) { - cachedAbility.setEnabled(enabled); - } - } - } - - /** - * Get the inline ability directly (null for reference slots). - */ - public Ability getInlineAbility() { - return inlineAbility; - } - - /** - * Convert this reference slot to an inline slot by copying the resolved ability. - * No-op if already inline. Returns false if resolution fails. - */ - public boolean convertToInline() { - if (!isReference()) return true; - - Ability resolved = getAbility(); - if (resolved == null) return false; - - // Deep copy via NBT round-trip - inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT()); - referenceId = null; - cachedAbility = null; - cachedVersion = -1; - return true; - } - - // ═══════════════════════════════════════════════════════════════════ - // NBT - // ═══════════════════════════════════════════════════════════════════ - - public NBTTagCompound writeNBT() { - if (isReference()) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("Reference", referenceId); - if (enabledOverride != null) { - nbt.setBoolean("RefEnabled", enabledOverride); - } - return nbt; - } - return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound(); - } - - public static AbilitySlot fromNBT(NBTTagCompound nbt) { - if (nbt == null) return null; - - if (nbt.hasKey("Reference")) { - AbilitySlot slot = reference(nbt.getString("Reference")); - if (nbt.hasKey("RefEnabled")) { - slot.enabledOverride = nbt.getBoolean("RefEnabled"); - } - return slot; - } - - // Inline ability - Ability ability = AbilityController.Instance.fromNBT(nbt); - if (ability == null) return null; - return inline(ability); - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java index 2bb179cc2..f3e7ccfd8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java @@ -87,4 +87,32 @@ public interface IAbilityExtender { default float modifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { return baseDamage; } + + /** + * Called when a barrier entity is about to be created, allowing extenders to modify its max health. + * Cumulative: all extenders apply in sequence, each receiving the previous output. + * + * @param ability The barrier ability being executed + * @param caster The entity creating the barrier + * @param baseHealth The base max health from EnergyBarrierData.maxHealth + * @return The modified max health value + */ + default float modifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) { + return baseHealth; + } + + /** + * Called when an ability is about to heal an entity. + * Return true to handle the healing (skip default entity.heal()). + * Chain of responsibility: first returning true wins. + * + * @param ability The ability performing the heal + * @param caster The entity casting the ability + * @param target The entity being healed + * @param healAmount The heal amount calculated by the ability + * @return true if healing was handled (skip default), false to pass to next extender or default + */ + default boolean onAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) { + return false; + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java index c81e97ced..d4f9c474b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java @@ -131,7 +131,7 @@ public class AbilityEffect extends Ability implements IAbilityEffect { if (instantHeal) { for (EntityLivingBase entity : getAffectedEntities()) { - healEntity(entity); + healEntity(caster, entity); applyAllEffects(caster, entity); spawnHealParticles(caster.worldObj, entity); } @@ -159,7 +159,9 @@ public class AbilityEffect extends Ability implements IAbilityEffect { } if (totalTickHeal > 0) { - entity.heal(totalTickHeal); + if (!AbilityController.Instance.fireOnAbilityHeal(this, caster, entity, totalTickHeal)) { + entity.heal(totalTickHeal); + } } if (tick % 20 == 0) { @@ -226,13 +228,15 @@ public class AbilityEffect extends Ability implements IAbilityEffect { } } - private void healEntity(EntityLivingBase entity) { + private void healEntity(EntityLivingBase caster, EntityLivingBase entity) { float totalHeal = healAmount; if (healPercent > 0) { totalHeal += entity.getMaxHealth() * healPercent; } if (totalHeal > 0) { - entity.heal(totalHeal); + if (!AbilityController.Instance.fireOnAbilityHeal(this, caster, entity, totalHeal)) { + entity.heal(totalHeal); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java similarity index 90% rename from src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java index 3366290e9..841750d1c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java @@ -2,9 +2,10 @@ package kamkeel.npcs.controllers.data.ability.type.energy; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; -import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityAbilityBarrier; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; @@ -16,14 +17,14 @@ import java.util.List; * Abstract base for energy barrier abilities (Dome, Wall, Shield). * Handles shared visual data, barrier configuration, and lifecycle management. */ -public abstract class AbilityEnergyBarrier extends AbilityEnergy { +public abstract class AbilityBarrier extends AbilityEnergy { protected final EnergyBarrierData barrierData; // Runtime entity tracking - protected transient EntityEnergyBarrier barrierEntity; + protected transient EntityAbilityBarrier barrierEntity; - protected AbilityEnergyBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) { + protected AbilityBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) { super(displayData); this.barrierData = barrierData; } @@ -33,7 +34,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { /** * Create and spawn the barrier entity during execution. */ - protected abstract EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); + protected abstract EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); /** * Add type-specific GUI field definitions. @@ -80,6 +81,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { if (tick == 1) { barrierEntity = createBarrierEntity(caster, target); if (barrierEntity != null) { + applyBarrierHealthModifiers(caster); barrierEntity.setupCharging(getWindUpTicks()); spawnAbilityEntity(barrierEntity); } @@ -95,6 +97,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { // No windup or entity died — create fresh barrierEntity = createBarrierEntity(caster, target); if (barrierEntity != null) { + applyBarrierHealthModifiers(caster); spawnAbilityEntity(barrierEntity); } } @@ -124,6 +127,16 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { public void onComplete(EntityLivingBase caster, EntityLivingBase target) { } + /** + * Allow extenders to modify the barrier's max health at spawn time. + */ + private void applyBarrierHealthModifiers(EntityLivingBase caster) { + float modHealth = AbilityController.Instance.fireModifyBarrierHealth(this, caster, barrierData.maxHealth); + if (modHealth != barrierData.maxHealth) { + barrierEntity.setBarrierMaxHealth(modHealth); + } + } + @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { cleanup(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java index 78a317cc2..1663f2447 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -8,8 +8,8 @@ import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -22,7 +22,7 @@ import java.util.List; * Blocks incoming energy projectiles with configurable damage multipliers. * Duration and/or HP based. */ -public class AbilityDome extends AbilityEnergyBarrier { +public class AbilityDome extends AbilityBarrier { private float domeRadius = 5.0f; private boolean followCaster = false; @@ -47,8 +47,8 @@ public class AbilityDome extends AbilityEnergyBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { - EntityEnergyDome dome = new EntityEnergyDome( + protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + EntityAbilityDome dome = new EntityAbilityDome( caster.worldObj, caster, caster.posX, caster.posY, caster.posZ, domeRadius, displayData.copy(), lightningData.copy(), barrierData.copy() diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java index f19f9844f..2d9c515a4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java @@ -10,8 +10,8 @@ import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyPanelData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -24,7 +24,7 @@ import java.util.List; * The shield follows the caster's position and rotates with their look direction. * Cannot be placed — it's always held. */ -public class AbilityShield extends AbilityEnergyBarrier { +public class AbilityShield extends AbilityBarrier { private float shieldWidth = 2.5f; private float shieldHeight = 2.5f; @@ -50,7 +50,7 @@ public class AbilityShield extends AbilityEnergyBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, 0.0f); float frontDist = 1.5f; @@ -59,10 +59,10 @@ public class AbilityShield extends AbilityEnergyBarrier { double spawnY = caster.posY + (caster.height * 0.5f); double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist); - EntityEnergyPanel panel = new EntityEnergyPanel( + EntityAbilityPanel panel = new EntityAbilityPanel( caster.worldObj, caster, spawnX, spawnY, spawnZ, caster.rotationYaw, - EntityEnergyPanel.PanelMode.HELD, + EntityAbilityPanel.PanelMode.HELD, displayData.copy(), lightningData.copy(), barrierData.copy(), panelData ); panel.setSourceAbility(this); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java index 4320177c1..5237485b8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java @@ -9,8 +9,8 @@ import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyPanelData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -23,7 +23,7 @@ import java.util.List; * Can float above ground (configurable height offset). * Optional launching mode fires the wall forward with damage/knockback. */ -public class AbilityWall extends AbilityEnergyBarrier { +public class AbilityWall extends AbilityBarrier { private final EnergyPanelData panelData; @@ -55,7 +55,7 @@ public class AbilityWall extends AbilityEnergyBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { // Place wall between caster and target double placeX, placeY, placeZ; float yaw; @@ -87,11 +87,11 @@ public class AbilityWall extends AbilityEnergyBarrier { yaw = caster.rotationYaw; } - EntityEnergyPanel.PanelMode mode = panelData.launching - ? EntityEnergyPanel.PanelMode.LAUNCHED - : EntityEnergyPanel.PanelMode.PLACED; + EntityAbilityPanel.PanelMode mode = panelData.launching + ? EntityAbilityPanel.PanelMode.LAUNCHED + : EntityAbilityPanel.PanelMode.PLACED; - EntityEnergyPanel panel = new EntityEnergyPanel( + EntityAbilityPanel panel = new EntityAbilityPanel( caster.worldObj, caster, placeX, placeY, placeZ, yaw, mode, displayData.copy(), lightningData.copy(), barrierData.copy(), panelData.copy() diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java similarity index 92% rename from src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java rename to src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java index 2db51fd14..02fbbdc4e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java @@ -22,24 +22,24 @@ import java.util.List; * and barrier lifecycle management. * Extends EntityEnergyAbility for shared visual/owner/charging state. */ -public abstract class EntityEnergyBarrier extends EntityEnergyAbility { +public abstract class EntityAbilityBarrier extends EntityEnergyAbility { // ==================== ACTIVE BARRIER REGISTRY ==================== - private static final List> activeBarriers = new ArrayList<>(); + private static final List> activeBarriers = new ArrayList<>(); private boolean tracked = false; - public static void trackBarrier(EntityEnergyBarrier barrier) { + public static void trackBarrier(EntityAbilityBarrier barrier) { activeBarriers.add(new WeakReference<>(barrier)); } /** * Get all living barriers in the given world. Auto-cleans dead refs. */ - public static List getActiveBarriers(World world) { - List result = new ArrayList<>(); - Iterator> it = activeBarriers.iterator(); + public static List getActiveBarriers(World world) { + List result = new ArrayList<>(); + Iterator> it = activeBarriers.iterator(); while (it.hasNext()) { - EntityEnergyBarrier b = it.next().get(); + EntityAbilityBarrier b = it.next().get(); if (b == null || b.isDead) { it.remove(); } else if (b.worldObj == world) { @@ -62,7 +62,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { protected static final int DW_HEALTH_PERCENT = 21; protected static final int DW_HIT_FLASH = 22; - public EntityEnergyBarrier(World world) { + public EntityAbilityBarrier(World world) { super(world); this.noClip = true; } @@ -358,10 +358,10 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { * Find a barrier that would absorb damage for the given entity (its caster). * Returns the barrier if: absorbing is enabled AND entity is the barrier's owner. */ - public static EntityEnergyBarrier getAbsorbingBarrier(Entity entity) { + public static EntityAbilityBarrier getAbsorbingBarrier(Entity entity) { if (entity == null || entity.worldObj == null) return null; - List barriers = getActiveBarriers(entity.worldObj); - for (EntityEnergyBarrier barrier : barriers) { + List barriers = getActiveBarriers(entity.worldObj); + for (EntityAbilityBarrier barrier : barriers) { if (barrier.isDead) continue; if (!barrier.barrierData.absorbing) continue; if (barrier.ownerEntityId == entity.getEntityId()) { @@ -425,6 +425,16 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { syncHealthPercent(); } + /** + * Override the barrier's max health and set current health to match. + * Used by extenders (e.g., DBC scaling) to dynamically set barrier HP at spawn time. + */ + public void setBarrierMaxHealth(float maxHealth) { + this.barrierData.setMaxHealth(maxHealth); + this.currentHealth = maxHealth; + syncHealthPercent(); + } + public int getTicksAlive() { return ticksAlive; } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java similarity index 98% rename from src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java rename to src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java index 68fa9ec8b..149475d0d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java @@ -22,9 +22,9 @@ import java.util.List; * Energy Dome entity - a spherical barrier that blocks incoming energy projectiles. * Centered on the caster's position at time of casting. * Only blocks incoming attacks (not outgoing from allies inside). - * Extends EntityEnergyBarrier for shared barrier logic. + * Extends EntityAbilityBarrier for shared barrier logic. */ -public class EntityEnergyDome extends EntityEnergyBarrier { +public class EntityAbilityDome extends EntityAbilityBarrier { // ==================== DOME-SPECIFIC PROPERTIES ==================== protected float domeRadius = 5.0f; @@ -35,16 +35,16 @@ public class EntityEnergyDome extends EntityEnergyBarrier { private boolean inTickMelee = false; private final HashSet processedMeleeSwings = new HashSet<>(); - public EntityEnergyDome(World world) { + public EntityAbilityDome(World world) { super(world); this.noClip = true; this.stepHeight = 0.0F; this.setSize(1.0f, 1.0f); } - public EntityEnergyDome(World world, EntityLivingBase owner, double x, double y, double z, - float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, - EnergyBarrierData barrier) { + public EntityAbilityDome(World world, EntityLivingBase owner, double x, double y, double z, + float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier) { this(world); this.noClip = true; this.stepHeight = 0.0F; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 8f9df2bb5..6a568a89d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -382,8 +382,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { protected boolean checkBarrierCollision() { if (currentLength <= 0 || fullyExtended) return false; - List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); - for (EntityEnergyBarrier barrier : barriers) { + List barriers = EntityAbilityBarrier.getActiveBarriers(worldObj); + for (EntityAbilityBarrier barrier : barriers) { if (barrier.isDead || barrier.isCharging()) continue; if (barrier.getOwnerEntityId() == this.ownerEntityId) continue; @@ -396,8 +396,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { } } - if (barrier instanceof EntityEnergyDome) { - EntityEnergyDome dome = (EntityEnergyDome) barrier; + if (barrier instanceof EntityAbilityDome) { + EntityAbilityDome dome = (EntityAbilityDome) barrier; float intersectDist = getLineSphereIntersection(dome); if (intersectDist >= 0) { // Truncate laser at dome surface @@ -431,7 +431,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { * Returns the distance along the laser direction to the first entry point, * or -1 if no intersection from outside. */ - private float getLineSphereIntersection(EntityEnergyDome dome) { + private float getLineSphereIntersection(EntityAbilityDome dome) { double cx = dome.posX; double cy = dome.posY; double cz = dome.posZ; diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java similarity index 97% rename from src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java rename to src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java index 1afc1f2bc..f1a89012e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java @@ -22,9 +22,9 @@ import java.util.List; /** * Energy Panel entity - a flat rectangular barrier used by Wall and Shield abilities. * Supports three modes: PLACED (stationary), HELD (tracks caster), LAUNCHED (moves forward). - * Extends EntityEnergyBarrier for shared barrier logic. + * Extends EntityAbilityBarrier for shared barrier logic. */ -public class EntityEnergyPanel extends EntityEnergyBarrier { +public class EntityAbilityPanel extends EntityAbilityBarrier { public enum PanelMode { PLACED, // Stationary wall @@ -42,15 +42,15 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { protected float targetPanelWidth; protected float targetPanelHeight; - public EntityEnergyPanel(World world) { + public EntityAbilityPanel(World world) { super(world); this.setSize(0.5f, 0.5f); } - public EntityEnergyPanel(World world, EntityLivingBase owner, double x, double y, double z, - float yaw, PanelMode mode, - EnergyDisplayData display, EnergyLightningData lightning, - EnergyBarrierData barrier, EnergyPanelData panel) { + public EntityAbilityPanel(World world, EntityLivingBase owner, double x, double y, double z, + float yaw, PanelMode mode, + EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier, EnergyPanelData panel) { this(world); this.setPosition(x, y + panel.heightOffset, z); this.ownerEntityId = owner.getEntityId(); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index f3a203001..5e48a468f 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -318,8 +318,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { * @return true if projectile was absorbed (caller should stop processing) */ protected boolean checkBarrierCollision() { - List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); - for (EntityEnergyBarrier barrier : barriers) { + List barriers = EntityAbilityBarrier.getActiveBarriers(worldObj); + for (EntityAbilityBarrier barrier : barriers) { if (barrier.isDead) continue; // Quick distance pre-filter diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 5cdd71bff..d7f951b1e 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -28,14 +28,15 @@ import kamkeel.npcs.controllers.SyncController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.controllers.data.profile.CNPCData; import kamkeel.npcs.developer.Developer; +import kamkeel.npcs.entity.EntityAbilityBarrier; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityAbilityPanel; import kamkeel.npcs.entity.EntityAbilitySweeper; import kamkeel.npcs.entity.EntityAbilityZone; -import kamkeel.npcs.entity.EntityEnergyDome; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityDome; import kamkeel.npcs.entity.EntityEnergySlicer; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.util.BukkitUtil; @@ -297,8 +298,8 @@ public class CustomNpcs { registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 3, true); registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true); registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true); - registerNewEntity(EntityEnergyDome.class, "energydome", 64, 3, true); - registerNewEntity(EntityEnergyPanel.class, "energypanel", 64, 3, true); + registerNewEntity(EntityAbilityDome.class, "energydome", 64, 3, true); + registerNewEntity(EntityAbilityPanel.class, "energypanel", 64, 3, true); registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 3, true); new RecipeController(); @@ -430,7 +431,7 @@ public class CustomNpcs { } kamkeel.npcs.entity.EntityEnergyProjectile.clearAllProjectiles(); - kamkeel.npcs.entity.EntityEnergyBarrier.clearAllBarriers(); + EntityAbilityBarrier.clearAllBarriers(); if (FMLCommonHandler.instance().getSide().isClient()) clientJaninoCompiler = null; diff --git a/src/main/java/noppes/npcs/ServerEventsHandler.java b/src/main/java/noppes/npcs/ServerEventsHandler.java index a13384ada..0f9fa1d3e 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -4,6 +4,8 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; import kamkeel.npcs.network.enums.EnumSyncAction; @@ -30,7 +32,6 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.village.MerchantRecipeList; import net.minecraftforge.event.entity.EntityJoinWorldEvent; -import kamkeel.npcs.entity.EntityEnergyBarrier; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; @@ -157,7 +158,7 @@ public class ServerEventsHandler { if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote) return; - EntityEnergyBarrier barrier = EntityEnergyBarrier.getAbsorbingBarrier(event.entityLiving); + EntityAbilityBarrier barrier = EntityAbilityBarrier.getAbsorbingBarrier(event.entityLiving); if (barrier != null) { // Redirect the caster's damage to their barrier barrier.absorbDamage(event.ammount); @@ -189,9 +190,9 @@ public class ServerEventsHandler { } if (!blacklisted) return; - List barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj); - for (EntityEnergyBarrier barrier : barriers) { - if (barrier instanceof kamkeel.npcs.entity.EntityEnergyDome && barrier.isEntityInside(player)) { + List barriers = EntityAbilityBarrier.getActiveBarriers(player.worldObj); + for (EntityAbilityBarrier barrier : barriers) { + if (barrier instanceof EntityAbilityDome && barrier.isEntityInside(player)) { event.setCanceled(true); return; } diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index c0a113a96..a221e35ae 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -12,8 +12,8 @@ import kamkeel.npcs.client.renderer.RenderAbilityLaser; import kamkeel.npcs.client.renderer.RenderAbilityOrb; import kamkeel.npcs.client.renderer.RenderAbilitySweeper; import kamkeel.npcs.client.renderer.RenderAbilityZone; -import kamkeel.npcs.client.renderer.RenderEnergyDome; -import kamkeel.npcs.client.renderer.RenderEnergyPanel; +import kamkeel.npcs.client.renderer.RenderAbilityDome; +import kamkeel.npcs.client.renderer.RenderAbilityPanel; import kamkeel.npcs.client.renderer.RenderEnergySlicer; import kamkeel.npcs.client.renderer.TelegraphRenderer; import kamkeel.npcs.client.renderer.lightning.LightningHandler; @@ -24,8 +24,8 @@ import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; import kamkeel.npcs.entity.EntityAbilitySweeper; import kamkeel.npcs.entity.EntityAbilityZone; -import kamkeel.npcs.entity.EntityEnergyDome; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityAbilityPanel; import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; @@ -278,8 +278,8 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone()); - RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome()); - RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDome.class, new RenderAbilityDome()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityPanel.class, new RenderAbilityPanel()); RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer()); RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc()); diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index aebc9321d..8cb554c3e 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -9,9 +9,13 @@ import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityDome; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityAbilitySweeper; import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.block.Block; import net.minecraft.command.CommandHandler; import net.minecraft.entity.Entity; @@ -126,9 +130,13 @@ import noppes.npcs.scripted.entity.ScriptArrow; import noppes.npcs.scripted.entity.ScriptDBCPlayer; import noppes.npcs.scripted.entity.ScriptEnergyBeam; import noppes.npcs.scripted.entity.ScriptEnergyDisc; +import noppes.npcs.scripted.entity.ScriptEnergyDome; import noppes.npcs.scripted.entity.ScriptEnergyLaser; import noppes.npcs.scripted.entity.ScriptEnergyOrb; +import noppes.npcs.scripted.entity.ScriptEnergyPanel; import noppes.npcs.scripted.entity.ScriptEnergyProjectile; +import noppes.npcs.scripted.entity.ScriptEnergySlicer; +import noppes.npcs.scripted.entity.ScriptEnergySweeper; import noppes.npcs.scripted.entity.ScriptEntity; import noppes.npcs.scripted.entity.ScriptEntityItem; import noppes.npcs.scripted.entity.ScriptFishHook; @@ -472,16 +480,16 @@ public class NpcAPI extends AbstractNpcAPI { data = new ScriptEntityData(new ScriptEnergyDisc<>((EntityAbilityDisc) entity)); else if (entity instanceof EntityAbilityLaser) data = new ScriptEntityData(new ScriptEnergyLaser<>((EntityAbilityLaser) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityEnergySlicer) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergySlicer<>((kamkeel.npcs.entity.EntityEnergySlicer) entity)); + else if (entity instanceof EntityEnergySlicer) + data = new ScriptEntityData(new ScriptEnergySlicer<>((EntityEnergySlicer) entity)); else if (entity instanceof EntityEnergyProjectile) data = new ScriptEntityData(new ScriptEnergyProjectile((EntityEnergyProjectile) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityEnergyDome) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergyDome<>((kamkeel.npcs.entity.EntityEnergyDome) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityEnergyPanel) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergyPanel<>((kamkeel.npcs.entity.EntityEnergyPanel) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityAbilitySweeper) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergySweeper<>((kamkeel.npcs.entity.EntityAbilitySweeper) entity)); + else if (entity instanceof EntityAbilityDome) + data = new ScriptEntityData(new ScriptEnergyDome<>((EntityAbilityDome) entity)); + else if (entity instanceof EntityAbilityPanel) + data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityAbilityPanel) entity)); + else if (entity instanceof EntityAbilitySweeper) + data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityAbilitySweeper) entity)); else data = new ScriptEntityData(new ScriptEntity<>(entity)); entity.registerExtendedProperties("ScriptedObject", data); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java index 6669bde50..a015a06ad 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java @@ -1,15 +1,15 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; import noppes.npcs.api.entity.IEnergyBarrier; import noppes.npcs.scripted.constants.EntityType; /** * Base script wrapper for energy barrier entities (Dome, Panel). - * All shared methods delegate directly to EntityEnergyBarrier base. + * All shared methods delegate directly to EntityAbilityBarrier base. */ -public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { +public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { public ScriptEnergyBarrier(T entity) { super(entity); @@ -122,6 +122,6 @@ public class ScriptEnergyBarrier extends ScriptEn } public int getBarrierType() { - return entity instanceof EntityEnergyDome ? 0 : 1; + return entity instanceof EntityAbilityDome ? 0 : 1; } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java index e022118f7..9bcceefbc 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java @@ -1,10 +1,10 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityDome; import noppes.npcs.api.entity.IEnergyDome; import noppes.npcs.scripted.constants.EntityType; -public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { +public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { public ScriptEnergyDome(T entity) { super(entity); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java index 04c730fad..fa929b4a8 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java @@ -1,10 +1,10 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityPanel; import noppes.npcs.api.entity.IEnergyPanel; import noppes.npcs.scripted.constants.EntityType; -public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { +public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { public ScriptEnergyPanel(T entity) { super(entity); @@ -52,6 +52,6 @@ public class ScriptEnergyPanel extends ScriptEnergy } public boolean isLaunched() { - return entity.getMode() == EntityEnergyPanel.PanelMode.LAUNCHED; + return entity.getMode() == EntityAbilityPanel.PanelMode.LAUNCHED; } }