From 1b755d7c87ce31dde8693d747c320a16f7db8fcf Mon Sep 17 00:00:00 2001 From: Vidal Date: Mon, 26 Jan 2026 00:48:31 -0300 Subject: [PATCH 01/76] part 3? --- src/api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api b/src/api index 2e5d86993..da15a3662 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 2e5d86993cd47e6df4572323514d4fe2166c570c +Subproject commit da15a36624c4b05b0aad02d107345cba1a0d6d50 From 2ba3bd214899cfaffce2e5eac85af73915e686f8 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sun, 1 Feb 2026 06:06:14 -0300 Subject: [PATCH 02/76] Added a bunch of ki-based abilities --- gradle-plugins | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle-plugins b/gradle-plugins index bfa9565fc..45dbf494c 160000 --- a/gradle-plugins +++ b/gradle-plugins @@ -1 +1 @@ -Subproject commit bfa9565fce3110adb8fb4e9fd1a52bafdd7d35e6 +Subproject commit 45dbf494ca06f58efa8d6f2f9d1a138a3ee573f8 From 45a4313b70c344097763ac6d3c8d16c0b8e6a429 Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 4 Feb 2026 21:50:39 -0500 Subject: [PATCH 03/76] Enhance ability system with position locking and duplicate name confirmation for presets --- src/main/java/kamkeel/npcs/util/Register.java | 4 +- src/main/java/noppes/npcs/DataAbilities.java | 113 +++++++++++++++++- .../client/gui/advanced/GuiNPCAbilities.java | 62 +++++++--- .../advanced/SubGuiAbilitySaveConfirm.java | 39 ++++-- .../gui/advanced/SubGuiAbilityTypeSelect.java | 54 +++++++-- .../advanced/SubGuiDuplicateNameConfirm.java | 47 ++++++++ .../gui/global/GuiNpcManageAbilities.java | 80 +++++++++++-- .../client/gui/util/GuiAbilityInterface.java | 3 + .../npcs/entity/EntityNPCInterface.java | 3 +- .../assets/customnpcs/lang/en_US.lang | 2 + 10 files changed, 351 insertions(+), 56 deletions(-) create mode 100644 src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index 69dbd1991..c97188316 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -11,6 +11,7 @@ import java.util.function.Supplier; public class Register { public static final Map> REGISTERED_NAMESPACES = new LinkedHashMap<>(); + public static final Map NAMESPACE_DISPLAY_NAMES = new LinkedHashMap<>(); private final String registryKey; protected final String namespace; protected final Map> entries = new LinkedHashMap<>(); @@ -71,7 +72,7 @@ public class Register { } } - public static Register.Abilities create(String namespace) { + public static Register.Abilities create(String namespace, String displayName) { if (!REGISTERED_NAMESPACES.containsKey("ability")) REGISTERED_NAMESPACES.put("ability", new ArrayList<>()); @@ -80,6 +81,7 @@ public class Register { } REGISTERED_NAMESPACES.get("ability").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); return new Register.Abilities(namespace); } diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 3f8cb5357..cb83caae2 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -44,7 +44,7 @@ public class DataAbilities { /** * Whether the ability system is enabled for this NPC */ - public boolean enabled = false; + public boolean enabled = true; /** * Minimum cooldown ticks between abilities (global minimum) @@ -90,6 +90,16 @@ public class DataAbilities { private transient float lockedRenderYawOffset = 0; private transient float lockedPitch = 0; + /** + * Locked position values for movement lock. + * Stored when entering a locked phase, applied after super.onLivingUpdate() + * to override any position changes from AI/physics. + */ + private transient boolean positionLocked = false; + private transient double lockedPosX = 0; + private transient double lockedPosY = 0; + private transient double lockedPosZ = 0; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -150,15 +160,22 @@ public class DataAbilities { // Handle rotation lock transition from WINDUP to ACTIVE if (currentAbility.isRotationLockedDuringActive()) { - // ACTIVE or WINDUP_AND_ACTIVE: capture (or keep) rotation lock if (!rotationLocked) { captureLockedRotation(); } } else if (rotationLocked) { - // WINDUP only: release the lock now that windup is over releaseLockedRotation(); } + // Handle position lock transition from WINDUP to ACTIVE + if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { + if (!positionLocked) { + captureLockedPosition(); + } + } else if (positionLocked) { + releaseLockedPosition(); + } + // Play active sound and animation playAbilitySound(currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); @@ -243,8 +260,9 @@ public class DataAbilities { npc.wrappedNPC, currentAbility, target); NpcAPI.EVENT_BUS.post(completeEvent); - // Release rotation lock before cleanup + // Release locks before cleanup releaseLockedRotation(); + releaseLockedPosition(); // Clean up and roll cooldown (this sets currentAbility to null) onAbilityComplete(); @@ -259,8 +277,9 @@ public class DataAbilities { // Stop any ability animation stopAbilityAnimation(); - // Release rotation lock + // Release locks releaseLockedRotation(); + releaseLockedPosition(); // Calculate cooldown: random(min, max) + ability offset int abilityCooldownOffset = currentAbility.getCooldownTicks(); @@ -399,6 +418,9 @@ public class DataAbilities { if (ability.isRotationLockedDuringWindup()) { captureLockedRotation(); } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } spawnTelegraph(ability, target); playAbilitySound(ability.getWindUpSound()); playAbilityAnimation(ability.getWindUpAnimation()); @@ -416,6 +438,9 @@ public class DataAbilities { if (ability.isRotationLockedDuringActive()) { captureLockedRotation(); } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } // Play active sound and animation playAbilitySound(ability.getActiveSound()); @@ -625,8 +650,9 @@ public class DataAbilities { // Stop any ability animation stopAbilityAnimation(); - // Release rotation lock + // Release locks releaseLockedRotation(); + releaseLockedPosition(); // Fire interrupt event AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent( @@ -649,6 +675,7 @@ public class DataAbilities { removeTelegraph(currentAbility); stopAbilityAnimation(); releaseLockedRotation(); + releaseLockedPosition(); currentAbility.interrupt(); currentAbility = null; lastTarget = null; @@ -1027,6 +1054,80 @@ public class DataAbilities { return rotationLocked; } + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** Bit flag for position lock in the existing data watcher slot 15 bitfield */ + private static final int POSITION_LOCKED_FLAG = 32; + + /** + * Capture current position to lock NPC in place. + * Called when entering a phase with movement lock. + */ + private void captureLockedPosition() { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + npc.setBoolFlag(true, POSITION_LOCKED_FLAG); + } + + /** + * Release the position lock. + * Called when leaving the locked phase or ability completes. + */ + private void releaseLockedPosition() { + positionLocked = false; + npc.setBoolFlag(false, POSITION_LOCKED_FLAG); + } + + /** + * Apply locked position values to the NPC. + * Called AFTER super.onLivingUpdate() in EntityNPCInterface to override + * any position changes from AI pathfinding, physics, or entity collisions. + * Runs on both client and server. + */ + public void applyLockedPosition() { + if (npc.worldObj.isRemote) { + // Client-side: check flag via data watcher + boolean flagActive = npc.getBoolFlag(POSITION_LOCKED_FLAG); + if (!flagActive) { + positionLocked = false; + return; + } + // First tick the flag is active: capture current position + if (!positionLocked) { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + } + // Snap position back and set prev to prevent interpolation jitter + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; + return; + } + + // Server-side: use stored locked values + if (!positionLocked) { + return; + } + + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; + } + // ═══════════════════════════════════════════════════════════════════ // NBT SERIALIZATION // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index e86370492..998473623 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -7,6 +7,7 @@ import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; @@ -57,6 +58,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC private String search = ""; private int selectedAbilityIndex = -1; + // Existing preset names for duplicate checking + private final Set existingPresetNames = new HashSet<>(); + public static int modIndex = 0; public static ScrollType scrollType = ScrollType.CNPC; @@ -64,6 +68,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC super(npc); PacketClient.sendClient(new AbilitiesGetAllPacket()); PacketClient.sendClient(new AbilitiesNpcGetPacket()); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); } public enum ScrollType { @@ -79,7 +84,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (Register.isEmpty("ability")) return "modded"; - return Register.REGISTERED_NAMESPACES.get("ability").get(modIndex); + String namespace = Register.REGISTERED_NAMESPACES.get("ability").get(modIndex); + String displayName = Register.NAMESPACE_DISPLAY_NAMES.get(namespace); + return displayName != null ? displayName : namespace; case ALL: return "filter.all"; default: return name(); } @@ -92,38 +99,38 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC int y = guiTop + 10; - // Enabled checkbox - addLabel(new GuiNpcLabel(100, "gui.enabled", guiLeft + 5, y + 5)); - addButton(new GuiNpcButton(100, guiLeft + 55, y, 50, 20, new String[]{"gui.no", "gui.yes"}, abilitiesEnabled ? 1 : 0)); + addButton(new GuiNpcButton(50, guiLeft + 5, y, 140, 20, scrollType.toString())); // Cooldown range: Min Cooldown and Max Cooldown (spaced apart more) - addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 115, y + 5)); - GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 165, y, 40, 20, "" + minCooldown); + addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 210, y + 5)); + GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 260, y, 40, 20, "" + minCooldown); minField.setIntegersOnly(); minField.setMinMaxDefault(0, 10000, 20); addTextField(minField); - addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 260, y + 5)); - GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 310, y, 40, 20, "" + maxCooldown); + addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 320, y + 5)); + GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 370, y, 40, 20, "" + maxCooldown); maxField.setIntegersOnly(); maxField.setMinMaxDefault(0, 10000, 60); addTextField(maxField); y += 28; + // Enabled checkbox + addButton(new GuiNpcButton(100, guiLeft + 334, y + 145, 76, 20, new String[]{"gui.disabled", "gui.enabled"}, abilitiesEnabled ? 1 : 0)); + getButton(100).packedFGColour = abilitiesEnabled ? 0x00FF00 : 0xFF0000; + // Left scroll: available ability types addLabel(new GuiNpcLabel(1, "ability.availableTypes", guiLeft + 5, y)); if (availableTypesScroll == null) { availableTypesScroll = new GuiCustomScroll(this, 0); - availableTypesScroll.setSize(140, 103); + availableTypesScroll.setSize(140, 130); } availableTypesScroll.guiLeft = guiLeft + 5; availableTypesScroll.guiTop = y + 12; availableTypesScroll.setList(getFilteredTypeList()); addScroll(availableTypesScroll); - addButton(new GuiNpcButton(50, guiLeft + 5, y + 120, 140, 20, scrollType.toString())); - // Search bar for types addTextField(new GuiNpcTextField(4, this, fontRendererObj, guiLeft + 5, y + 145, 140, 18, search)); @@ -131,9 +138,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC addLabel(new GuiNpcLabel(2, "ability.npcAbilities", guiLeft + 210, y)); if (npcAbilitiesScroll == null) { npcAbilitiesScroll = new GuiCustomScroll(this, 1); - npcAbilitiesScroll.setSize(160, 130); + npcAbilitiesScroll.setSize(200, 130); } else { - npcAbilitiesScroll.setSize(160, 130); + npcAbilitiesScroll.setSize(200, 130); } npcAbilitiesScroll.guiLeft = guiLeft + 210; npcAbilitiesScroll.guiTop = y + 12; @@ -142,11 +149,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Center buttons: Add/Remove int centerX = guiLeft + 158; - addButton(new GuiNpcButton(70, centerX, y + 40, 40, 20, ">>>")); // Add - addButton(new GuiNpcButton(71, centerX, y + 62, 40, 20, "<<<")); // Remove + addButton(new GuiNpcButton(70, centerX, y + 15, 40, 20, ">>>")); // Add + addButton(new GuiNpcButton(71, centerX, y + 37, 40, 20, "<<<")); // Remove + getButton(71).setEnabled(selectedAbilityIndex >= 0); // Load button (under the add/remove arrows) - addButton(new GuiNpcButton(75, centerX, y + 90, 40, 20, "gui.load")); + addButton(new GuiNpcButton(75, centerX, y + 60, 40, 20, "gui.load")); // On/Off toggle for selected ability (under Load button) if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { @@ -167,7 +175,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC getButton(74).setEnabled(selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1); // Save button (to the right of carrots, only enabled when ability is selected) - addButton(new GuiNpcButton(76, guiLeft + 320, y + 145, 50, 20, "gui.save")); + addButton(new GuiNpcButton(76, centerX, y + 82, 40, 20, "gui.save")); getButton(76).setEnabled(selectedAbilityIndex >= 0); } @@ -178,6 +186,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Enabled toggle if (id == 100) { abilitiesEnabled = ((GuiNpcButton) guibutton).getValue() == 1; + initGui(); save(); return; } @@ -276,7 +285,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) { setSubGui(abilityToSave.createConfigGui(this)); } else { - setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave)); + setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave, null, existingPresetNames)); } } } @@ -301,7 +310,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (id == 50) { if (scrollType != ScrollType.MODDED) { ScrollType[] values = ScrollType.values(); - scrollType = values[(scrollType.ordinal() + 1) % values.length]; + ScrollType next = values[(scrollType.ordinal() + 1) % values.length]; + // Skip MODDED if no namespaces are registered + if (next == ScrollType.MODDED && Register.isEmpty("ability")) { + next = ScrollType.ALL; + } + scrollType = next; } else { List list = Register.REGISTERED_NAMESPACES.get("ability"); @@ -336,6 +350,16 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (availableTypesScroll != null) { availableTypesScroll.setList(getFilteredTypeList()); } + } else if (type == EnumScrollData.CUSTOM_ABILITIES) { + existingPresetNames.clear(); + for (String key : data.keySet()) { + int tabIndex = key.indexOf('\t'); + if (tabIndex > 0) { + existingPresetNames.add(key.substring(0, tabIndex)); + } else { + existingPresetNames.add(key); + } + } } initGui(); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java index 9407d20c5..b8a4e0e66 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java @@ -7,24 +7,29 @@ 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.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.ISubGuiListener; import noppes.npcs.client.gui.util.SubGuiInterface; +import java.util.Set; + /** * Confirmation dialog for saving an ability preset. * Uses packet-based communication for proper client-server architecture. */ -public class SubGuiAbilitySaveConfirm extends SubGuiInterface { +public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGuiListener { private final Ability ability; private final IAbilityConfigCallback callback; + private final Set existingNames; public SubGuiAbilitySaveConfirm(Ability ability) { - this(ability, null); + this(ability, null, null); } - public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback) { + public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback, Set existingNames) { this.ability = ability; this.callback = callback; + this.existingNames = existingNames; setBackground("menubg.png"); xSize = 200; @@ -52,14 +57,32 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface { int id = guibutton.id; if (id == 0) { - // Save the ability via packet - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); - if (callback != null) { - callback.onAbilitySaved(ability); + if (existingNames != null && existingNames.contains(ability.getName())) { + setSubGui(new SubGuiDuplicateNameConfirm()); + return; } - close(); + doSave(); } else if (id == 1) { close(); } } + + private void doSave() { + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + if (callback != null) { + callback.onAbilitySaved(ability); + } + close(); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiDuplicateNameConfirm) { + if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) { + doSave(); + } else { + close(); + } + } + } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java index 2bf724684..5d810862f 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -5,22 +5,26 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import noppes.npcs.client.gui.util.GuiCustomScroll; 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.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; /** * SubGui for selecting an ability type when creating a new ability. */ -public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener { +public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { private GuiCustomScroll scroll; private final HashMap displayNameToTypeId = new HashMap<>(); + private final HashMap allDisplayNameToTypeId = new HashMap<>(); private String selectedTypeId = null; + private String search = ""; public SubGuiAbilityTypeSelect() { setBackground("menubg.png"); @@ -32,32 +36,42 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS public void initGui() { super.initGui(); - addLabel(new GuiNpcLabel(0, "ability.selectType", guiLeft + 5, guiTop + 5)); + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); if (scroll == null) { scroll = new GuiCustomScroll(this, 0); - scroll.setSize(190, 165); + scroll.setSize(190, 145); } scroll.guiLeft = guiLeft + 5; - scroll.guiTop = guiTop + 16; + scroll.guiTop = guiTop + 26; addScroll(scroll); - List list = buildTypeList(); - scroll.setList(list); + buildAllTypes(); + scroll.setList(getFilteredTypeList()); addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.add")); getButton(0).setEnabled(scroll.hasSelected()); addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); } - private List buildTypeList() { - List list = new ArrayList<>(); - displayNameToTypeId.clear(); + private void buildAllTypes() { + allDisplayNameToTypeId.clear(); String[] types = AbilityController.Instance.getTypes(); for (String typeId : types) { String displayName = I18n.format(typeId); - list.add(displayName); - displayNameToTypeId.put(displayName, typeId); + allDisplayNameToTypeId.put(displayName, typeId); + } + } + + private List getFilteredTypeList() { + List list = new ArrayList<>(); + displayNameToTypeId.clear(); + for (Map.Entry entry : allDisplayNameToTypeId.entrySet()) { + String displayName = entry.getKey(); + if (search.isEmpty() || displayName.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) { + list.add(displayName); + displayNameToTypeId.put(displayName, entry.getValue()); + } } return list; } @@ -89,6 +103,22 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS } } + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + if (!search.equals(getTextField(10).getText())) { + search = getTextField(10).getText().toLowerCase(); + scroll.setList(getFilteredTypeList()); + scroll.resetScroll(); + } + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + } + public String getSelectedTypeId() { return selectedTypeId; } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java new file mode 100644 index 000000000..b16386c32 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java @@ -0,0 +1,47 @@ +package noppes.npcs.client.gui.advanced; + +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.SubGuiInterface; + +/** + * Confirmation dialog shown when saving an ability preset with a name that already exists. + */ +public class SubGuiDuplicateNameConfirm extends SubGuiInterface { + + private boolean confirmed = false; + + public SubGuiDuplicateNameConfirm() { + setBackground("menubg.png"); + xSize = 220; + ySize = 80; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.duplicate.name", guiLeft + 10, y)); + + y += 30; + addButton(new GuiNpcButton(0, guiLeft + 20, y, 80, 20, "gui.continue")); + addButton(new GuiNpcButton(1, guiLeft + 120, y, 80, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + confirmed = true; + close(); + } else if (guibutton.id == 1) { + confirmed = false; + close(); + } + } + + public boolean isConfirmed() { + return confirmed; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java index 5296bb615..f911c6f43 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -16,7 +16,9 @@ import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import noppes.npcs.client.NoppesUtil; +import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect; +import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm; import noppes.npcs.client.gui.util.AbilityPreviewExecutor; import noppes.npcs.client.gui.util.GuiAbilityInterface; import noppes.npcs.client.gui.util.GuiCustomScroll; @@ -62,6 +64,10 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private String search = ""; private Ability selectedAbility = null; + // ==================== PENDING SAVE ==================== + private Ability pendingSaveAbility = null; + private boolean pendingNewCreation = false; + // ==================== PREVIEW ==================== private AbilityPreviewExecutor previewExecutor; private long prevTick = 0; @@ -343,21 +349,76 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface Ability newAbility = AbilityController.Instance.create(typeId); if (newAbility != null) { newAbility.setId(UUID.randomUUID().toString()); - newAbility.setName(newAbility.getTypeId()); - // Save to server, then open config GUI - PacketClient.sendClient(new CustomAbilitySavePacket(newAbility.writeNBT())); - selectedAbility = newAbility; - selected = newAbility.getName(); - selectedUuid = newAbility.getId(); - previewExecutor.stop(); - setSubGui(selectedAbility.createConfigGui(this)); + if (hasDuplicateName(newAbility)) { + pendingSaveAbility = newAbility; + pendingNewCreation = true; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + saveAndOpenConfig(newAbility); return; } } + } else if (subgui instanceof SubGuiDuplicateNameConfirm) { + SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui; + if (confirm.isConfirmed() && pendingSaveAbility != null) { + if (pendingNewCreation) { + saveAndOpenConfig(pendingSaveAbility); + pendingSaveAbility = null; + pendingNewCreation = false; + return; + } else { + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + pendingSaveAbility = null; + } + } else if (pendingSaveAbility != null) { + if (pendingNewCreation) { + // Cancel new creation - discard + pendingSaveAbility = null; + pendingNewCreation = false; + } else { + // Cancel edit save - re-open config GUI to change name + Ability ability = pendingSaveAbility; + pendingSaveAbility = null; + setSubGui(ability.createConfigGui(this)); + return; + } + } + } else if (pendingSaveAbility != null) { + // Config GUI closed with a pending save (set by onAbilitySaved) + if (hasDuplicateName(pendingSaveAbility)) { + pendingNewCreation = false; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + pendingSaveAbility = null; } initGui(); } + private void saveAndOpenConfig(Ability ability) { + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + selectedAbility = ability; + selected = ability.getName(); + selectedUuid = ability.getId(); + previewExecutor.stop(); + setSubGui(ability.createConfigGui(this)); + } + + private boolean hasDuplicateName(Ability ability) { + String name = ability.getName(); + if (name == null || name.isEmpty()) return false; + for (java.util.Map.Entry entry : displayToUuid.entrySet()) { + if (entry.getKey().equals(name) && !entry.getValue().equals(ability.getId())) { + return true; + } + } + return false; + } + @Override public void confirmClicked(boolean result, int id) { NoppesUtil.openGUI(player, this); @@ -375,7 +436,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void onAbilitySaved(Ability ability) { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + // Defer save until subGuiClosed where we can check for duplicate names + pendingSaveAbility = ability; } @Override diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java index 31a093b8d..278903bb7 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java @@ -135,6 +135,9 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { * Draw the 3D preview with NPC and entities. */ protected void drawPreview(int mouseX, int mouseY, float partialTicks) { + if (hasSubGui()) + return; + GL11.glColor4f(1, 1, 1, 1); // Enable scissor to clip rendering to preview area diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 9e6366fdf..6b344f9b9 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -481,8 +481,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti super.onLivingUpdate(); - // Apply locked rotation after super.onLivingUpdate() to override look helper changes + // Apply locks after super.onLivingUpdate() to override AI/physics changes abilities.applyLockedRotation(); + abilities.applyLockedPosition(); handleMountRiderState(); diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 2158e9ea4..7317856c9 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -164,6 +164,7 @@ gui.playerMap=Regen PlayerMap gui.unused=Unused gui.apply=Apply gui.cancel=Cancel +gui.continue=Continue gui.yes=Yes gui.lineColor1=Upper line color @@ -1829,6 +1830,7 @@ ability.dualFireDelay=Fire Delay # Ability Save/Load ability.save.confirm=Save ability preset ability.save.overwrite=Overwrite existing preset +ability.duplicate.name=A preset with this name already exists ability.load.select=Select ability to load: ability.load.mode=How should this ability be loaded? ability.clone=Clone From 095709b9d2c5ae7beed84de5f0f3d173823a7e86 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 5 Feb 2026 22:49:40 -0500 Subject: [PATCH 04/76] Add ability wheel and toggle abilities for enhanced gameplay --- .../kamkeel/npcs/command/AbilityCommand.java | 192 ++++++++++++++++++ .../kamkeel/npcs/command/CommandKamkeel.java | 4 + .../data/ability/AbilityController.java | 77 ++++++- .../packets/player/SpecialKeyStatePacket.java | 10 + src/main/java/noppes/npcs/DataAbilities.java | 10 + .../java/noppes/npcs/NoppesUtilServer.java | 4 + .../client/gui/advanced/GuiNPCAbilities.java | 6 +- .../scripted/wrapper/ScriptDataAbilities.java | 23 ++- .../wrapper/ScriptPlayerAbilityData.java | 14 +- 9 files changed, 330 insertions(+), 10 deletions(-) diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java index d5b9420cc..004274fc3 100644 --- a/src/main/java/kamkeel/npcs/command/AbilityCommand.java +++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java @@ -2,7 +2,12 @@ package kamkeel.npcs.command; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.data.ability.UserType; import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; import java.util.ArrayList; import java.util.Collections; @@ -122,5 +127,192 @@ public class AbilityCommand extends CommandKamkeelBase { } sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange()); sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No")); + sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name()); + } + + @SubCommand( + desc = "List all built-in abilities available for players" + ) + public void prebuilts(ICommandSender sender, String[] args) { + Set names = AbilityController.Instance.getAbilityNames(); + if (names.isEmpty()) { + sendResult(sender, "No built-in abilities found."); + return; + } + + List playerAbilities = new ArrayList<>(); + for (String name : names) { + Ability ability = AbilityController.Instance.getAbility(name); + if (ability != null && ability.getAllowedBy().allowsPlayer()) { + playerAbilities.add(name); + } + } + + if (playerAbilities.isEmpty()) { + sendResult(sender, "No player-usable built-in abilities found."); + return; + } + + Collections.sort(playerAbilities); + sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):"); + for (String name : playerAbilities) { + Ability ability = AbilityController.Instance.getAbility(name); + String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]"; + sendResult(sender, " - \u00A7b" + name + " " + userType); + } + } + + @SubCommand( + desc = "Unlock an ability for a player", + usage = " " + ) + public void unlock(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability unlock "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + // Resolve ability + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + if (ability == null) { + sendError(sender, "Ability not found: " + abilityKey); + return; + } + + // Use the ability's canonical ID for storage (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId(); + if (canonicalKey == null || canonicalKey.isEmpty()) { + canonicalKey = abilityKey; // Fallback to user-provided key + } + String displayName = ability.getName() != null ? ability.getName() : canonicalKey; + + // Check if ability allows players + if (!ability.getAllowedBy().allowsPlayer()) { + sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players."); + return; + } + + // Get player data and unlock + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player already has ability: " + displayName); + return; + } + + data.abilityData.unlockAbility(canonicalKey); + sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName); + } + + @SubCommand( + desc = "Lock (revoke) an ability from a player", + usage = " " + ) + public void lock(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability lock "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + // Resolve ability to get canonical key + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + String canonicalKey = abilityKey; + String displayName = abilityKey; + if (ability != null) { + canonicalKey = ability.getId() != null ? ability.getId() : abilityKey; + displayName = ability.getName() != null ? ability.getName() : canonicalKey; + } + + // Get player data and lock + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (!data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player doesn't have ability: " + displayName); + return; + } + + data.abilityData.lockAbility(canonicalKey); + sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName); + } + + @SubCommand( + desc = "List abilities unlocked for a player", + usage = "" + ) + public void player(ICommandSender sender, String[] args) { + if (args.length < 1) { + sendError(sender, "Usage: /kam ability player "); + return; + } + + String playerName = args[0]; + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + String[] abilityKeys = data.abilityData.getUnlockedAbilities(); + + if (abilityKeys.length == 0) { + sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities."); + return; + } + + sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):"); + int selected = data.abilityData.getSelectedIndex(); + for (int i = 0; i < abilityKeys.length; i++) { + String key = abilityKeys[i]; + Ability ability = AbilityController.Instance.resolveAbility(key); + String displayName = ability != null && ability.getName() != null ? ability.getName() : key; + String prefix = (i == selected) ? "\u00A7e> " : " "; + // Show display name and key if different + if (!displayName.equals(key)) { + sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]"); + } else { + sendResult(sender, prefix + "\u00A7b" + displayName); + } + } + } + + private String joinArgs(String[] args, int startIndex) { + StringBuilder sb = new StringBuilder(); + for (int i = startIndex; i < args.length; i++) { + if (i > startIndex) sb.append(" "); + sb.append(args[i]); + } + return sb.toString(); + } + + /** + * Get list of player-usable ability keys (for tab completion). + * Uses registry keys for built-in abilities (no spaces) and UUIDs for custom. + * Used by CommandKamkeel for usage token. + */ + public static List getPlayerAbilityNames() { + List keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys()); + Collections.sort(keys); + return keys; } } diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java index d0341f211..91356c825 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames; import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames; public class CommandKamkeel extends CommandBase { @@ -135,6 +136,9 @@ public class CommandKamkeel extends CommandBase { } else if (usage.equals("")) { List keys = getSortedEffectNames(); return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); + } else if (usage.equals("")) { + List keys = getPlayerAbilityNames(); + return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 213c1a214..05110f553 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -180,30 +180,93 @@ public class AbilityController implements IAbilityHandler { // ═══════════════════════════════════════════════════════════════════════════ /** - * Resolve an ability by key. Checks built-in abilities first (by name), - * then custom abilities (by UUID). Returns a copy safe to modify. + * Resolve an ability by key. Checks built-in abilities first (by name or registry key), + * then custom abilities (by UUID or name). Returns a copy safe to modify for + * custom abilities, or the singleton instance for built-in abilities. * - * @param key The ability name (built-in) or UUID (custom) - * @return A copy of the resolved ability, or null if not found + * @param key The ability name, registry key (built-in) or UUID (custom) + * @return The resolved ability, or null if not found */ public Ability resolveAbility(String key) { if (key == null || key.isEmpty()) return null; - // Check built-in abilities first + // Check built-in abilities first (exact match by name) Ability builtIn = abilities.get(key); if (builtIn != null) { - return fromNBT(builtIn.writeNBT()); + return builtIn; } - // Check custom abilities + // Check built-in abilities by name (case-insensitive) + for (Map.Entry entry : abilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue(); + } + } + + // Check built-in abilities by registry key / ID + for (Ability ability : abilities.values()) { + if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) { + return ability; + } + } + + // Check custom abilities (exact UUID match) Ability custom = customAbilities.get(key); if (custom != null) { return fromNBT(custom.writeNBT()); } + // Check custom abilities by name (case-insensitive) + for (Ability ability : customAbilities.values()) { + if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { + return fromNBT(ability.writeNBT()); + } + } + return null; } + /** + * Get all keys that can be used to look up abilities (for tab completion). + * Returns registry keys for built-in abilities (no spaces) and UUIDs for custom. + */ + public Set getAbilityKeys() { + Set keys = new LinkedHashSet<>(); + // Built-in abilities - use the ID (registry key for BuiltInAbility) + for (Ability ability : abilities.values()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + // Custom abilities - use UUID + keys.addAll(customAbilities.keySet()); + return keys; + } + + /** + * Get keys for player-usable abilities only (for tab completion). + */ + public Set getPlayerAbilityKeys() { + Set keys = new LinkedHashSet<>(); + // Built-in abilities - use the ID (registry key for BuiltInAbility) + for (Ability ability : abilities.values()) { + if (ability.getAllowedBy().allowsPlayer()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + } + // Custom abilities - use UUID (if player-usable) + for (Map.Entry entry : customAbilities.entrySet()) { + if (entry.getValue().getAllowedBy().allowsPlayer()) { + keys.add(entry.getKey()); + } + } + return keys; + } + /** * Check if an ability key exists (either built-in or custom). */ 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 48ac3391b..a58b896f4 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -59,6 +59,16 @@ 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) { + return; + } + data.abilityData.activateAbility(player); } } diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index cb83caae2..36dc6f34a 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -368,6 +368,11 @@ public class DataAbilities { * Check if a specific ability is eligible for use. */ private boolean isAbilityEligible(Ability ability, EntityLivingBase target) { + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + // Check enabled if (!ability.isEnabled()) { return false; @@ -695,6 +700,11 @@ public class DataAbilities { return false; } + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + // Stop any currently executing ability stopCurrentAbility(); diff --git a/src/main/java/noppes/npcs/NoppesUtilServer.java b/src/main/java/noppes/npcs/NoppesUtilServer.java index 4b93ad2b5..7faa7b2b5 100644 --- a/src/main/java/noppes/npcs/NoppesUtilServer.java +++ b/src/main/java/noppes/npcs/NoppesUtilServer.java @@ -2,6 +2,7 @@ package noppes.npcs; import io.netty.buffer.ByteBuf; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.packets.data.ParticlePacket; @@ -792,6 +793,9 @@ public class NoppesUtilServer { if (controller != null) { int index = 0; for (String uuid : controller.getCustomAbilityIds()) { + Ability ability = controller.getCustomAbility(uuid); + if (ability == null || !ability.getAllowedBy().allowsNpc()) continue; + String name = controller.getCustomAbilityName(uuid); if (name == null || name.isEmpty()) name = uuid; map.put(name + "\t" + uuid, index++); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index 998473623..fd8461245 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -334,8 +334,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Map dummyMap = new HashMap<>(allAbilityTypes); filteredAbilityTypes.clear(); filteredAbilityTypes.putAll(getFilteredData(dummyMap)); - } + // Reset scroll position when changing category + if (availableTypesScroll != null) { + availableTypesScroll.resetScroll(); + } + } initGui(); } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java index d0b5259ea..e27f6e075 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java @@ -42,12 +42,25 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public void addAbility(IAbility ability) { if (ability instanceof Ability) { - data.addAbility((Ability) ability); + Ability a = (Ability) ability; + // Validate ability allows NPCs + if (!a.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } + data.addAbility(a); } } @Override public void addAbilityReference(String key) { + // Validate ability exists and allows NPCs + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } data.addAbilityReference(key); } @@ -158,6 +171,14 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public boolean executeAbility(String key, Object target) { + // Validate ability exists and allows NPCs + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return false; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsNpc()) { + return false; // Ability is PLAYER_ONLY + } EntityLivingBase targetEntity = resolveTarget(target); return data.executeAbility(key, targetEntity); } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java index a36c65d51..42ed3372e 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java @@ -1,5 +1,7 @@ package noppes.npcs.scripted.wrapper; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import net.minecraft.entity.player.EntityPlayer; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.ability.IPlayerAbilityData; @@ -26,7 +28,17 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public void unlockAbility(String key) { - data.unlockAbility(key); + // Validate ability exists and allows players + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsPlayer()) { + return; // Ability is NPC-only + } + // Use canonical key (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId() != null ? ability.getId() : key; + data.unlockAbility(canonicalKey); } @Override From 4f7773eb3f34c9635ef7590249adf74d760145b9 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 03:34:29 -0500 Subject: [PATCH 05/76] Fix Preview Entity --- .../client/gui/util/GuiAbilityInterface.java | 21 +++---------------- 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java index 278903bb7..3d0573bf2 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java @@ -11,10 +11,7 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import noppes.npcs.client.ClientEventHandler; -import noppes.npcs.client.EntityUtil; -import noppes.npcs.entity.EntityCustomNpc; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.entity.data.ModelData; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -50,7 +47,6 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { private GuiNpcButton btnLeft, btnRight; // ==================== NPC STATE ==================== - public ModelData playerdata; public EntityNPCInterface npc; /** NPC starting position (saved when preview starts, used to track movement) */ @@ -85,7 +81,6 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { public GuiAbilityInterface(EntityNPCInterface npc, boolean hasMenuNpc) { super(hasMenuNpc ? npc : null); this.npc = npc; - this.playerdata = ((EntityCustomNpc) npc).modelData; this.drawDefaultBackground = false; CAMERA_ZOOM = 30f; @@ -144,14 +139,8 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { GL11.glEnable(GL11.GL_SCISSOR_TEST); setScissorClip(previewX, previewY, previewWidth, previewHeight); - // Get the entity to render (could be transformed player model) - EntityLivingBase renderEntity = playerdata.getEntity(npc); - if (renderEntity == null) { - renderEntity = this.npc; - } - - // Sync NPC properties to render entity - EntityUtil.Copy(npc, renderEntity); + // Always use the standard NPC animation renderer for ability preview + EntityLivingBase renderEntity = this.npc; // Set NPC facing direction (affects anchor points and visual facing) npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; @@ -207,11 +196,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { ClientEventHandler.renderingEntityInGUI = true; // Render the NPC at its position delta (for movement like slam jumps) - try { - RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); - } catch (Exception e) { - playerdata.setEntityClass(null); - } + RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); // Render preview entities at their positions relative to NPC start position renderPreviewEntities(partialTicks); From 55cd8cc5b3cf556b82d58b6a66a2ef4fb804c7be Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 03:34:45 -0500 Subject: [PATCH 06/76] Fix Rotation Locking --- src/main/java/noppes/npcs/DataAbilities.java | 25 ++++++++++++++++++- .../npcs/entity/EntityNPCInterface.java | 7 ++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 36dc6f34a..19dc59ecd 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -117,10 +117,33 @@ public class DataAbilities { * Should be called every tick from onLivingUpdate(). */ public void tick() { - if (!enabled || npc.worldObj.isRemote || npc.isKilled()) { + if (npc.worldObj.isRemote) { return; } + // Force-stop any running ability when NPC is killed or abilities are disabled + if (!enabled || npc.isKilled()) { + if (currentAbility != null) { + removeTelegraph(currentAbility); + stopAbilityAnimation(); + releaseLockedRotation(); + releaseLockedPosition(); + currentAbility = null; + lastTarget = null; + } else { + // No ability but locks could be orphaned + if (rotationLocked) releaseLockedRotation(); + if (positionLocked) releaseLockedPosition(); + } + return; + } + + // Safety: release orphaned locks if no ability is actively executing + if (currentAbility == null || !currentAbility.isExecuting()) { + if (rotationLocked) releaseLockedRotation(); + if (positionLocked) releaseLockedPosition(); + } + // Tick current ability if executing if (currentAbility != null && currentAbility.isExecuting()) { tickCurrentAbility(); diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 6b344f9b9..00de6d405 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -308,6 +308,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti @Override public void onUpdate() { super.onUpdate(); + + // Re-apply locks after super.onUpdate() to override body rotation smoothing + // in EntityLivingBase.onUpdate() (func_110146_f) which runs AFTER onLivingUpdate() + // and overwrites renderYawOffset, causing a visible twitch each frame. + abilities.applyLockedRotation(); + abilities.applyLockedPosition(); + if (!isRemote()) { if (this.ticksExisted % 10 == 0) { EventHooks.onNPCUpdate(this); From 70583743ce67d6e591d122773dfdc019eb950a7a Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 03:36:32 -0500 Subject: [PATCH 07/76] Fix Ability and Custom Button --- .../client/gui/global/GuiNPCManageAnimations.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java index ac4675243..3ac3923b4 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java @@ -65,16 +65,17 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol public void initGui() { super.initGui(); + // Toggle button - added FIRST to maintain stable buttonList index + // (prevents double-toggle when initGui() is called from actionPerformed) + String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; + this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel)); + // Add/Remove buttons - only show for custom animations if (!showingBuiltIn) { this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove")); } - // Toggle button for Custom/Built-in - under Remove button - String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; - this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel)); - if (scrollAnimations == null) { scrollAnimations = new GuiCustomScroll(this, 0, 0); scrollAnimations.setSize(143, 185); @@ -200,11 +201,15 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol // Toggle button if (button.id == 10) { showingBuiltIn = !showingBuiltIn; - // Clear selection when switching views + // Clear selection and search when switching views selected = null; + search = ""; animation = new Animation(); currentIsBuiltIn = false; + playingAnimation = false; scrollAnimations.clear(); + // Re-request data to ensure both lists are populated + PacketClient.sendClient(new AnimationsGetPacket()); initGui(); return; } From 2e5c4c3bf41eab22c1bd9bb2e3ec59bef74c886a Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 05:04:19 -0500 Subject: [PATCH 08/76] Fix Preview Handling for Abilities, Fix Disc Positioning in Real World --- .../controllers/data/ability/Ability.java | 112 ++++------ .../data/ability/PreviewEntityHandler.java | 13 ++ .../data/ability/type/AbilityBeam.java | 35 ++- .../data/ability/type/AbilityBeamDual.java | 45 ++-- .../data/ability/type/AbilityCharge.java | 83 ++----- .../data/ability/type/AbilityCutter.java | 20 +- .../data/ability/type/AbilityDash.java | 85 ++------ .../data/ability/type/AbilityDisc.java | 37 ++-- .../data/ability/type/AbilityDiscDual.java | 51 +++-- .../data/ability/type/AbilityHazard.java | 92 ++++---- .../data/ability/type/AbilityHeal.java | 38 ++-- .../data/ability/type/AbilityHeavyHit.java | 68 +++--- .../data/ability/type/AbilityLaserShot.java | 31 +-- .../data/ability/type/AbilityOrb.java | 32 ++- .../data/ability/type/AbilityOrbBarrage.java | 26 +-- .../data/ability/type/AbilityOrbDual.java | 42 ++-- .../data/ability/type/AbilityProjectile.java | 89 ++++---- .../data/ability/type/AbilityShockwave.java | 70 +++--- .../data/ability/type/AbilitySlam.java | 140 +++--------- .../data/ability/type/AbilitySweeper.java | 14 +- .../data/ability/type/AbilityTeleport.java | 63 ++++-- .../data/ability/type/AbilityTrap.java | 34 +-- .../data/ability/type/AbilityVortex.java | 48 +++-- .../npcs/entity/EntityAbilityBeam.java | 25 ++- .../npcs/entity/EntityAbilityDisc.java | 1 - .../npcs/entity/EntityAbilityLaser.java | 4 - .../npcs/entity/EntityAbilitySweeper.java | 13 ++ .../java/noppes/npcs/client/ClientProxy.java | 2 + .../gui/util/AbilityPreviewExecutor.java | 202 +++++++++++------- 29 files changed, 714 insertions(+), 801 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.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 03faf42d5..e6404a0cb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -110,6 +110,13 @@ public abstract class Ability implements IAbility { protected transient long executionStartTime; protected transient TelegraphInstance telegraphInstance; + // ═══════════════════════════════════════════════════════════════════ + // PREVIEW STATE (client-side only, not saved) + // ═══════════════════════════════════════════════════════════════════ + + protected transient boolean previewMode = false; + protected transient PreviewEntityHandler previewEntityHandler; + // ═══════════════════════════════════════════════════════════════════ // ABSTRACT METHODS // ═══════════════════════════════════════════════════════════════════ @@ -837,6 +844,8 @@ public abstract class Ability implements IAbility { currentTick = 0; currentTarget = null; telegraphInstance = null; + previewMode = false; + previewEntityHandler = null; } /** @@ -849,90 +858,57 @@ public abstract class Ability implements IAbility { } // ═══════════════════════════════════════════════════════════════════ - // CLIENT-SIDE PREVIEW METHODS + // PREVIEW MODE SUPPORT // ═══════════════════════════════════════════════════════════════════ /** - * Get total active phase duration for preview (in ticks). - * Override in subclasses to provide accurate preview duration. - * - * @return Duration of active phase in ticks (default: 40 = 2 seconds) + * Whether this ability is running in preview mode (GUI preview). + * When true, abilities should skip damage, effects, sounds, and particles + * but still run their core logic (entity spawning, movement, timing). */ - public int getPreviewActiveDuration() { - return 40; + public boolean isPreview() { + return previewMode; + } + + public void setPreviewMode(boolean preview) { + this.previewMode = preview; + } + + public void setPreviewEntityHandler(PreviewEntityHandler handler) { + this.previewEntityHandler = handler; } /** - * Called during preview windup tick (client-side only). - * Override for visual updates during windup preview. - * Do NOT apply damage or world effects here. - * - * @param npc The preview NPC - * @param tick Current tick within windup phase + * Spawn an entity during ability execution. + * In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld(). */ - @SideOnly(Side.CLIENT) - public void onPreviewWindUpTick(EntityNPCInterface npc, int tick) { - // Default: no-op. Override in subclasses for visual effects. + protected void spawnAbilityEntity(World world, Entity entity) { + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntitySpawned(entity); + } else { + world.spawnEntityInWorld(entity); + } } /** - * Called during preview active tick (client-side only). - * Override for visual updates during active preview. - * Do NOT apply damage or world effects here. - * - * @param npc The preview NPC - * @param tick Current tick within active phase + * Kill an entity spawned by this ability. + * In preview mode, notifies PreviewEntityHandler of removal. */ - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - // Default: no-op. Override in subclasses for visual effects. + protected void killAbilityEntity(Entity entity) { + if (entity == null) return; + entity.setDead(); + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntityRemoved(entity); + } } /** - * Create a preview entity for GUI display (client-side only). - * The entity should be in preview mode and not apply damage. - * Override in abilities that spawn entities (Beam, Orb, Disc, etc.) - * - * @param npc The preview NPC - * @return Preview entity, or null if ability doesn't spawn entities + * Maximum duration (in ticks) for preview before auto-stopping. + * Override in movement abilities that have variable duration. + * Default: 200 ticks (10 seconds). */ - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - return null; // Override in entity-spawning abilities - } - - /** - * Whether to spawn preview entity during WINDUP phase (true) or ACTIVE phase (false). - * Most abilities (Orb, Beam, Disc) spawn during windup for charging effect. - * Laser spawns at active phase since it has no charging state. - */ - public boolean spawnPreviewDuringWindup() { - return true; // Default: spawn during windup for charging - } - - // ── Preview target (set by executor for abilities that need targeting) ── - - protected transient EntityLivingBase previewTarget; - - /** - * Set the fake target entity for preview mode. - * Called by AbilityPreviewExecutor before starting preview. - */ - public void setPreviewTarget(EntityLivingBase target) { - this.previewTarget = target; - } - - public EntityLivingBase getPreviewTarget() { - return previewTarget; - } - - /** - * Called once when transitioning from WINDUP to ACTIVE in preview mode. - * Override in movement-based abilities to initiate movement. - */ - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - // Default: no-op. Override in movement abilities. + public int getMaxPreviewDuration() { + return 200; } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java new file mode 100644 index 000000000..77fae9774 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java @@ -0,0 +1,13 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.Entity; + +/** + * Interface for routing entity spawn/kill calls during preview mode. + * In preview mode, entities are not added to the world but instead + * tracked by the GUI for rendering in the 3D viewport. + */ +public interface PreviewEntityHandler { + void onEntitySpawned(Entity entity); + void onEntityRemoved(Entity entity); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 5157eea01..8e3bfc575 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -76,29 +76,29 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } // Start firing the beam that was spawned during windup if (beamEntity != null && !beamEntity.isDead) { - beamEntity.startFiring(target); + if (isPreview()) { + beamEntity.startPreviewFiring(); + } else { + beamEntity.startFiring(target); + } } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class } @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn beam in charging mode on first tick of windup if (tick == 1) { float offsetDist = 1.0f; - // Create beam in charging mode - follows caster based on anchor point during windup Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData, offsetDist); beamEntity = new EntityAbilityBeam( world, caster, target, @@ -106,11 +106,16 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { beamWidth, headSize, colorData, combatData, homingData, lightningData, lifespanData, trajectoryData, lockMovement.locksActive()); - beamEntity.setupCharging(anchorData, windUpTicks, offsetDist); + + if (isPreview()) { + beamEntity.setupPreview(caster, beamWidth, headSize, colorData, lightningData, anchorData, windUpTicks, offsetDist); + } else { + beamEntity.setupCharging(anchorData, windUpTicks, offsetDist); + } beamEntity.setEffects(this.effects); beamEntity.setSourceAbility(this); - world.spawnEntityInWorld(beamEntity); + spawnAbilityEntity(world, beamEntity); } } @@ -267,17 +272,7 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityBeam beam = new EntityAbilityBeam(npc.worldObj); - beam.setupPreview(npc, beamWidth, headSize, colorData, lightningData, anchorData, windUpTicks, 1.0f); - return beam; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java index 762145fc4..89c5b126f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java @@ -81,37 +81,41 @@ public class AbilityBeamDual extends Ability { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } // Start firing the beam that was spawned during windup if (beamEntity != null && !beamEntity.isDead) { - beamEntity.startFiring(target); + if (isPreview()) { + beamEntity.startPreviewFiring(); + } else { + beamEntity.startFiring(target); + } } if (dualFire) { if (beamEntity2 != null && !beamEntity2.isDead && dualFireDelay <= 0) { - beamEntity2.startFiring(target); + if (isPreview()) { + beamEntity2.startPreviewFiring(); + } else { + beamEntity2.startFiring(target); + } } } else if (beamEntity2 != null) { beamEntity2.setDead(); } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class } @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn beam in charging mode on first tick of windup if (tick == 1) { float offsetDist = 1.0f; - // Create beam in charging mode - follows caster based on anchor point during windup Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0], offsetDist); beamEntity = new EntityAbilityBeam( world, caster, target, @@ -131,16 +135,21 @@ public class AbilityBeamDual extends Ability { beamEntity.setSiblingEntityId(beamEntity2.getEntityId()); beamEntity2.setSiblingEntityId(beamEntity.getEntityId()); - beamEntity.setupCharging(anchorData[0], windUpTicks, offsetDist); - beamEntity2.setupCharging(anchorData[1], windUpTicks, offsetDist); + if (isPreview()) { + beamEntity.setupPreview(caster, beamWidth, headSize, displayData[0], lightningData[0], anchorData[0], windUpTicks, offsetDist); + beamEntity2.setupPreview(caster, beamWidth, headSize, displayData[1], lightningData[1], anchorData[1], windUpTicks, offsetDist); + } else { + beamEntity.setupCharging(anchorData[0], windUpTicks, offsetDist); + beamEntity2.setupCharging(anchorData[1], windUpTicks, offsetDist); + } beamEntity.setEffects(this.effects); if (dualFire) beamEntity2.setEffects(this.effects); beamEntity.setSourceAbility(this); beamEntity2.setSourceAbility(this); - world.spawnEntityInWorld(beamEntity); - world.spawnEntityInWorld(beamEntity2); + spawnAbilityEntity(world, beamEntity); + spawnAbilityEntity(world, beamEntity2); } } @@ -501,17 +510,7 @@ public class AbilityBeamDual extends Ability { } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityBeam beam = new EntityAbilityBeam(npc.worldObj); - beam.setupPreview(npc, beamWidth, headSize, displayData[0], lightningData[0], anchorData[0], windUpTicks, 1.0f); - return beam; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } } 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 e09ff7e11..8e179dc73 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 @@ -138,7 +138,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge { if (chargeDirection == null) return; // Enforce rotation every tick - enforceLockedRotation(caster); + if (!isPreview()) { + enforceLockedRotation(caster); + } // Calculate distance traveled double distanceTraveled = Math.sqrt( @@ -150,12 +152,15 @@ public class AbilityCharge extends Ability implements IAbilityCharge { if (distanceTraveled >= maxRange) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } signalCompletion(); return; } - if (isChargeBlocked(caster)) { + // Block detection (skip in preview - no real world collision) + if (!isPreview() && isChargeBlocked(caster)) { stopMomentum(caster); signalCompletion(); return; @@ -165,10 +170,12 @@ public class AbilityCharge extends Ability implements IAbilityCharge { caster.motionX = chargeDirection.xCoord * chargeSpeed; caster.motionY = 0; caster.motionZ = chargeDirection.zCoord * chargeSpeed; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } - // Server-side collision damage - if (!world.isRemote) { + // Server-side collision damage (skip in preview) + if (!world.isRemote && !isPreview()) { AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth); @SuppressWarnings("unchecked") @@ -211,7 +218,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge { private void stopMomentum(EntityLivingBase caster) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } } private boolean isChargeBlocked(EntityLivingBase caster) { @@ -277,66 +286,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return instance; } - // ==================== PREVIEW MODE ==================== - - private transient double previewDirX, previewDirZ; - private transient double previewStartX, previewStartZ; - private transient boolean previewCharging = false; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewStartX = npc.posX; - previewStartZ = npc.posZ; - previewCharging = false; - - // Calculate direction toward fake target - if (previewTarget != null) { - double dx = previewTarget.posX - npc.posX; - double dz = previewTarget.posZ - npc.posZ; - double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - previewDirX = dx / len; - previewDirZ = dz / len; - } else { - float yaw = (float) Math.toRadians(npc.rotationYaw); - previewDirX = -Math.sin(yaw); - previewDirZ = Math.cos(yaw); - } - } else { - float yaw = (float) Math.toRadians(npc.rotationYaw); - previewDirX = -Math.sin(yaw); - previewDirZ = Math.cos(yaw); - } - previewCharging = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewCharging) return; - - // Check distance traveled - double distTraveled = Math.sqrt( - Math.pow(npc.posX - previewStartX, 2) + - Math.pow(npc.posZ - previewStartZ, 2) - ); - - if (distTraveled >= maxRange) { - previewCharging = false; - return; - } - - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewDirX * chargeSpeed; - npc.posZ += previewDirZ * chargeSpeed; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return (int) Math.ceil(maxRange / chargeSpeed) + 5; } 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 405dac612..22831f4ff 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 @@ -109,31 +109,35 @@ public class AbilityCutter extends Ability implements IAbilityCutter { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; switch (sweepMode) { case SWIPE: float prevRotation = currentRotation; currentRotation += sweepSpeed; if (currentRotation > arcAngle / 2.0f) { - // Final sweep — check from prevRotation to end of arc - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + if (!isPreview()) { + performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + } signalCompletion(); return; } - // Check entities between previous and current sweep position - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); + if (!isPreview()) { + performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); + } break; case SPIN: if (tick >= spinDurationTicks) { - signalCompletion(); // Spin duration complete + signalCompletion(); return; } float prevSpin = currentRotation; currentRotation = (currentRotation + sweepSpeed) % 360.0f; - hitEntities.clear(); - performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); + if (!isPreview()) { + hitEntities.clear(); + performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); + } break; } } 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 1a1e76aa3..f80f336aa 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 @@ -172,7 +172,7 @@ public class AbilityDash extends Ability implements IAbilityDash { if (dashDirection == null) return; // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall - if (tick > 1) { + if (!isPreview() && tick > 1) { double movedThisTick = Math.sqrt( Math.pow(caster.posX - prevTickX, 2) + Math.pow(caster.posZ - prevTickZ, 2)); @@ -197,12 +197,15 @@ public class AbilityDash extends Ability implements IAbilityDash { if (distanceTraveled >= dashDistance) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } signalCompletion(); return; } - if (isDashBlocked(caster)) { + // Block detection (skip in preview - no real world collision) + if (!isPreview() && isDashBlocked(caster)) { caster.motionX = 0; caster.motionZ = 0; caster.velocityChanged = true; @@ -214,24 +217,30 @@ public class AbilityDash extends Ability implements IAbilityDash { caster.motionX = dashDirection.xCoord * dashSpeed; caster.motionY = 0; caster.motionZ = dashDirection.zCoord * dashSpeed; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; - // Trail particles - world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + // Trail particles + world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + } } @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } } @Override @@ -247,66 +256,8 @@ public class AbilityDash extends Ability implements IAbilityDash { return !caster.worldObj.getCollidingBoundingBoxes(caster, caster.boundingBox.copy().offset(nextX, 0, nextZ)).isEmpty(); } - // ==================== PREVIEW MODE ==================== - - private transient double previewDirX, previewDirZ; - private transient double previewStartX, previewStartZ; - private transient boolean previewDashing = false; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewStartX = npc.posX; - previewStartZ = npc.posZ; - previewDashing = false; - - // Pick a random direction based on mode - DashDirection[] directions = dashMode == DashMode.AGGRESSIVE - ? AGGRESSIVE_DIRECTIONS - : DEFENSIVE_DIRECTIONS; - DashDirection dir = directions[RANDOM.nextInt(directions.length)]; - - float baseYaw; - if (previewTarget != null) { - double dx = previewTarget.posX - npc.posX; - double dz = previewTarget.posZ - npc.posZ; - baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); - } else { - baseYaw = npc.rotationYaw; - } - - float dashYaw = baseYaw + dir.getAngleOffset(); - float yawRad = (float) Math.toRadians(dashYaw); - previewDirX = -Math.sin(yawRad); - previewDirZ = Math.cos(yawRad); - previewDashing = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewDashing) return; - - double distTraveled = Math.sqrt( - Math.pow(npc.posX - previewStartX, 2) + - Math.pow(npc.posZ - previewStartZ, 2) - ); - - if (distTraveled >= dashDistance) { - previewDashing = false; - return; - } - - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewDirX * dashSpeed; - npc.posZ += previewDirZ * dashSpeed; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return (int) Math.ceil(dashDistance / dashSpeed) + 5; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 0f91869fa..77d137eb9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -12,7 +12,6 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; @@ -23,7 +22,6 @@ import noppes.npcs.api.ability.type.IAbilityDisc; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; /** * Disc ability: Spawns a flat spinning disc projectile. @@ -79,27 +77,27 @@ public class AbilityDisc extends Ability implements IAbilityDisc { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } // Start moving the disc that was spawned during windup if (discEntity != null && !discEntity.isDead) { - discEntity.startMoving(target); + if (isPreview()) { + discEntity.startPreviewFiring(); + } else { + discEntity.startMoving(target); + } } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class } @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn disc in charging mode on first tick of windup if (tick == 1) { - // Create disc in charging mode - follows caster based on anchor point during windup Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); discEntity = new EntityAbilityDisc( world, caster, target, @@ -107,11 +105,16 @@ public class AbilityDisc extends Ability implements IAbilityDisc { discRadius, discThickness, colorData, combatData, homingData, lightningData, lifespanData, trajectoryData, boomerang, boomerangDelay); - discEntity.setupCharging(anchorData, windUpTicks); + + if (isPreview()) { + discEntity.setupPreview(caster, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks); + } else { + discEntity.setupCharging(anchorData, windUpTicks); + } discEntity.setEffects(this.effects); discEntity.setSourceAbility(this); - world.spawnEntityInWorld(discEntity); + spawnAbilityEntity(world, discEntity); } } @@ -264,17 +267,7 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityDisc disc = new EntityAbilityDisc(npc.worldObj); - disc.setupPreview(npc, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks); - return disc; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java index 421861fcd..2fbd6cbda 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java @@ -14,12 +14,10 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.util.ValueUtil; import java.util.Arrays; @@ -89,19 +87,27 @@ public class AbilityDiscDual extends Ability { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - // Start moving the orb that was spawned during windup + // Start moving the disc that was spawned during windup if (discEntity != null && !discEntity.isDead) { - discEntity.startMoving(target); + if (isPreview()) { + discEntity.startPreviewFiring(); + } else { + discEntity.startMoving(target); + } } if (dualFire) { if (discEntity2 != null && !discEntity2.isDead && dualFireDelay <= 0) { - discEntity2.startMoving(target); + if (isPreview()) { + discEntity2.startPreviewFiring(); + } else { + discEntity2.startMoving(target); + } } } else if (discEntity2 != null) { discEntity2.setDead(); @@ -113,7 +119,7 @@ public class AbilityDiscDual extends Ability { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn disc in charging mode on first tick of windup if (tick == 1) { @@ -137,8 +143,13 @@ public class AbilityDiscDual extends Ability { discEntity.setSiblingEntityId(discEntity2.getEntityId()); discEntity2.setSiblingEntityId(discEntity.getEntityId()); - discEntity.setupCharging(anchorData[0], windUpTicks); - discEntity2.setupCharging(anchorData[1], windUpTicks); + if (isPreview()) { + discEntity.setupPreview(caster, discRadius, discThickness, displayData[0], lightningData[0], anchorData[0], windUpTicks); + discEntity2.setupPreview(caster, discRadius, discThickness, displayData[1], lightningData[1], anchorData[1], windUpTicks); + } else { + discEntity.setupCharging(anchorData[0], windUpTicks); + discEntity2.setupCharging(anchorData[1], windUpTicks); + } discEntity.setEffects(this.effects); @@ -148,8 +159,8 @@ public class AbilityDiscDual extends Ability { discEntity.setSourceAbility(this); discEntity2.setSourceAbility(this); - world.spawnEntityInWorld(discEntity); - world.spawnEntityInWorld(discEntity2); + spawnAbilityEntity(world, discEntity); + spawnAbilityEntity(world, discEntity2); } } @@ -164,7 +175,11 @@ public class AbilityDiscDual extends Ability { } if (tick == dualFireDelay && discEntity2 != null && !discEntity2.isDead) { - discEntity2.startMoving(target); + if (isPreview()) { + discEntity2.startPreviewFiring(); + } else { + discEntity2.startMoving(target); + } } } else { if (discEntity == null || discEntity.isDead) { @@ -511,17 +526,7 @@ public class AbilityDiscDual extends Ability { } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityDisc disc = new EntityAbilityDisc(npc.worldObj); - disc.setupPreview(npc, discRadius, discThickness, displayData[0], lightningData[0], anchorData[0], windUpTicks); - return disc; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 99ea47172..112b2a637 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -243,7 +243,7 @@ public class AbilityHazard extends Ability implements IAbilityHazard { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Check if hazard duration has ended if (tick >= durationTicks) { @@ -251,53 +251,55 @@ public class AbilityHazard extends Ability implements IAbilityHazard { return; } - damagedThisTick.clear(); - ticksSinceDamage++; + if (!isPreview()) { + damagedThisTick.clear(); + ticksSinceDamage++; - switch (placement) { - case FOLLOW_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - break; - case FOLLOW_TARGET: - if (target != null) { - zoneX = target.posX; - zoneY = target.posY; - zoneZ = target.posZ; - } - break; - default: - break; - } - - if (ticksSinceDamage >= damageInterval) { - ticksSinceDamage = 0; - - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - zoneX - radius, zoneY - heightBelow, zoneZ - radius, - zoneX + radius, zoneY + heightAbove, zoneZ + radius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); - - for (EntityLivingBase entity : entities) { - if (entity == caster && !affectsCaster) continue; - if (damagedThisTick.contains(entity.getEntityId())) continue; - if (!isInZone(entity, caster)) continue; - - if (damagePerSecond > 0) { - if (ignoreInvulnFrames) { - entity.hurtResistantTime = 0; + switch (placement) { + case FOLLOW_CASTER: + zoneX = caster.posX; + zoneY = caster.posY; + zoneZ = caster.posZ; + break; + case FOLLOW_TARGET: + if (target != null) { + zoneX = target.posX; + zoneY = target.posY; + zoneZ = target.posZ; } - // Apply damage with scripted event support (no knockback for hazard) - boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0); - if (!wasHit) continue; // Skip debuffs if hit was cancelled - } + break; + default: + break; + } - applyDebuffs(entity); - damagedThisTick.add(entity.getEntityId()); + if (ticksSinceDamage >= damageInterval) { + ticksSinceDamage = 0; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + zoneX - radius, zoneY - heightBelow, zoneZ - radius, + zoneX + radius, zoneY + heightAbove, zoneZ + radius + ); + + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + + for (EntityLivingBase entity : entities) { + if (entity == caster && !affectsCaster) continue; + if (damagedThisTick.contains(entity.getEntityId())) continue; + if (!isInZone(entity, caster)) continue; + + if (damagePerSecond > 0) { + if (ignoreInvulnFrames) { + entity.hurtResistantTime = 0; + } + // Apply damage with scripted event support (no knockback for hazard) + boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0); + if (!wasHit) continue; // Skip debuffs if hit was cancelled + } + + applyDebuffs(entity); + damagedThisTick.add(entity.getEntityId()); + } } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index c1faf000b..b60c46d9d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -75,27 +75,31 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; - getHealedAllies().clear(); + if (!isPreview()) { + getHealedAllies().clear(); - // Always find allies if we're healing them (needed for both instant and HoT) - if (healAllies && healRadius > 0) { - findAlliesInRadius(caster, world); + // Always find allies if we're healing them (needed for both instant and HoT) + if (healAllies && healRadius > 0) { + findAlliesInRadius(caster, world); + } + + if (instantHeal) { + // Instant heal - apply all healing now + if (healSelf) { + healEntity(caster); + spawnHealParticles(world, caster); + } + + for (EntityLivingBase ally : getHealedAllies()) { + healEntity(ally); + spawnHealParticles(world, ally); + } + } } if (instantHeal) { - // Instant heal - apply all healing now - if (healSelf) { - healEntity(caster); - spawnHealParticles(world, caster); - } - - for (EntityLivingBase ally : getHealedAllies()) { - healEntity(ally); - spawnHealParticles(world, ally); - } - // Instant heal completes immediately signalCompletion(); } @@ -104,7 +108,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote || instantHeal) return; + if ((world.isRemote && !isPreview()) || instantHeal) return; // Heal over time - distribute heal across duration ticks if (tick % 10 == 0) { 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 0e236de32..dd5d5fc09 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 @@ -68,51 +68,53 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - // Calculate forward and right vectors from caster yaw - float yawRad = (float) Math.toRadians(caster.rotationYaw); - double forwardX = -Math.sin(yawRad); - double forwardZ = Math.cos(yawRad); - double rightX = forwardZ; // perpendicular right - double rightZ = -forwardX; + if (!isPreview()) { + // Calculate forward and right vectors from caster yaw + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double forwardX = -Math.sin(yawRad); + double forwardZ = Math.cos(yawRad); + double rightX = forwardZ; // perpendicular right + double rightZ = -forwardX; - // Search area: AABB that encompasses the rectangle - float searchDist = Math.max(hitLength, hitWidth) + 1.0f; - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity( - caster, caster.boundingBox.expand(searchDist, 2, searchDist)); + // Search area: AABB that encompasses the rectangle + float searchDist = Math.max(hitLength, hitWidth) + 1.0f; + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity( + caster, caster.boundingBox.expand(searchDist, 2, searchDist)); - boolean anyHit = false; - for (Entity entity : entities) { - if (!(entity instanceof EntityLivingBase) || entity == caster) continue; - EntityLivingBase livingTarget = (EntityLivingBase) entity; + boolean anyHit = false; + for (Entity entity : entities) { + if (!(entity instanceof EntityLivingBase) || entity == caster) continue; + EntityLivingBase livingTarget = (EntityLivingBase) entity; - double dx = livingTarget.posX - caster.posX; - double dz = livingTarget.posZ - caster.posZ; + double dx = livingTarget.posX - caster.posX; + double dz = livingTarget.posZ - caster.posZ; - // Project onto forward direction (must be in front, within hitLength) - double forwardDist = dx * forwardX + dz * forwardZ; - if (forwardDist < 0 || forwardDist > hitLength) continue; + // Project onto forward direction (must be in front, within hitLength) + double forwardDist = dx * forwardX + dz * forwardZ; + if (forwardDist < 0 || forwardDist > hitLength) continue; - // Project onto right direction (must be within hitWidth to each side) - double sideDist = dx * rightX + dz * rightZ; - if (Math.abs(sideDist) > hitWidth) continue; + // Project onto right direction (must be within hitWidth to each side) + double sideDist = dx * rightX + dz * rightZ; + if (Math.abs(sideDist) > hitWidth) continue; - // Entity is within the rectangle - apply damage - boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); - if (wasHit) { - applyEffects(livingTarget); - anyHit = true; + // Entity is within the rectangle - apply damage + boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); + if (wasHit) { + applyEffects(livingTarget); + anyHit = true; + } } - } - // Play hit sound even if nothing was hit (the attack still happens) - if (!anyHit) { - world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + // Play hit sound even if nothing was hit (the attack still happens) + if (!anyHit) { + world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index 4be2315d5..d211de6d2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -12,7 +12,6 @@ import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; @@ -22,7 +21,6 @@ import noppes.npcs.api.ability.type.IAbilityLaserShot; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; /** * Laser Shot ability: Fast expanding thin line that pierces through targets. @@ -84,7 +82,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; if (tick == 1) { Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); @@ -96,17 +94,21 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { expansionSpeed, lingerTicks ); - laserEntity.setupCharging(anchorData, windUpTicks); + if (isPreview()) { + laserEntity.setupPreview(caster, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); + } else { + laserEntity.setupCharging(anchorData, windUpTicks); + } laserEntity.setEffects(this.effects); laserEntity.setSourceAbility(this); - world.spawnEntityInWorld(laserEntity); + spawnAbilityEntity(world, laserEntity); } } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } @@ -235,25 +237,10 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityLaser laser = new EntityAbilityLaser(npc.worldObj); - laser.setupPreview(npc, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); - return laser; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; } - @Override - public boolean spawnPreviewDuringWindup() { - return false; // Laser has no charging, spawns at active phase - } - @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 96881cf4e..6a87b38b4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -75,14 +75,18 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } // Start moving the orb that was spawned during windup if (orbEntity != null && !orbEntity.isDead) { - orbEntity.startMoving(target); + if (isPreview()) { + orbEntity.startPreviewFiring(); + } else { + orbEntity.startMoving(target); + } } // Ability stays active until entity dies (prevents firing another while projectile is alive) @@ -91,21 +95,25 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn orb in charging mode on first tick of windup if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); orbEntity = new EntityAbilityOrb( world, caster, target, spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, displayData, combatData, homingData, lightningData, lifespanData, trajectoryData); - orbEntity.setupCharging(anchorData, windUpTicks); + + if (isPreview()) { + orbEntity.setupPreview(caster, orbSize, displayData, lightningData, anchorData, windUpTicks); + } else { + orbEntity.setupCharging(anchorData, windUpTicks); + } orbEntity.setEffects(this.effects); orbEntity.setSourceAbility(this); - world.spawnEntityInWorld(orbEntity); + spawnAbilityEntity(world, orbEntity); } } @@ -405,17 +413,7 @@ public class AbilityOrb extends Ability implements IAbilityOrb { } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, displayData, lightningData, anchorData, windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java index 71be07a34..dda01f68a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java @@ -89,7 +89,7 @@ public class AbilityOrbBarrage extends Ability { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } @@ -107,12 +107,10 @@ public class AbilityOrbBarrage extends Ability { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn orb in charging mode on first tick of windup if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup - if (dualCharging) { chargingEntities = new EntityAbilityOrb[2]; } else { @@ -128,11 +126,15 @@ public class AbilityOrbBarrage extends Ability { colorData, combatData, homingData, lightningData, lifespanData, trajectoryData ); - orbEntity.setupCharging(anchorData[i], windUpTicks); + if (isPreview()) { + orbEntity.setupPreview(caster, orbSize, colorData, lightningData, anchorData[i], windUpTicks); + } else { + orbEntity.setupCharging(anchorData[i], windUpTicks); + } orbEntity.setSourceAbility(this); chargingEntities[i] = orbEntity; - world.spawnEntityInWorld(orbEntity); + spawnAbilityEntity(world, orbEntity); } } } @@ -540,17 +542,7 @@ public class AbilityOrbBarrage extends Ability { public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, colorData, lightningData, anchorData[0], windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java index bd2870438..7b8362464 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java @@ -80,19 +80,27 @@ public class AbilityOrbDual extends Ability { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } // Start moving the orb that was spawned during windup if (orbEntity != null && !orbEntity.isDead) { - orbEntity.startMoving(target); + if (isPreview()) { + orbEntity.startPreviewFiring(); + } else { + orbEntity.startMoving(target); + } } if (dualFire) { if (orbEntity2 != null && !orbEntity2.isDead && dualFireDelay <= 0) { - orbEntity2.startMoving(target); + if (isPreview()) { + orbEntity2.startPreviewFiring(); + } else { + orbEntity2.startMoving(target); + } } } else if (orbEntity2 != null) { orbEntity2.setDead(); @@ -104,11 +112,10 @@ public class AbilityOrbDual extends Ability { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Spawn orb in charging mode on first tick of windup if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0]); orbEntity = new EntityAbilityOrb( world, caster, target, @@ -124,8 +131,13 @@ public class AbilityOrbDual extends Ability { orbEntity.setSiblingEntityId(orbEntity2.getEntityId()); orbEntity2.setSiblingEntityId(orbEntity.getEntityId()); - orbEntity.setupCharging(anchorData[0], windUpTicks); - orbEntity2.setupCharging(anchorData[1], windUpTicks); + if (isPreview()) { + orbEntity.setupPreview(caster, orbSize, displayData[0], lightningData[0], anchorData[0], windUpTicks); + orbEntity2.setupPreview(caster, orbSize, displayData[1], lightningData[1], anchorData[1], windUpTicks); + } else { + orbEntity.setupCharging(anchorData[0], windUpTicks); + orbEntity2.setupCharging(anchorData[1], windUpTicks); + } orbEntity.setEffects(this.effects); @@ -135,8 +147,8 @@ public class AbilityOrbDual extends Ability { orbEntity.setSourceAbility(this); orbEntity2.setSourceAbility(this); - world.spawnEntityInWorld(orbEntity); - world.spawnEntityInWorld(orbEntity2); + spawnAbilityEntity(world, orbEntity); + spawnAbilityEntity(world, orbEntity2); } } @@ -570,17 +582,7 @@ public class AbilityOrbDual extends Ability { } @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, displayData[0], lightningData[0], anchorData[0], windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index e5f6f5df6..75c27a507 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -62,59 +62,64 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote || target == null) return; - - // Calculate direction to target - double dx = target.posX - caster.posX; - double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); - double dz = target.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (len > 0) { - dx /= len; - dy /= len; - dz /= len; + if ((world.isRemote && !isPreview()) || target == null) { + signalCompletion(); + return; } - // Deal instant damage with scripted event support - // TODO: Use custom EntityAbilityProjectile for actual tracking - applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); + if (!isPreview()) { + // Calculate direction to target + double dx = target.posX - caster.posX; + double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); + double dz = target.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - // Play sound - world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); + if (len > 0) { + dx /= len; + dy /= len; + dz /= len; + } - // Handle splash damage for explosive projectiles - if (explosive && explosionRadius > 0) { - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity(target, - target.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + // Deal instant damage with scripted event support + // TODO: Use custom EntityAbilityProjectile for actual tracking + applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); - for (Entity entity : entities) { - if (entity instanceof EntityLivingBase && entity != caster) { - EntityLivingBase living = (EntityLivingBase) entity; - float dist = target.getDistanceToEntity(living); - if (dist < explosionRadius) { - float falloff = 1.0f - (dist / explosionRadius); - // Apply splash damage with scripted event support (no knockback) - applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); + // Play sound + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); + + // Handle splash damage for explosive projectiles + if (explosive && explosionRadius > 0) { + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity(target, + target.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + + for (Entity entity : entities) { + if (entity instanceof EntityLivingBase && entity != caster) { + EntityLivingBase living = (EntityLivingBase) entity; + float dist = target.getDistanceToEntity(living); + if (dist < explosionRadius) { + float falloff = 1.0f - (dist / explosionRadius); + // Apply splash damage with scripted event support (no knockback) + applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); + } } } + + // Explosion particles + world.playSoundAtEntity(target, "random.explode", 0.5f, 1.0f); + for (int i = 0; i < 10; i++) { + world.spawnParticle("explode", + target.posX + (world.rand.nextDouble() - 0.5) * explosionRadius, + target.posY + world.rand.nextDouble() * target.height, + target.posZ + (world.rand.nextDouble() - 0.5) * explosionRadius, + 0, 0.1, 0); + } } - // Explosion particles - world.playSoundAtEntity(target, "random.explode", 0.5f, 1.0f); - for (int i = 0; i < 10; i++) { - world.spawnParticle("explode", - target.posX + (world.rand.nextDouble() - 0.5) * explosionRadius, - target.posY + world.rand.nextDouble() * target.height, - target.posZ + (world.rand.nextDouble() - 0.5) * explosionRadius, - 0, 0.1, 0); - } + // Spawn projectile particles (visual trail) + spawnProjectileParticles(world, caster, target); } - // Spawn projectile particles (visual trail) - spawnProjectileParticles(world, caster, target); - // Projectile is instant signalCompletion(); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 775c15515..6788a3ea3 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -63,48 +63,50 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Shockwave is instant - apply effect immediately after windup + if (!isPreview()) { + // Shockwave is instant - apply effect immediately after windup - // Get all entities in radius - AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + // Get all entities in radius + AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + int count = 0; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist > pushRadius) continue; + double dist = caster.getDistanceToEntity(entity); + if (dist > pushRadius) continue; - count++; - if (count > maxTargets) break; + count++; + if (count > maxTargets) break; - // Calculate push direction (away from caster) - double dx = entity.posX - caster.posX; - double dz = entity.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dz * dz); + // Calculate push direction (away from caster) + double dx = entity.posX - caster.posX; + double dz = entity.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - dx /= len; - dz /= len; - } else { - // Entity is directly on top of caster, push in random direction - double angle = Math.random() * Math.PI * 2; - dx = Math.cos(angle); - dz = Math.sin(angle); - } + if (len > 0) { + dx /= len; + dz /= len; + } else { + // Entity is directly on top of caster, push in random direction + double angle = Math.random() * Math.PI * 2; + dx = Math.cos(angle); + dz = Math.sin(angle); + } - // Scale knockback by distance (closer = stronger) - float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f; - float finalPush = pushStrength * distFactor; - // Apply damage with custom knockback direction - boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz); + // Scale knockback by distance (closer = stronger) + float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f; + float finalPush = pushStrength * distFactor; + // Apply damage with custom knockback direction + boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz); - // Apply effects if hit connected - if (wasHit) { - applyEffects(entity); + // Apply effects if hit connected + if (wasHit) { + applyEffects(entity); + } } } } 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 1be741d35..15b4060b8 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 @@ -187,11 +187,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.motionZ = 0; caster.motionY = vy; hasLaunched = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); } - caster.velocityChanged = true; - caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + if (!isPreview()) { + caster.velocityChanged = true; + caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + } return; } @@ -233,10 +235,12 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.motionY = vy; hasLaunched = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); } - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } // Face the target float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); @@ -252,7 +256,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { airTicks++; // Continuously reset fall distance during slam to prevent fall damage - caster.fallDistance = 0; + if (!isPreview()) { + caster.fallDistance = 0; + } // Check for landing if (caster.onGround && airTicks > 3) { @@ -268,11 +274,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } // While in air, face toward target - double dx = targetX - caster.posX; - double dz = targetZ - caster.posZ; - float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); - caster.rotationYaw = targetYaw; - caster.rotationYawHead = targetYaw; + if (!isPreview()) { + double dx = targetX - caster.posX; + double dz = targetZ - caster.posZ; + float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); + caster.rotationYaw = targetYaw; + caster.rotationYawHead = targetYaw; + } } /** @@ -280,22 +288,25 @@ public class AbilitySlam extends Ability implements IAbilitySlam { */ private void onLanding(EntityLivingBase caster, World world) { hasLanded = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } // Signal that the ability has completed its active phase signalCompletion(); - // Reset fall distance to prevent fall damage on landing - caster.fallDistance = 0; - // Stop horizontal momentum caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; - if (world.isRemote) return; + if (!isPreview()) { + // Reset fall distance to prevent fall damage on landing + caster.fallDistance = 0; + caster.velocityChanged = true; + } + + if (world.isRemote && !isPreview()) return; + if (isPreview()) return; // Play slam impact sound on landing world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f); @@ -361,7 +372,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } hasLaunched = false; @@ -371,7 +382,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } hasLaunched = false; @@ -387,97 +398,8 @@ public class AbilitySlam extends Ability implements IAbilitySlam { airTicks = 0; } - // ==================== PREVIEW MODE ==================== - - private transient double previewVelX, previewVelY, previewVelZ; - private transient boolean previewLaunched = false; - private transient double previewGroundY; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewLaunched = false; - - double tx, ty, tz; - if (previewTarget != null && targetingMode == TargetingMode.AOE_TARGET) { - tx = previewTarget.posX; - ty = previewTarget.posY; - tz = previewTarget.posZ; - } else { - tx = npc.posX; - ty = npc.posY; - tz = npc.posZ; - } - - previewGroundY = npc.posY; - - double dx = tx - npc.posX; - double dz = tz - npc.posZ; - double horizontalDist = Math.sqrt(dx * dx + dz * dz); - - // Calculate vertical velocity for exact leapHeight - double arcHeight = Math.max(1.0, leapHeight); - double vy = calculateLaunchVelocity(arcHeight); - - if (horizontalDist < 0.5) { - previewVelX = 0; - previewVelZ = 0; - previewVelY = vy; - } else { - if (horizontalDist > maxRange) { - double scale = maxRange / horizontalDist; - dx *= scale; - dz *= scale; - horizontalDist = maxRange; - } - - double speedFactor = Math.max(0.1, leapSpeed); - int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40)); - double drag = 0.91; - double dragPowN = Math.pow(drag, flightTicks); - double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN); - - double dirX = dx / horizontalDist; - double dirZ = dz / horizontalDist; - previewVelX = dirX * vHorizontal; - previewVelZ = dirZ * vHorizontal; - previewVelY = vy; - } - previewLaunched = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewLaunched) return; - - // Apply velocity - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewVelX; - npc.posY += previewVelY; - npc.posZ += previewVelZ; - - // Gravity and drag - previewVelY -= 0.08; - previewVelY *= 0.98; - previewVelX *= 0.91; - previewVelZ *= 0.91; - - // Ground clamp - stop falling below starting Y - if (npc.posY < previewGroundY && previewVelY < 0) { - npc.posY = previewGroundY; - previewVelY = 0; - previewVelX = 0; - previewVelZ = 0; - previewLaunched = false; - } - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return 60; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 2fcc62956..3155310ef 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -73,7 +73,7 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } @@ -85,7 +85,12 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { sweepSpeed, numberOfRotations, damage, damageInterval, piercing, lockOnTarget); - world.spawnEntityInWorld(activeEntity); + + if (isPreview()) { + activeEntity.setupPreview(caster); + } + + spawnAbilityEntity(world, activeEntity); // Ability stays active until entity dies (prevents firing another while projectile is alive) // Movement locking is handled separately by the base class @@ -200,6 +205,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } + @Override + public int getMaxPreviewDuration() { + return (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index cb06b7b6b..fe847bf3a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -128,7 +128,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } private void performBlink(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; double oldX = caster.posX; double oldY = caster.posY; @@ -137,36 +137,47 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { Vec3 destination = calculateDestination(caster, target, world); if (destination == null) return; - boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; - if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, - destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { - destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + if (!isPreview()) { + boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; + if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, + destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { + destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + destination.xCoord, destination.yCoord, destination.zCoord); + if (destination == null) return; + } + + destination = findSafeDestination(world, oldX, oldY, oldZ, destination.xCoord, destination.yCoord, destination.zCoord); if (destination == null) return; + + // Damage at origin + if (damageAtStart) { + dealDamageAt(caster, world, oldX, oldY, oldZ); + } + + // Spawn particles at origin + spawnTeleportParticles(world, oldX, oldY, oldZ); } - destination = findSafeDestination(world, oldX, oldY, oldZ, - destination.xCoord, destination.yCoord, destination.zCoord); - if (destination == null) return; - - // Damage at origin - if (damageAtStart) { - dealDamageAt(caster, world, oldX, oldY, oldZ); - } - - // Spawn particles at origin - spawnTeleportParticles(world, oldX, oldY, oldZ); - // Teleport - caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + if (isPreview()) { + caster.setPosition(destination.xCoord, destination.yCoord, destination.zCoord); + caster.prevPosX = destination.xCoord; + caster.prevPosY = destination.yCoord; + caster.prevPosZ = destination.zCoord; + } else { + caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + } caster.fallDistance = 0; - // Spawn particles at destination - spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); + if (!isPreview()) { + // Spawn particles at destination + spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); - // Damage at destination - if (damageAtEnd) { - dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + // Damage at destination + if (damageAtEnd) { + dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + } } // Face target after teleport @@ -561,6 +572,12 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.damageRadius = damageRadius; } + @Override + public int getMaxPreviewDuration() { + int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; + return blinkLimit * blinkDelayTicks + 10; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 102c4395f..1623bacd8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -207,26 +207,28 @@ public class AbilityTrap extends Ability implements IAbilityTrap { return; } - AxisAlignedBB box = AxisAlignedBB.getBoundingBox( - trapX - triggerRadius, trapY - 1, trapZ - triggerRadius, - trapX + triggerRadius, trapY + 2, trapZ + triggerRadius - ); + if (!isPreview()) { + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + trapX - triggerRadius, trapY - 1, trapZ - triggerRadius, + trapX + triggerRadius, trapY + 2, trapZ + triggerRadius + ); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; - if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; + if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; - double dx = entity.posX - trapX; - double dz = entity.posZ - trapZ; - double dist = Math.sqrt(dx * dx + dz * dz); + double dx = entity.posX - trapX; + double dz = entity.posZ - trapZ; + double dist = Math.sqrt(dx * dx + dz * dz); - if (dist <= triggerRadius) { - triggerTrap(caster, entity, world); - return; + if (dist <= triggerRadius) { + triggerTrap(caster, entity, world); + return; + } } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index e31a1e6ce..73f9816f7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -84,29 +84,31 @@ public class AbilityVortex extends Ability implements IAbilityVortex { pullComplete = false; ticksSincePullDamage = 0; - if (aoe) { - AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + if (!isPreview()) { + if (aoe) { + AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + int count = 0; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist <= pullRadius) { - getPulledEntities().add(entity.getUniqueID()); - count++; - if (count >= maxTargets) break; + double dist = caster.getDistanceToEntity(entity); + if (dist <= pullRadius) { + getPulledEntities().add(entity.getUniqueID()); + count++; + if (count >= maxTargets) break; + } } - } - } else { - // Single target mode - still check pullRadius - if (target != null && !target.isDead) { - double dist = caster.getDistanceToEntity(target); - if (dist <= pullRadius) { - getPulledEntities().add(target.getUniqueID()); + } else { + // Single target mode - still check pullRadius + if (target != null && !target.isDead) { + double dist = caster.getDistanceToEntity(target); + if (dist <= pullRadius) { + getPulledEntities().add(target.getUniqueID()); + } } } } @@ -114,6 +116,12 @@ public class AbilityVortex extends Ability implements IAbilityVortex { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + if (isPreview()) { + // No entities to pull in preview, just run animation for a duration + if (tick >= 60) signalCompletion(); + return; + } + if (pullComplete || getPulledEntities().isEmpty()) { signalCompletion(); return; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 60175169a..1427b298f 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -222,24 +222,39 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { setCharging(false); - // Update start position to current position + // Origin (tail) stays at the charged position startX = posX; startY = posY; startZ = posZ; + // Reset head offset to origin + headOffsetX = 0; + headOffsetY = 0; + headOffsetZ = 0; + prevHeadOffsetX = 0; + prevHeadOffsetY = 0; + prevHeadOffsetZ = 0; + + // Origin no longer follows owner after firing + attachedToOwner = false; + // Sync prev position to prevent visual jump on first frame prevPosX = posX; prevPosY = posY; prevPosZ = posZ; + // Reset trail + trailPoints.clear(); + trailPointAges.clear(); + trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); + // Fire forward based on owner facing direction Entity owner = getOwnerEntity(); if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = 0; // Fire horizontally - motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - motionY = -Math.sin(pitch) * getSpeed(); - motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); + motionX = -Math.sin(yaw) * getSpeed(); + motionY = 0; + motionZ = Math.cos(yaw) * getSpeed(); } else { motionX = getSpeed(); motionY = 0; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index bbd77abd0..3578ac9bf 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -38,7 +38,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { private int chargeTick = 0; private float targetDiscRadius = 1.0f; // Full radius to grow to during charging private float targetDiscThickness = 0.2f; // Full thickness to grow to during charging - private EnergyAnchorData anchorData = new EnergyAnchorData(); // Data watcher index for charging state (synced to clients) private static final int DW_CHARGING = 20; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 1a036573e..9c09bd467 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -1,6 +1,5 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; @@ -46,7 +45,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { private boolean charging = false; private int chargeDuration = 40; private int chargeTick = 0; - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); private float targetSize = 1.0f; // Full size to grow to during charging // Data watcher index for charging state (synced to clients) @@ -454,7 +452,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; - anchorData.readNBT(nbt); } @Override @@ -476,7 +473,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { nbt.setInteger("ChargeDuration", chargeDuration); nbt.setInteger("ChargeTick", chargeTick); nbt.setFloat("TargetSize", targetSize); - anchorData.writeNBT(nbt); } /** diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index 8eceb11de..4d072090e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -60,6 +60,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa private int maxTicks = 400; private long deathWorldTime = -1; + // Preview mode + private boolean previewMode = false; + private EntityLivingBase previewOwner = null; + // Damage state private transient int ticksSinceDamage = 0; private transient Set hitThisTick = new HashSet<>(); @@ -281,7 +285,16 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa target.velocityChanged = true; } + /** + * Set up preview mode. Owner is stored directly since world entity lookup won't work. + */ + public void setupPreview(EntityLivingBase owner) { + this.previewMode = true; + this.previewOwner = owner; + } + private Entity getOwner() { + if (previewMode && previewOwner != null) return previewOwner; if (ownerEntityId == -1) return null; return worldObj.getEntityByID(ownerEntityId); } diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index 3255452c9..4331ab0ea 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -509,6 +509,8 @@ public class ClientProxy extends CommonProxy { } else { abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld); abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png"; + abilityNpc.height = 1.8f; + abilityNpc.width = 0.6f; } return new GuiNpcManageAbilities(abilityNpc, npc != null); } diff --git a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java index 90204fdc4..2da4a1a7b 100644 --- a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java +++ b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java @@ -4,15 +4,10 @@ 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.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.PreviewEntityHandler; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.entity.EntityAbilityBeam; -import kamkeel.npcs.entity.EntityAbilityDisc; -import kamkeel.npcs.entity.EntityAbilityLaser; -import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.entity.EntityAbilityProjectile; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.world.World; import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.entity.EntityCustomNpc; @@ -25,38 +20,39 @@ import java.util.List; /** * Client-side executor for previewing abilities in the GUI. * - * Lifecycle: - * 1. WINDUP phase - plays windup animation, entities spawn and charge - * 2. ACTIVE phase - plays active animation, entities fire and move - * 3. EXTENDED phase - continues for +100 ticks after animations to see results - * 4. IDLE - preview complete + * Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick) + * with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true. * - * Features: - * - Invisible fake target NPC placed in front of the preview NPC for targeting - * - NPC movement tracking for abilities that move the NPC (e.g. slam) + * Lifecycle: + * 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn + * 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated + * 3. EXTENDED phase - 100 extra ticks to observe results (entities continue updating) + * 4. IDLE - preview complete */ @SideOnly(Side.CLIENT) -public class AbilityPreviewExecutor { +public class AbilityPreviewExecutor implements PreviewEntityHandler { // ==================== PREVIEW STATE ==================== private Ability previewAbility; private EntityNPCInterface previewNpc; - private AbilityPhase phase = AbilityPhase.IDLE; + + /** Executor's own phase tracking (separate from ability.getPhase()) */ + private enum ExecutorPhase { IDLE, WINDUP, ACTIVE, EXTENDED } + private ExecutorPhase executorPhase = ExecutorPhase.IDLE; + private int currentTick = 0; private boolean playing = false; private boolean paused = false; // ==================== TIMING ==================== private static final int EXTENDED_DURATION = 100; - private int activeDuration = 40; + private int maxPreviewDuration = 200; // ==================== FAKE TARGET ==================== - /** Invisible fake target NPC for ability targeting (placed 5 blocks in front of preview NPC) */ private EntityNPCInterface fakeTarget; private static final double TARGET_DISTANCE = 5.0; // ==================== NPC START POSITION ==================== - /** Saved NPC position for restoring after movement abilities */ private double npcStartX, npcStartY, npcStartZ; // ==================== PREVIEW CONTENT ==================== @@ -74,7 +70,8 @@ public class AbilityPreviewExecutor { } /** - * Start previewing an ability. + * Start previewing an ability using unified execution. + * Sets previewMode=true on the ability, then calls its real methods. */ public void startPreview(Ability ability, EntityNPCInterface npc) { stop(); @@ -84,31 +81,35 @@ public class AbilityPreviewExecutor { this.currentTick = 0; this.playing = true; this.paused = false; - this.activeDuration = ability.getPreviewActiveDuration(); + this.maxPreviewDuration = ability.getMaxPreviewDuration(); // Save NPC start position for restoring later this.npcStartX = npc.posX; this.npcStartY = npc.posY; this.npcStartZ = npc.posZ; + // Enable preview mode on the ability + ability.setPreviewMode(true); + ability.setPreviewEntityHandler(this); + // Create invisible fake target NPC for targeting createFakeTarget(npc); - // Set preview target on the ability - ability.setPreviewTarget(fakeTarget); - // Start tracking NPC movement if (parentGui != null) { parentGui.startTrackingMovement(); } + // Use the ability's real start() method with the fake target + ability.start(fakeTarget); + if (ability.getWindUpTicks() <= 0) { // No windup — go straight to active - this.phase = AbilityPhase.ACTIVE; + this.executorPhase = ExecutorPhase.ACTIVE; transitionToActive(); } else { // Normal windup flow - this.phase = AbilityPhase.WINDUP; + this.executorPhase = ExecutorPhase.WINDUP; // Create telegraph for preview previewTelegraph = ability.createTelegraph(npc, fakeTarget); @@ -121,24 +122,17 @@ public class AbilityPreviewExecutor { data.setAnimation(windUpAnim); data.animation.paused = false; } - - // Spawn preview entity on first tick if ability spawns during windup - if (ability.spawnPreviewDuringWindup()) { - spawnPreviewEntity(); - } } } /** * Create an invisible fake target NPC placed in front of the preview NPC. - * This entity is NOT rendered - it only exists for ability targeting logic. */ private void createFakeTarget(EntityNPCInterface npc) { if (npc.worldObj == null) return; try { fakeTarget = new EntityCustomNpc(npc.worldObj); - // Position target in front of NPC based on its facing direction float facingYaw = GuiAbilityInterface.NPC_FACING_YAW; double yawRad = Math.toRadians(facingYaw); double targetX = npc.posX - Math.sin(yawRad) * TARGET_DISTANCE; @@ -153,15 +147,12 @@ public class AbilityPreviewExecutor { } } - /** - * Get the fake target entity for abilities that need a target. - */ public EntityLivingBase getFakeTarget() { return fakeTarget; } public void play() { - if (previewAbility == null || phase == AbilityPhase.IDLE) { + if (previewAbility == null || executorPhase == ExecutorPhase.IDLE) { return; } playing = true; @@ -187,9 +178,17 @@ public class AbilityPreviewExecutor { } public void stop() { + // Clean up the ability + if (previewAbility != null) { + previewAbility.cleanup(); + previewAbility.setPreviewMode(false); + previewAbility.setPreviewEntityHandler(null); + previewAbility.reset(); + } + playing = false; paused = false; - phase = AbilityPhase.IDLE; + executorPhase = ExecutorPhase.IDLE; currentTick = 0; previewTelegraph = null; @@ -211,9 +210,11 @@ public class AbilityPreviewExecutor { previewNpc.prevPosX = npcStartX; previewNpc.prevPosY = npcStartY; previewNpc.prevPosZ = npcStartZ; + previewNpc.motionX = 0; + previewNpc.motionY = 0; + previewNpc.motionZ = 0; } - // Remove fake target fakeTarget = null; if (previewNpc != null) { @@ -224,7 +225,7 @@ public class AbilityPreviewExecutor { } /** - * Tick the preview forward. + * Tick the preview forward. Calls real ability methods. */ public void tick() { if (!playing || paused || previewAbility == null || previewNpc == null) { @@ -239,14 +240,14 @@ public class AbilityPreviewExecutor { tickEntities(); - switch (phase) { + switch (executorPhase) { case WINDUP: tickWindup(); break; case ACTIVE: tickActive(); break; - case IDLE: + case EXTENDED: tickExtended(); break; default: @@ -255,7 +256,8 @@ public class AbilityPreviewExecutor { } private void tickWindup() { - previewAbility.onPreviewWindUpTick(previewNpc, currentTick); + // Call the REAL windup tick method + previewAbility.onWindUpTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); if (currentTick >= previewAbility.getWindUpTicks()) { transitionToActive(); @@ -263,35 +265,41 @@ public class AbilityPreviewExecutor { } private void tickActive() { - previewAbility.onPreviewActiveTick(previewNpc, currentTick); + // Call the REAL active tick method + previewAbility.onActiveTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); - if (currentTick == 1 && !previewAbility.spawnPreviewDuringWindup()) { - spawnPreviewEntity(); - fireEntities(); + // Simulate physics for movement abilities + simulatePhysics(); + + // Check if the ability signaled completion (phase went to IDLE) + if (previewAbility.getPhase() == AbilityPhase.IDLE) { + transitionToExtended(); + return; } - if (currentTick >= activeDuration) { + // Safety timeout + if (currentTick >= maxPreviewDuration) { transitionToExtended(); } } private void tickExtended() { + // Continue ticking entities so they can finish their animations if (currentTick >= EXTENDED_DURATION) { playing = false; } } private void transitionToActive() { - phase = AbilityPhase.ACTIVE; + executorPhase = ExecutorPhase.ACTIVE; currentTick = 0; previewTelegraph = null; - // Notify ability of execution (for movement abilities like Slam/Charge/Dash) - previewAbility.onPreviewExecute(previewNpc); - - fireEntities(); + // Call the REAL onExecute method (fires entities, initiates movement, etc.) + previewAbility.onExecute(previewNpc, fakeTarget, previewNpc.worldObj); + // Start active animation Animation activeAnim = previewAbility.getActiveAnimation(); if (activeAnim != null && previewNpc != null) { AnimationData data = previewNpc.display.animationData; @@ -301,7 +309,7 @@ public class AbilityPreviewExecutor { } private void transitionToExtended() { - phase = AbilityPhase.IDLE; + executorPhase = ExecutorPhase.EXTENDED; currentTick = 0; if (previewNpc != null) { @@ -310,26 +318,40 @@ public class AbilityPreviewExecutor { } } - private void spawnPreviewEntity() { - Entity entity = previewAbility.createPreviewEntity(previewNpc); - if (entity != null) { - previewEntities.add(entity); - if (parentGui != null) { - parentGui.addPreviewEntity(entity); - } - } - } + /** + * Simulate basic physics for movement abilities (Slam, Charge, Dash). + * Applies gravity, drag, and ground clamping to NPC position. + */ + private void simulatePhysics() { + if (!previewAbility.hasAbilityMovement()) return; + if (previewNpc == null) return; - private void fireEntities() { - for (Entity entity : previewEntities) { - if (entity instanceof EntityAbilityOrb) { - ((EntityAbilityOrb) entity).startPreviewFiring(); - } else if (entity instanceof EntityAbilityBeam) { - ((EntityAbilityBeam) entity).startPreviewFiring(); - } else if (entity instanceof EntityAbilityDisc) { - ((EntityAbilityDisc) entity).startPreviewFiring(); - } + // Save previous position for interpolation + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + + // Apply velocity + previewNpc.posX += previewNpc.motionX; + previewNpc.posY += previewNpc.motionY; + previewNpc.posZ += previewNpc.motionZ; + + // Apply gravity + previewNpc.motionY -= 0.08; + previewNpc.motionY *= 0.98; + + // Apply horizontal drag + previewNpc.motionX *= 0.91; + previewNpc.motionZ *= 0.91; + + // Ground clamp: if below start position and falling, stop + if (previewNpc.posY < npcStartY && previewNpc.motionY < 0) { + previewNpc.posY = npcStartY; + previewNpc.motionY = 0; + previewNpc.onGround = true; } + + previewNpc.fallDistance = 0; } private void tickEntities() { @@ -347,12 +369,38 @@ public class AbilityPreviewExecutor { } } + // ==================== PreviewEntityHandler ==================== + + @Override + public void onEntitySpawned(Entity entity) { + if (entity == null) return; + previewEntities.add(entity); + if (parentGui != null) { + parentGui.addPreviewEntity(entity); + } + } + + @Override + public void onEntityRemoved(Entity entity) { + if (entity == null) return; + previewEntities.remove(entity); + if (parentGui != null) { + parentGui.removePreviewEntity(entity); + } + } + // ==================== GETTERS ==================== public boolean isPlaying() { return playing; } public boolean isPaused() { return paused; } public boolean isActive() { return playing || paused; } - public AbilityPhase getPhase() { return phase; } + public AbilityPhase getPhase() { + switch (executorPhase) { + case WINDUP: return AbilityPhase.WINDUP; + case ACTIVE: return AbilityPhase.ACTIVE; + default: return AbilityPhase.IDLE; + } + } public int getCurrentTick() { return currentTick; } public TelegraphInstance getTelegraph() { return previewTelegraph; } public List getPreviewEntities() { return previewEntities; } @@ -364,11 +412,11 @@ public class AbilityPreviewExecutor { return "Stopped"; } else if (paused) { return "Paused"; - } else if (phase == AbilityPhase.WINDUP) { + } else if (executorPhase == ExecutorPhase.WINDUP) { return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0); - } else if (phase == AbilityPhase.ACTIVE) { - return "Active: " + currentTick + "/" + activeDuration; - } else if (phase == AbilityPhase.IDLE && playing) { + } else if (executorPhase == ExecutorPhase.ACTIVE) { + return "Active: " + currentTick + "/" + maxPreviewDuration; + } else if (executorPhase == ExecutorPhase.EXTENDED) { return "Extended: " + currentTick + "/" + EXTENDED_DURATION; } return ""; From af02b0ab1d6dbd82daff76b7b43a10aea547064d Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 16:28:38 -0500 Subject: [PATCH 09/76] Various Fixes --- src/api | 2 +- .../client/renderer/RenderAbilityDisc.java | 11 +- .../controllers/data/ability/Ability.java | 154 +++++++++++++---- .../data/ability/RotationMode.java | 53 ++++++ .../data/ability/gui/AbilityFieldDefs.java | 1 + .../data/ability/type/AbilityBeam.java | 9 + .../data/ability/type/AbilityBeamDual.java | 12 ++ .../data/ability/type/AbilityDisc.java | 17 +- .../data/ability/type/AbilityDiscDual.java | 27 ++- .../data/ability/type/AbilityLaserShot.java | 15 +- .../data/ability/type/AbilityOrb.java | 6 + .../data/ability/type/AbilityOrbBarrage.java | 6 + .../data/ability/type/AbilityOrbDual.java | 12 ++ .../npcs/entity/EntityAbilityDisc.java | 31 +++- .../npcs/entity/EntityAbilityLaser.java | 153 ++++++++++++----- .../kamkeel/npcs/util/AnchorPointHelper.java | 38 ++++- src/main/java/noppes/npcs/DataAbilities.java | 155 +++++++++++------- .../gui/util/AbilityPreviewExecutor.java | 35 +++- .../npcs/entity/EntityNPCInterface.java | 4 +- .../assets/customnpcs/lang/en_US.lang | 21 ++- 20 files changed, 599 insertions(+), 163 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java diff --git a/src/api b/src/api index f383fc303..fe1cec898 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit f383fc3037221791e2f22a272580df9be013810f +Subproject commit fe1cec89814290a745ac708b309703125b5a3c15 diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java index 20486d70e..8cb8cdaad 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java @@ -43,7 +43,16 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { GL11.glPushMatrix(); GL11.glScalef(scale, scale, scale); - // Apply ONLY Y-axis rotation for flat spin + if (disc.isVertical()) { + // Vertical mode: thin edge faces direction of travel (like a saw blade) + // 1. Spin in local space (Y-axis) + // 2. Tilt 90° to stand up (X-axis) + // 3. Orient to face travel direction (Y-axis world yaw) + GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + } + + // Apply Y-axis rotation for spin GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f); // Inner scale defines the core size 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 e6404a0cb..65d941327 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -67,7 +67,8 @@ public abstract class Ability implements IAbility { // Feedback protected LockMovementType lockMovement = LockMovementType.WINDUP; - protected LockType lockType = LockType.BOTH; + protected RotationMode rotationMode = RotationMode.FREE; + protected LockMovementType rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; protected int windUpColor = 0x80FF4400; // Telegraph color during wind up protected int activeColor = 0xC0FF0000; // Telegraph warning/active color @@ -418,26 +419,33 @@ public abstract class Ability implements IAbility { defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks) .tab("General").range(0, 10000)); defs.add(FieldDef.section("ability.section.movement").tab("General")); - defs.add(FieldDef.row( - FieldDef.stringEnumField("ability.lockPosition", LockMovementType.getDisplayKeys(), + defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), () -> this.getLockMovement().getDisplayKey(), v -> { - String[] keys = LockMovementType.getDisplayKeys(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].equals(v)) { this.setLockMovement(LockMovementType.fromOrdinal(i)); break; } + for (LockMovementType t : LockMovementType.values()) { + if (t.getDisplayKey().equals(v)) { this.setLockMovement(t); break; } } }) - .hover("ability.hover.lockPosition"), - FieldDef.stringEnumField("ability.lockType", LockType.getDisplayKeys(), - () -> this.getLockType().getDisplayKey(), + .hover("ability.hover.lockMovement") + .tab("General")); + defs.add(FieldDef.row( + FieldDef.stringEnumField("ability.rotationMode", RotationMode.getDisplayKeys(), + () -> this.getRotationMode().getDisplayKey(), v -> { - String[] keys = LockType.getDisplayKeys(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].equals(v)) { this.setLockType(LockType.fromOrdinal(i)); break; } + for (RotationMode m : RotationMode.values()) { + if (m.getDisplayKey().equals(v)) { this.setRotationMode(m); break; } } }) - .hover("ability.hover.lockType") - .visibleWhen(() -> this.lockMovement != LockMovementType.NO) + .hover("ability.hover.rotationMode"), + FieldDef.stringEnumField("ability.rotationPhase", getRotationPhaseKeys(), + () -> this.getRotationPhase().getDisplayKey(), + v -> { + for (LockMovementType t : LockMovementType.values()) { + if (t.getDisplayKey().equals(v)) { this.setRotationPhase(t); break; } + } + }) + .hover("ability.hover.rotationPhase") + .visibleWhen(() -> this.rotationMode != RotationMode.FREE) ).tab("General")); defs.add(FieldDef.row( FieldDef.boolField("ability.interruptible", this::isInterruptible, this::setInterruptible) @@ -606,12 +614,12 @@ public abstract class Ability implements IAbility { instance.setEntityIdToFollow(caster.getEntityId()); // For LINE/CONE telegraphs: track target direction during windup - // Only track if movement is NOT locked during windup (locked = NPC can't rotate) + // Only track if rotation is NOT locked during windup (NPC can still turn) if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { - if (!lockMovement.locksWindup()) { + if (!isRotationLockedDuringWindup()) { instance.setTargetEntityId(target.getEntityId()); } - // If windup is locked, yaw stays fixed at creation time + // If rotation is locked, yaw stays fixed at creation time } } else if (target != null) { // AOE_TARGET abilities: telegraph follows target during windup @@ -954,7 +962,8 @@ public abstract class Ability implements IAbility { nbt.setInteger("recovery", dazedTicks); nbt.setBoolean("interruptible", interruptible); nbt.setInteger("lockMovement", lockMovement.ordinal()); - nbt.setInteger("lockType", lockType.ordinal()); + nbt.setInteger("rotationMode", rotationMode.ordinal()); + nbt.setInteger("rotationPhase", rotationPhase.ordinal()); nbt.setInteger("windUpColor", windUpColor); nbt.setInteger("activeColor", activeColor); nbt.setString("windUpSound", windUpSound); @@ -1005,7 +1014,30 @@ public abstract class Ability implements IAbility { dazedTicks = nbt.getInteger("recovery"); interruptible = nbt.getBoolean("interruptible"); lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement")); - lockType = nbt.hasKey("lockType") ? LockType.fromOrdinal(nbt.getInteger("lockType")) : LockType.BOTH; + if (nbt.hasKey("rotationMode")) { + // Current format + rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); + rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); + } else if (nbt.hasKey("lockType")) { + // Legacy format migration: lockType was LockType enum (0=MOVEMENT, 1=ROTATION, 2=BOTH) + int oldLockType = nbt.getInteger("lockType"); + if (oldLockType == 0) { + // MOVEMENT only: movement locked, rotation was free + rotationMode = RotationMode.FREE; + } else if (oldLockType == 1) { + // ROTATION only: rotation locked same timing as old lockMovement, movement was free + rotationMode = RotationMode.LOCKED; + rotationPhase = lockMovement; + lockMovement = LockMovementType.NO; + } else { + // BOTH: both locked same timing + rotationMode = RotationMode.LOCKED; + rotationPhase = lockMovement; + } + } else { + rotationMode = RotationMode.FREE; + rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; + } windUpColor = nbt.getInteger("windUpColor"); activeColor = nbt.getInteger("activeColor"); windUpSound = nbt.getString("windUpSound"); @@ -1170,12 +1202,20 @@ public abstract class Ability implements IAbility { this.lockMovement = lockMovement; } - public LockType getLockType() { - return lockType; + public RotationMode getRotationMode() { + return rotationMode; } - public void setLockType(LockType lockType) { - this.lockType = lockType; + public void setRotationMode(RotationMode rotationMode) { + this.rotationMode = rotationMode; + } + + public LockMovementType getRotationPhase() { + return rotationPhase; + } + + public void setRotationPhase(LockMovementType rotationPhase) { + this.rotationPhase = rotationPhase; } /** @@ -1197,21 +1237,39 @@ public abstract class Ability implements IAbility { } /** - * API method: Get lock type as integer. - * @return 0=MOVEMENT, 1=ROTATION, 2=BOTH + * API method: Get rotation mode as integer. + * @return 0=FREE, 1=LOCKED, 2=TRACK */ @Override - public int getLockTypeOrdinal() { - return lockType.ordinal(); + public int getRotationModeType() { + return rotationMode.ordinal(); } /** - * API method: Set lock type from integer. - * @param type 0=MOVEMENT, 1=ROTATION, 2=BOTH + * API method: Set rotation mode from integer. + * @param type 0=FREE, 1=LOCKED, 2=TRACK */ @Override - public void setLockTypeOrdinal(int type) { - this.lockType = LockType.fromOrdinal(type); + public void setRotationModeType(int type) { + this.rotationMode = RotationMode.fromOrdinal(type); + } + + /** + * API method: Get rotation phase as integer. + * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public int getRotationPhaseType() { + return rotationPhase.ordinal(); + } + + /** + * API method: Set rotation phase from integer. + * @param type 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public void setRotationPhaseType(int type) { + this.rotationPhase = LockMovementType.fromOrdinal(type); } /** @@ -1219,7 +1277,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isMovementLockedDuringWindup() { - return lockMovement.locksWindup() && lockType.locksMovement(); + return lockMovement.locksWindup(); } /** @@ -1227,7 +1285,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isMovementLockedDuringActive() { - return lockMovement.locksActive() && lockType.locksMovement(); + return lockMovement.locksActive(); } /** @@ -1235,7 +1293,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isRotationLockedDuringWindup() { - return lockMovement.locksWindup() && lockType.locksRotation(); + return rotationMode == RotationMode.LOCKED && rotationPhase.locksWindup(); } /** @@ -1243,7 +1301,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isRotationLockedDuringActive() { - return lockMovement.locksActive() && lockType.locksRotation(); + return rotationMode == RotationMode.LOCKED && rotationPhase.locksActive(); } /** @@ -1274,6 +1332,21 @@ public abstract class Ability implements IAbility { } } + /** + * Check if hit scan (force face target) is active during the current phase. + */ + public boolean isHitScanForCurrentPhase() { + if (rotationMode != RotationMode.TRACK) return false; + switch (phase) { + case WINDUP: + return rotationPhase.locksWindup(); + case ACTIVE: + return rotationPhase.locksActive(); + default: + return false; + } + } + public int getWindUpColor() { return windUpColor; } @@ -1457,6 +1530,17 @@ public abstract class Ability implements IAbility { effects.clear(); } + /** + * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). + */ + private static String[] getRotationPhaseKeys() { + return new String[]{ + "ability.lockMove.windup", + "ability.lockMove.active", + "ability.lockMove.both" + }; + } + // ═══════════════════════════════════════════════════════════════════ // SHIT FROM THE ASS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java new file mode 100644 index 000000000..e1142b571 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java @@ -0,0 +1,53 @@ +package kamkeel.npcs.controllers.data.ability; + +/** + * Defines what happens to NPC rotation during ability phases. + * Used with a LockMovementType to control WHEN it applies. + */ +public enum RotationMode { + /** + * NPC rotates normally via AI look helper. + */ + FREE, + + /** + * Freeze rotation at the moment the phase starts. + * NPC stays facing the direction it was looking when the phase began. + */ + LOCKED, + + /** + * Force NPC to continuously face its target (hit scan). + * Overrides AI look helper every tick for precise aiming. + */ + TRACK; + + public String getDisplayKey() { + switch (this) { + case FREE: + return "ability.rotation.free"; + case LOCKED: + return "ability.rotation.locked"; + case TRACK: + return "ability.rotation.track"; + default: + return "ability.rotation.free"; + } + } + + public static String[] getDisplayKeys() { + return new String[]{ + "ability.rotation.free", + "ability.rotation.locked", + "ability.rotation.track" + }; + } + + public static RotationMode fromOrdinal(int ordinal) { + RotationMode[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return FREE; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java index bc1dc9ab8..6e419b943 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java @@ -23,4 +23,5 @@ public class AbilityFieldDefs { () -> getter.get(), v -> setter.accept((List) v)); } + } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 8e3bfc575..356c1c4e9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -5,6 +5,7 @@ import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.controllers.data.telegraph.Telegraph; @@ -57,6 +58,8 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { this.cooldownTicks = 0; this.windUpTicks = 40; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; // Default built-in animations @@ -313,6 +316,12 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { // Visual tab FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) + .tab("ability.tab.visual"), FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) .tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java index 89c5b126f..daf04a446 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java @@ -439,6 +439,12 @@ public class AbilityBeamDual extends Ability { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(0), v -> setAnchorOffsetX(0, v)), + FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(0), v -> setAnchorOffsetY(0, v)) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(0), v -> setAnchorOffsetZ(0, v)) + .tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", () -> getInnerColor(0), v -> setInnerColor(0, v)) .tab("ability.tab.visual"), @@ -475,6 +481,12 @@ public class AbilityBeamDual extends Ability { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(1), v -> setAnchorOffsetX(1, v)), + FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(1), v -> setAnchorOffsetY(1, v)) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(1), v -> setAnchorOffsetZ(1, v)) + .tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", () -> getInnerColor(1), v -> setInnerColor(1, v)) .tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 77d137eb9..98fe9eaac 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -32,6 +32,7 @@ public class AbilityDisc extends Ability implements IAbilityDisc { // Disc geometry private float discRadius = 1.0f; private float discThickness = 0.2f; + private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) // Boomerang properties private boolean boomerang = false; @@ -107,9 +108,9 @@ public class AbilityDisc extends Ability implements IAbilityDisc { boomerang, boomerangDelay); if (isPreview()) { - discEntity.setupPreview(caster, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks); + discEntity.setupPreview(caster, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks, vertical); } else { - discEntity.setupCharging(anchorData, windUpTicks); + discEntity.setupCharging(anchorData, windUpTicks, vertical); } discEntity.setEffects(this.effects); @@ -176,6 +177,7 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("discRadius", discRadius); nbt.setFloat("discThickness", discThickness); + nbt.setBoolean("vertical", vertical); nbt.setBoolean("boomerang", boomerang); nbt.setInteger("boomerangDelay", boomerangDelay); anchorData.writeNBT(nbt); @@ -190,6 +192,7 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void readTypeNBT(NBTTagCompound nbt) { this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; + this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; anchorData.readNBT(nbt); @@ -207,6 +210,8 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } public float getDiscThickness() { return discThickness; } public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } + public boolean isVertical() { return vertical; } + public void setVertical(boolean vertical) { this.vertical = vertical; } public float getMaxDistance() { return lifespanData.maxDistance; } public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } public int getMaxLifetime() { return lifespanData.maxLifetime; } @@ -286,6 +291,8 @@ public class AbilityDisc extends Ability implements IAbilityDisc { FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) ), + FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) + .hover("ability.hover.vertical"), FieldDef.row( FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) @@ -309,6 +316,12 @@ public class AbilityDisc extends Ability implements IAbilityDisc { // Visual tab FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) + .tab("ability.tab.visual"), FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) .tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java index 2fbd6cbda..87d7fffd5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java @@ -28,6 +28,7 @@ public class AbilityDiscDual extends Ability { // Disc geometry private float discRadius = 1.0f; private float discThickness = 0.2f; + private boolean vertical = false; // Boomerang properties private boolean boomerang = false; @@ -144,11 +145,11 @@ public class AbilityDiscDual extends Ability { discEntity2.setSiblingEntityId(discEntity.getEntityId()); if (isPreview()) { - discEntity.setupPreview(caster, discRadius, discThickness, displayData[0], lightningData[0], anchorData[0], windUpTicks); - discEntity2.setupPreview(caster, discRadius, discThickness, displayData[1], lightningData[1], anchorData[1], windUpTicks); + discEntity.setupPreview(caster, discRadius, discThickness, displayData[0], lightningData[0], anchorData[0], windUpTicks, vertical); + discEntity2.setupPreview(caster, discRadius, discThickness, displayData[1], lightningData[1], anchorData[1], windUpTicks, vertical); } else { - discEntity.setupCharging(anchorData[0], windUpTicks); - discEntity2.setupCharging(anchorData[1], windUpTicks); + discEntity.setupCharging(anchorData[0], windUpTicks, vertical); + discEntity2.setupCharging(anchorData[1], windUpTicks, vertical); } discEntity.setEffects(this.effects); @@ -244,6 +245,7 @@ public class AbilityDiscDual extends Ability { public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("discRadius", discRadius); nbt.setFloat("discThickness", discThickness); + nbt.setBoolean("vertical", vertical); nbt.setBoolean("boomerang", boomerang); nbt.setInteger("boomerangDelay", boomerangDelay); nbt.setBoolean("dualFire", dualFire); @@ -274,6 +276,7 @@ public class AbilityDiscDual extends Ability { this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; + this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); @@ -315,6 +318,8 @@ public class AbilityDiscDual extends Ability { public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } public float getDiscThickness() { return discThickness; } public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } + public boolean isVertical() { return vertical; } + public void setVertical(boolean vertical) { this.vertical = vertical; } public float getMaxDistance() { return lifespanData.maxDistance; } public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } public int getMaxLifetime() { return lifespanData.maxLifetime; } @@ -426,6 +431,8 @@ public class AbilityDiscDual extends Ability { FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) ), + FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) + .hover("ability.hover.vertical"), FieldDef.row( FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) @@ -455,6 +462,12 @@ public class AbilityDiscDual extends Ability { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(0), v -> setAnchorOffsetX(0, v)), + FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(0), v -> setAnchorOffsetY(0, v)) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(0), v -> setAnchorOffsetZ(0, v)) + .tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", () -> getInnerColor(0), v -> setInnerColor(0, v)) .tab("ability.tab.visual"), @@ -491,6 +504,12 @@ public class AbilityDiscDual extends Ability { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(1), v -> setAnchorOffsetX(1, v)), + FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(1), v -> setAnchorOffsetY(1, v)) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(1), v -> setAnchorOffsetZ(1, v)) + .tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", () -> getInnerColor(1), v -> setInnerColor(1, v)) .tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index d211de6d2..d5b48f1fd 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -5,6 +5,7 @@ import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; import noppes.npcs.client.gui.builder.FieldDef; @@ -38,7 +39,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { private final EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f); private final EnergyLightningData lightningData = new EnergyLightningData(); private final EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); + private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); // Transient state for laser entity (used for movement locking) @@ -53,6 +54,8 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { this.cooldownTicks = 0; this.windUpTicks = 15; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMovementType.WINDUP; this.telegraphType = TelegraphType.LINE; this.showTelegraph = true; // Default built-in animations @@ -118,10 +121,8 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { return; } + laserEntity.setLockVerticalDirection(true); laserEntity.startMoving(target); - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class } @Override @@ -269,6 +270,12 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { // Visual tab FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) + .tab("ability.tab.visual"), FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 6a87b38b4..1f1cb5e7d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -446,6 +446,12 @@ public class AbilityOrb extends Ability implements IAbilityOrb { // Visual tab FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) + .tab("ability.tab.visual"), FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java index dda01f68a..f384c4b71 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java @@ -581,6 +581,12 @@ public class AbilityOrbBarrage extends Ability { // Visual tab FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) + .tab("ability.tab.visual"), FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java index 7b8362464..3cabf4892 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java @@ -511,6 +511,12 @@ public class AbilityOrbDual extends Ability { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(0), v -> setAnchorOffsetX(0, v)), + FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(0), v -> setAnchorOffsetY(0, v)) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(0), v -> setAnchorOffsetZ(0, v)) + .tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", () -> getInnerColor(0), v -> setInnerColor(0, v)) .tab("ability.tab.visual"), @@ -547,6 +553,12 @@ public class AbilityOrbDual extends Ability { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(1), v -> setAnchorOffsetX(1, v)), + FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(1), v -> setAnchorOffsetY(1, v)) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(1), v -> setAnchorOffsetZ(1, v)) + .tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", () -> getInnerColor(1), v -> setInnerColor(1, v)) .tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index 3578ac9bf..edd7b3dff 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -31,6 +31,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { // Disc shape properties private float discRadius = 1.0f; // Width of disc private float discThickness = 0.2f; // Height of disc + private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) // Charging state (during windup) private boolean charging = false; @@ -122,11 +123,12 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * The disc will grow from 0 to discRadius over chargeDuration ticks. * Position follows the owner based on anchor point. */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { + public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) { setCharging(true); this.chargeDuration = chargeDuration; this.chargeTick = 0; this.anchorData = anchor; + this.vertical = vertical; this.targetDiscRadius = this.discRadius; this.targetDiscThickness = this.discThickness; this.discRadius = 0.01f; @@ -144,7 +146,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Follows anchor point and animations like in the real game. * Can be fired when transitioning to active phase. */ - public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { + public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, boolean vertical) { this.setPreviewMode(true); this.setPreviewOwner(owner); @@ -157,6 +159,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.chargeDuration = chargeDuration; this.chargeTick = 0; this.anchorData = anchor; + this.vertical = vertical; // Store target size and start at 0 for grow effect this.targetDiscRadius = discRadius; @@ -541,6 +544,28 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { return returning; } + public boolean isVertical() { + return vertical; + } + + /** + * Get the yaw angle (degrees) from motion vector for vertical disc orientation. + * During charging, uses owner's facing direction. + */ + public float getTravelYaw() { + if (isCharging()) { + Entity owner = previewMode ? previewOwner : getOwnerEntity(); + if (owner != null) { + return owner.rotationYaw; + } + } + double speed = Math.sqrt(motionX * motionX + motionZ * motionZ); + if (speed > 0.001) { + return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI); + } + return 0.0f; + } + // ==================== NBT ==================== @Override @@ -549,6 +574,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.boomerangDelay = nbt.hasKey("BoomerangDelay") ? nbt.getInteger("BoomerangDelay") : 40; this.discRadius = nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f; this.discThickness = nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f; + this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false; this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning"); // Charging state boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); @@ -566,6 +592,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { nbt.setInteger("BoomerangDelay", boomerangDelay); nbt.setFloat("DiscRadius", discRadius); nbt.setFloat("DiscThickness", discThickness); + nbt.setBoolean("Vertical", vertical); nbt.setBoolean("Returning", returning); // Charging state nbt.setBoolean("Charging", isCharging()); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 9c09bd467..8a1325a27 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -35,6 +35,9 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { // Direction (normalized) private double dirX, dirY, dirZ; + // Lock vertical direction after firing (only update yaw, keep pitch fixed) + private boolean lockVerticalDirection = false; + // Track hit entities to avoid double-damage private Set hitEntities = new HashSet<>(); @@ -165,6 +168,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { return; } + // Track owner's anchor position and rotation each tick + // so the laser follows the NPC's facing direction + updateLaserOriginAndDirection(); + if (!fullyExtended) { // Expand the laser currentLength += expansionSpeed; @@ -187,27 +194,76 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } else { // Laser is fully extended, count down linger time ticksSinceFullExtension++; + + // Update end point during linger (origin/direction may still change) + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + if (ticksSinceFullExtension >= lingerTicks) { this.setDead(); } } } + /** + * Update laser origin and direction from the owner's current anchor position and rotation. + * Called each tick so the laser follows the NPC when tracking a target. + */ + private void updateLaserOriginAndDirection() { + Entity owner = getOwnerEntity(); + if (owner == null || owner.isDead) return; + if (!(owner instanceof EntityLivingBase)) return; + + EntityLivingBase livingOwner = (EntityLivingBase) owner; + + // Update origin from anchor point + if (anchorData != null) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData); + startX = pos.xCoord; + startY = pos.yCoord; + startZ = pos.zCoord; + } else { + startX = owner.posX; + startY = owner.posY + owner.height * 0.7; + startZ = owner.posZ; + } + + // Update direction from owner's current rotation + float yaw = (float) Math.toRadians(owner.rotationYaw); + if (lockVerticalDirection) { + // Only update horizontal direction (yaw), keep vertical (pitch) fixed + double horizontalLen = Math.sqrt(dirX * dirX + dirZ * dirZ); + if (horizontalLen < 0.001) horizontalLen = 1.0; + dirX = -Math.sin(yaw) * horizontalLen; + dirZ = Math.cos(yaw) * horizontalLen; + } else { + float pitch = (float) Math.toRadians(owner.rotationPitch); + dirX = -Math.sin(yaw) * Math.cos(pitch); + dirY = -Math.sin(pitch); + dirZ = Math.cos(yaw) * Math.cos(pitch); + } + + // Keep entity positioned at origin + prevPosX = startX; + prevPosY = startY; + prevPosZ = startZ; + setPosition(startX, startY, startZ); + } + public void startMoving(EntityLivingBase target) { if (!isCharging()) return; setCharging(false); - // Update start position to current position + // Initialize from current anchor position + // updateLaserOriginAndDirection() will keep these updated each tick startX = posX; startY = posY; startZ = posZ; - // Always derive direction from the owner's current yaw/pitch. - // This ensures the laser fires in the direction the NPC is visually facing, - // which matches the telegraph line direction regardless of Lock Movement mode. + // Set initial direction from owner's rotation Entity owner = getOwnerEntity(); - if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); @@ -215,7 +271,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.dirY = -Math.sin(pitch); this.dirZ = Math.cos(yaw) * Math.cos(pitch); } else if (target != null) { - // Fallback: aim at target if owner is somehow unavailable double dx = target.posX - startX; double dy = (target.posY + target.getEyeHeight() - 0.4) - startY; double dz = target.posZ - startZ; @@ -227,12 +282,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } } - setPosition(endX, endY, endZ); - - // Initialize end point - this.endX = posX; - this.endY = posY; - this.endZ = posZ; + // Initialize end point at start (will expand from here) + this.endX = startX; + this.endY = startY; + this.endZ = startZ; } private void checkBlockCollision() { @@ -308,14 +361,14 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } private void checkEntityCollisionAlongLine() { - // Check collision along the entire laser line - // Use a slightly expanded AABB for the full line - double minX = Math.min(startX, endX) - laserWidth; - double minY = Math.min(startY, endY) - laserWidth; - double minZ = Math.min(startZ, endZ) - laserWidth; - double maxX = Math.max(startX, endX) + laserWidth; - double maxY = Math.max(startY, endY) + laserWidth; - double maxZ = Math.max(startZ, endZ) + laserWidth; + // Expand search AABB by entity sizes to ensure we find all potential targets + double expand = Math.max(laserWidth, 1.0); + double minX = Math.min(startX, endX) - expand; + double minY = Math.min(startY, endY) - expand; + double minZ = Math.min(startZ, endZ) - expand; + double maxX = Math.max(startX, endX) + expand; + double maxY = Math.max(startY, endY) + expand; + double maxZ = Math.max(startZ, endZ) + expand; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); @@ -326,7 +379,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { if (shouldIgnoreEntity(entity)) continue; if (hitEntities.contains(entity.getEntityId())) continue; - // Check if entity is close to the laser line + // Check if entity's bounding box intersects with the laser line if (isEntityOnLine(entity)) { hitEntities.add(entity.getEntityId()); applyDamage(entity); @@ -337,42 +390,64 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } /** - * Check if an entity intersects with the laser line. + * Check if an entity's bounding box intersects with the laser line. + * Uses separate XZ (horizontal) and Y (vertical) checks against + * the entity's full bounding box rather than just its center point. */ private boolean isEntityOnLine(EntityLivingBase entity) { - // Get entity center double ex = entity.posX; - double ey = entity.posY + entity.height * 0.5; double ez = entity.posZ; - // Vector from start to entity + // Project entity XZ position onto the laser line direction double vx = ex - startX; - double vy = ey - startY; double vz = ez - startZ; - - // Project onto line direction - double dot = vx * dirX + vy * dirY + vz * dirZ; - - // Clamp to line segment + // Project using horizontal direction components only + double dirLenXZ = Math.sqrt(dirX * dirX + dirZ * dirZ); + double dot; + if (dirLenXZ > 0.001) { + dot = (vx * dirX + vz * dirZ) / (dirLenXZ * dirLenXZ) * dirLenXZ; + // Remap to full 3D parameter + dot = (vx * dirX + vz * dirZ + (entity.posY + entity.height * 0.5 - startY) * dirY); + } else { + // Laser fires nearly straight up/down - use full 3D projection + dot = vx * dirX + (entity.posY + entity.height * 0.5 - startY) * dirY + vz * dirZ; + } dot = Math.max(0, Math.min(dot, currentLength)); - // Closest point on line + // Closest point on laser line at this parameter double closestX = startX + dirX * dot; double closestY = startY + dirY * dot; double closestZ = startZ + dirZ * dot; - // Distance from entity to closest point - double distSq = (ex - closestX) * (ex - closestX) + - (ey - closestY) * (ey - closestY) + - (ez - closestZ) * (ez - closestZ); + // XZ distance check: entity center vs laser line point + // Use minimum collision width so visually thin lasers still hit reliably + double xzDistSq = (ex - closestX) * (ex - closestX) + (ez - closestZ) * (ez - closestZ); + double effectiveWidth = Math.max(laserWidth, 0.5); + double hitRadiusXZ = effectiveWidth * 0.5 + entity.width * 0.5; + if (xzDistSq > hitRadiusXZ * hitRadiusXZ) return false; - // Hit if within laser width + entity radius - double hitRadius = laserWidth * 0.5 + entity.width * 0.5; - return distSq <= hitRadius * hitRadius; + // Y overlap check: laser point vs entity's full height range + double entityMinY = entity.boundingBox.minY; + double entityMaxY = entity.boundingBox.maxY; + double laserHalfWidth = effectiveWidth * 0.5; + + // Check if laser Y is within entity's height range (expanded by laser half-width) + if (closestY < entityMinY - laserHalfWidth) return false; + if (closestY > entityMaxY + laserHalfWidth) return false; + + return true; } // ==================== GETTERS FOR RENDERER ==================== + public void setLockVerticalDirection(boolean lock) { + this.lockVerticalDirection = lock; + } + + public boolean isLockVerticalDirection() { + return lockVerticalDirection; + } + public float getLaserWidth() { return laserWidth; } diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index 3ec5560ba..5ee5936b1 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -100,9 +100,12 @@ public class AnchorPointHelper { break; } - x += anchorX * scale; - y += anchorY * scale; - z += anchorZ * scale; + // Rotate offsets relative to entity's body yaw + // +X = entity's right, +Y = up, +Z = entity's forward + Vec3 rotatedOffset = rotateOffsetByYaw(anchorX * scale, anchorY * scale, anchorZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; return Vec3.createVectorHelper(x, y, z); } @@ -246,9 +249,11 @@ public class AnchorPointHelper { double worldY = entity.posY + shoulderHeight - blockY; double worldZ = entity.posZ + worldOffsetZ; - worldX += anchor.anchorOffsetX * scale; - worldY += anchor.anchorOffsetY * scale; - worldZ += anchor.anchorOffsetZ * scale; + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + worldX += rotatedOffset.xCoord; + worldY += rotatedOffset.yCoord; + worldZ += rotatedOffset.zCoord; return Vec3.createVectorHelper(worldX, worldY, worldZ); } @@ -317,9 +322,11 @@ public class AnchorPointHelper { double y = entity.posY + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset; double z = entity.posZ + lateralZ + forwardZ; - x += anchor.anchorOffsetX * scale; - y += anchor.anchorOffsetY * scale; - z += anchor.anchorOffsetZ * scale; + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; return Vec3.createVectorHelper(x, y, z); } @@ -344,4 +351,17 @@ public class AnchorPointHelper { return FRONT_HEIGHT; } } + + /** + * Rotate an offset vector by the entity's body yaw so offsets are entity-relative. + * +X = entity's right, +Y = up, +Z = entity's forward. + * @param bodyYawRad body yaw in radians + */ + private static Vec3 rotateOffsetByYaw(double offsetX, double offsetY, double offsetZ, float bodyYawRad) { + double cos = Math.cos(bodyYawRad); + double sin = Math.sin(bodyYawRad); + double worldX = -offsetX * cos - offsetZ * sin; + double worldZ = -offsetX * sin + offsetZ * cos; + return Vec3.createVectorHelper(worldX, offsetY, worldZ); + } } diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 19dc59ecd..606df7742 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -100,6 +100,14 @@ public class DataAbilities { private transient double lockedPosY = 0; private transient double lockedPosZ = 0; + /** + * Hit scan state - forces NPC to face target. + * Set during tickCurrentAbility(), applied after super.onLivingUpdate() + * to override AI look helper rotation. + */ + private transient boolean hitScanActive = false; + private transient EntityLivingBase hitScanTarget = null; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -126,13 +134,13 @@ public class DataAbilities { if (currentAbility != null) { removeTelegraph(currentAbility); stopAbilityAnimation(); - releaseLockedRotation(); + releaseRotationControl(); releaseLockedPosition(); currentAbility = null; lastTarget = null; } else { // No ability but locks could be orphaned - if (rotationLocked) releaseLockedRotation(); + if (rotationLocked || hitScanActive) releaseRotationControl(); if (positionLocked) releaseLockedPosition(); } return; @@ -140,7 +148,7 @@ public class DataAbilities { // Safety: release orphaned locks if no ability is actively executing if (currentAbility == null || !currentAbility.isExecuting()) { - if (rotationLocked) releaseLockedRotation(); + if (rotationLocked || hitScanActive) releaseRotationControl(); if (positionLocked) releaseLockedPosition(); } @@ -181,13 +189,13 @@ public class DataAbilities { // Remove telegraph - it has served its purpose removeTelegraph(currentAbility); - // Handle rotation lock transition from WINDUP to ACTIVE + // Handle rotation control transition from WINDUP to ACTIVE if (currentAbility.isRotationLockedDuringActive()) { if (!rotationLocked) { captureLockedRotation(); } } else if (rotationLocked) { - releaseLockedRotation(); + releaseRotationControl(); } // Handle position lock transition from WINDUP to ACTIVE @@ -203,6 +211,11 @@ public class DataAbilities { playAbilitySound(currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); + // Snap NPC to face target before execute so startMoving() reads correct rotation + if (currentAbility.isHitScanForCurrentPhase() && target != null) { + faceTarget(target); + } + // Fire execute event (cancelable) AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent( npc.wrappedNPC, currentAbility, target); @@ -239,6 +252,15 @@ public class DataAbilities { break; } + // Update hit scan state - actual facing is deferred to applyRotationControl() + // which runs AFTER super.onLivingUpdate() to override AI look helper + if (currentAbility != null && currentAbility.isExecuting() + && currentAbility.isHitScanForCurrentPhase() && target != null) { + enableHitScan(target); + } else if (hitScanActive) { + releaseRotationControl(); + } + // Apply movement control if ability is still executing if (currentAbility != null && currentAbility.isExecuting()) { applyMovementControl(); @@ -284,7 +306,7 @@ public class DataAbilities { NpcAPI.EVENT_BUS.post(completeEvent); // Release locks before cleanup - releaseLockedRotation(); + releaseRotationControl(); releaseLockedPosition(); // Clean up and roll cooldown (this sets currentAbility to null) @@ -301,7 +323,7 @@ public class DataAbilities { stopAbilityAnimation(); // Release locks - releaseLockedRotation(); + releaseRotationControl(); releaseLockedPosition(); // Calculate cooldown: random(min, max) + ability offset @@ -679,7 +701,7 @@ public class DataAbilities { stopAbilityAnimation(); // Release locks - releaseLockedRotation(); + releaseRotationControl(); releaseLockedPosition(); // Fire interrupt event @@ -702,7 +724,7 @@ public class DataAbilities { if (currentAbility != null) { removeTelegraph(currentAbility); stopAbilityAnimation(); - releaseLockedRotation(); + releaseRotationControl(); releaseLockedPosition(); currentAbility.interrupt(); currentAbility = null; @@ -1000,15 +1022,15 @@ public class DataAbilities { } // ═══════════════════════════════════════════════════════════════════ - // ROTATION LOCKING + // ROTATION CONTROL // ═══════════════════════════════════════════════════════════════════ - /** Bit flag for rotation lock in the existing data watcher slot 15 bitfield */ - private static final int ROTATION_LOCKED_FLAG = 16; + /** Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15 */ + private static final int ROTATION_CONTROLLED_FLAG = 16; /** * Capture current rotation values to lock NPC's look direction. - * Called when entering a locked phase (WINDUP or ACTIVE depending on LockMovementType). + * Called when entering a LOCKED rotation phase. */ private void captureLockedRotation() { lockedYaw = npc.rotationYaw; @@ -1016,41 +1038,79 @@ public class DataAbilities { lockedRenderYawOffset = npc.renderYawOffset; lockedPitch = npc.rotationPitch; rotationLocked = true; - npc.setBoolFlag(true, ROTATION_LOCKED_FLAG); + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); } /** - * Release the rotation lock. - * Called when leaving the locked phase or ability completes. + * Release rotation control (both locked and hit scan). */ - private void releaseLockedRotation() { + private void releaseRotationControl() { rotationLocked = false; - npc.setBoolFlag(false, ROTATION_LOCKED_FLAG); + hitScanActive = false; + hitScanTarget = null; + npc.setBoolFlag(false, ROTATION_CONTROLLED_FLAG); } /** - * Apply locked rotation values to the NPC. - * Called AFTER super.onLivingUpdate() in EntityNPCInterface to override - * any rotation changes made by the look helper, AI tasks, or body smoothing. - * Runs on both client and server. + * Enable hit scan tracking for the given target. */ - public void applyLockedRotation() { + private void enableHitScan(EntityLivingBase target) { + if (!hitScanActive) { + hitScanActive = true; + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); + } + hitScanTarget = target; + } + + /** + * Snap the NPC to face the target instantly. + */ + private void faceTarget(EntityLivingBase target) { + double dx = target.posX - npc.posX; + double dz = target.posZ - npc.posZ; + double dy = (target.posY + target.getEyeHeight() * 0.5) - (npc.posY + npc.getEyeHeight()); + double distXZ = Math.sqrt(dx * dx + dz * dz); + + float yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI); + float pitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI); + + npc.rotationYaw = yaw; + npc.rotationYawHead = yaw; + npc.renderYawOffset = yaw; + npc.rotationPitch = pitch; + npc.prevRotationYaw = yaw; + npc.prevRotationYawHead = yaw; + npc.prevRenderYawOffset = yaw; + npc.prevRotationPitch = pitch; + } + + /** + * Apply rotation control after super.onLivingUpdate() and super.onUpdate(). + * Handles both LOCKED (freeze at captured values) and TRACK (face target) modes. + * + * Server: computes the correct rotation (locked values or target facing). + * Client: trusts the server-synced rotation values and prevents body smoothing override. + */ + public void applyRotationControl() { if (npc.worldObj.isRemote) { - // Client-side: check bit 16 in the existing flags data watcher (slot 15) - boolean flagActive = npc.getBoolFlag(ROTATION_LOCKED_FLAG); - if (!flagActive) { + // Client: check single flag for any rotation control + if (!npc.getBoolFlag(ROTATION_CONTROLLED_FLAG)) { rotationLocked = false; return; } - // First tick the flag is active: capture current rotation values - if (!rotationLocked) { - lockedYaw = npc.rotationYaw; - lockedYawHead = npc.rotationYawHead; - lockedRenderYawOffset = npc.renderYawOffset; - lockedPitch = npc.rotationPitch; - rotationLocked = true; - } - // Force all rotation values back to locked state + // Trust server rotation, prevent body smoothing from overriding + npc.prevRotationYaw = npc.rotationYaw; + npc.prevRotationYawHead = npc.rotationYawHead; + npc.renderYawOffset = npc.rotationYawHead; + npc.prevRenderYawOffset = npc.rotationYawHead; + npc.prevRotationPitch = npc.rotationPitch; + return; + } + + // Server: apply the appropriate rotation + if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) { + faceTarget(hitScanTarget); + } else if (rotationLocked) { npc.rotationYaw = lockedYaw; npc.rotationYawHead = lockedYawHead; npc.renderYawOffset = lockedRenderYawOffset; @@ -1059,39 +1119,22 @@ public class DataAbilities { npc.prevRotationYawHead = lockedYawHead; npc.prevRenderYawOffset = lockedRenderYawOffset; npc.prevRotationPitch = lockedPitch; - return; } - - // Server-side: use stored locked values - if (!rotationLocked) { - return; - } - - // Force rotation back to locked values - npc.rotationYaw = lockedYaw; - npc.rotationYawHead = lockedYawHead; - npc.renderYawOffset = lockedRenderYawOffset; - npc.rotationPitch = lockedPitch; - - // Also set prev values to prevent interpolation jitter - npc.prevRotationYaw = lockedYaw; - npc.prevRotationYawHead = lockedYawHead; - npc.prevRenderYawOffset = lockedRenderYawOffset; - npc.prevRotationPitch = lockedPitch; } /** - * Check if rotation is currently locked. + * Check if rotation is currently controlled (locked or tracking target). + * Used by AI tasks to determine if they should try to change NPC look direction. */ public boolean isRotationLocked() { - return rotationLocked; + return rotationLocked || hitScanActive; } // ═══════════════════════════════════════════════════════════════════ // POSITION LOCKING // ═══════════════════════════════════════════════════════════════════ - /** Bit flag for position lock in the existing data watcher slot 15 bitfield */ + /** Bit flag for position lock in data watcher slot 15 */ private static final int POSITION_LOCKED_FLAG = 32; /** diff --git a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java index 2da4a1a7b..7d856d916 100644 --- a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java +++ b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java @@ -169,6 +169,9 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { public void pause() { paused = true; + // Immediately sync prevPos to pos for NPC and all entities to prevent interpolation jitter + syncPrevPositions(); + if (previewNpc != null) { AnimationData data = previewNpc.display.animationData; if (data.animation != null) { @@ -177,6 +180,25 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { } } + /** + * Sync prevPos to pos for the NPC and all preview entities. + * Prevents rendering interpolation jitter when standing still or paused. + */ + private void syncPrevPositions() { + if (previewNpc != null) { + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + } + for (Entity entity : previewEntities) { + if (entity != null && !entity.isDead) { + entity.prevPosX = entity.posX; + entity.prevPosY = entity.posY; + entity.prevPosZ = entity.posZ; + } + } + } + public void stop() { // Clean up the ability if (previewAbility != null) { @@ -228,10 +250,21 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { * Tick the preview forward. Calls real ability methods. */ public void tick() { - if (!playing || paused || previewAbility == null || previewNpc == null) { + if (!playing || previewAbility == null || previewNpc == null) { return; } + if (paused) { + // Sync prevPos to pos for NPC and all entities to prevent interpolation jitter while paused + syncPrevPositions(); + return; + } + + // Sync NPC's prevPos to current pos BEFORE any updates to prevent jitter when standing still + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + currentTick++; if (previewTelegraph != null) { diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 00de6d405..faaa2c9f5 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -312,7 +312,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti // Re-apply locks after super.onUpdate() to override body rotation smoothing // in EntityLivingBase.onUpdate() (func_110146_f) which runs AFTER onLivingUpdate() // and overwrites renderYawOffset, causing a visible twitch each frame. - abilities.applyLockedRotation(); + abilities.applyRotationControl(); abilities.applyLockedPosition(); if (!isRemote()) { @@ -489,7 +489,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti super.onLivingUpdate(); // Apply locks after super.onLivingUpdate() to override AI/physics changes - abilities.applyLockedRotation(); + abilities.applyRotationControl(); abilities.applyLockedPosition(); handleMountRiderState(); diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 7317856c9..497134b16 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1632,11 +1632,12 @@ ability.cnpc.sweeper=Sweeper ability.weight=Weight ability.windUpTicks=Wind Up ability.cooldownTicks=Cooldown -ability.lockPosition=Lock Position -ability.lockType=Lock Type -ability.lockType.movement=Movement -ability.lockType.rotation=Rotation -ability.lockType.both=Both +ability.lockMovement=Lock Movement +ability.rotationMode=Rotation +ability.rotationPhase=Phase +ability.rotation.free=Free +ability.rotation.locked=Locked +ability.rotation.track=Track ability.interruptible=Interruptible ability.dazedTicks=Dazed Ticks ability.targetingMode=Targeting @@ -1724,6 +1725,10 @@ ability.effects=Effects ability.mode=Mode ability.duration=Duration ability.anchorPoint=Anchor Point +ability.anchor.offsetX=Offset X +ability.anchor.offsetY=Offset Y +ability.anchor.offsetZ=Offset Z +ability.vertical=Vertical ability.rotationSpeed=Rotation Speed # Slam @@ -1864,8 +1869,9 @@ ability.noTypeSettings=No type-specific settings # ═══════════════════════════════════════════════════════════════ ability.hover.weight=Higher weight = more likely to be chosen when multiple abilities available -ability.hover.lockPosition=Prevents NPC from moving or rotating while ability is charging or active -ability.hover.lockType=What to lock: Movement (pathfinding), Rotation (facing direction), or Both +ability.hover.lockMovement=Prevents NPC pathfinding during the selected phases (Windup, Active, or Both) +ability.hover.rotationMode=Free: normal AI rotation. Locked: freeze facing direction. Track: force face target for precise aiming. +ability.hover.rotationPhase=When the rotation mode applies (Windup, Active, or Both) ability.hover.interruptible=If enabled, ability can be interrupted by taking damage ability.hover.dazed=Stun duration in ticks if ability is interrupted (20 ticks = 1 second) ability.hover.windup=Charge-up time before ability activates (20 ticks = 1 second) @@ -1886,6 +1892,7 @@ ability.hover.piercing=Hits multiple targets instead of stopping on first hit ability.hover.lightning=Add electrical effect to visuals ability.hover.outerGlow=Enable outer glow layer around projectile ability.hover.anchorPoint=Where on the NPC the ability spawns from +ability.hover.vertical=Disc flies standing up with thin edge facing target (like a saw blade) ability.hover.dualCharge=Whether or not should create two anchor points ability.hover.damage=Base damage dealt to targets ability.hover.speed=Movement speed of projectile From 74cae17ebd57bfdd9c4f9b1033c168ee979f8def Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 20:25:52 -0500 Subject: [PATCH 10/76] Burst and Dual Mode + Variant Ability Support --- src/api | 2 +- .../controllers/data/ability/Ability.java | 194 ++++- .../data/ability/AbilityController.java | 46 +- .../data/ability/AbilityPhase.java | 3 +- .../data/ability/AbilityVariant.java | 39 + .../data/ability/data/ProjectileData.java | 60 ++ .../data/ability/type/AbilityBeam.java | 630 +++++++++++---- .../data/ability/type/AbilityBeamDual.java | 528 ------------ .../data/ability/type/AbilityDisc.java | 637 +++++++++++---- .../data/ability/type/AbilityDiscDual.java | 551 ------------- .../data/ability/type/AbilityGuard.java | 5 + .../data/ability/type/AbilityHazard.java | 5 + .../data/ability/type/AbilityHeal.java | 5 + .../data/ability/type/AbilityLaserShot.java | 49 +- .../data/ability/type/AbilityOrb.java | 765 +++++++++++------- .../data/ability/type/AbilityOrbBarrage.java | 612 -------------- .../data/ability/type/AbilityOrbDual.java | 600 -------------- .../data/ability/type/AbilityProjectile.java | 5 + .../data/ability/type/AbilitySweeper.java | 5 + .../data/ability/type/AbilityTrap.java | 5 + src/main/java/noppes/npcs/DataAbilities.java | 44 +- .../client/gui/advanced/GuiNPCAbilities.java | 32 +- .../gui/advanced/SubGuiAbilityConfig.java | 4 +- .../advanced/SubGuiAbilityVariantSelect.java | 92 +++ .../client/gui/builder/GuiFieldBuilder.java | 39 +- .../gui/global/GuiNpcManageAbilities.java | 37 +- .../assets/customnpcs/lang/en_US.lang | 43 +- 27 files changed, 2055 insertions(+), 2982 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java create mode 100644 src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java diff --git a/src/api b/src/api index fe1cec898..8917e37a6 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit fe1cec89814290a745ac708b309703125b5a3c15 +Subproject commit 8917e37a6d35230a5c7b75ac8f89428edf1aabd2 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 65d941327..49ffbf587 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -32,6 +32,7 @@ import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import noppes.npcs.client.gui.builder.FieldDef; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import net.minecraft.entity.Entity; @@ -101,6 +102,13 @@ public abstract class Ability implements IAbility { // Configurable potion effects protected List effects = new ArrayList<>(); + // Burst + protected boolean burstEnabled = false; + protected int burstAmount = 0; // number of EXTRA repetitions + protected int burstDelay = 0; // ticks between bursts + protected boolean burstReplayAnimations = true; + protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts + // ═══════════════════════════════════════════════════════════════════ // EXECUTION STATE (not saved, reset each combat) // ═══════════════════════════════════════════════════════════════════ @@ -111,6 +119,10 @@ public abstract class Ability implements IAbility { protected transient long executionStartTime; protected transient TelegraphInstance telegraphInstance; + // Burst execution state + protected transient int burstIndex = 0; + protected transient List burstEntities = new ArrayList<>(); + // ═══════════════════════════════════════════════════════════════════ // PREVIEW STATE (client-side only, not saved) // ═══════════════════════════════════════════════════════════════════ @@ -156,6 +168,50 @@ public abstract class Ability implements IAbility { return true; } + /** + * Override to provide variant templates for this ability type. + * When a user creates this ability type, they will be shown a selection dialog + * with the returned variants. If empty or single-entry, the dialog is skipped. + */ + public List getVariants() { + return Collections.emptyList(); + } + + /** + * Whether this ability type supports the burst system. + * Override to return false for abilities that shouldn't repeat (Guard, Heal, Sweeper, etc.). + */ + public boolean allowBurst() { + return true; + } + + /** + * Whether this ability supports overlap mode for burst (entities from previous bursts keep flying). + * Override to return true for entity-spawning projectile abilities (Orb, Beam, Disc, LaserShot). + */ + public boolean allowOverlap() { + return false; + } + + /** + * Whether this ability is ready for auto-completion during burst overlap mode. + * Override to delay auto-completion until all staggered projectiles have been fired. + * @param activeTick the current tick within the ACTIVE phase + */ + public boolean isReadyForBurstCompletion(int activeTick) { + return true; + } + + /** + * Called when burst re-fires without replay animations (burstReplayAnimations=false). + * Entity-spawning abilities should override to spawn and fire entities in one step, + * since onWindUpTick was not called (windup was skipped). + * Default: does nothing (ability goes directly to onExecute with existing state). + */ + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + // Override in entity-spawning abilities (Orb, Beam, Disc, LaserShot) + } + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { } @@ -454,6 +510,25 @@ public abstract class Ability implements IAbility { .range(0, 1000).visibleWhen(this::isInterruptible) ).tab("General")); + // ── Burst section ──────────────────────────────────────────── + if (allowBurst()) { + defs.add(FieldDef.section("ability.section.burst").tab("General")); + defs.add(FieldDef.boolField("ability.burstEnabled", this::isBurstEnabled, this::setBurstEnabled) + .tab("General")); + defs.add(FieldDef.row( + FieldDef.intField("ability.burstAmount", this::getBurstAmount, this::setBurstAmount).range(1, 100), + FieldDef.intField("ability.burstDelay", this::getBurstDelay, this::setBurstDelay).range(0, 1000) + ).tab("General").visibleWhen(this::isBurstEnabled)); + defs.add(FieldDef.boolField("ability.burstReplayAnimations", this::isBurstReplayAnimations, this::setBurstReplayAnimations) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstReplay")); + if (allowOverlap()) { + defs.add(FieldDef.boolField("ability.burstOverlap", this::isBurstOverlap, this::setBurstOverlap) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstOverlap")); + } + } + // ── Target tab ─────────────────────────────────────────────── defs.add(FieldDef.row( FieldDef.intField("ability.minRange", () -> (int) getMinRange(), v -> setMinRange(v)).range(0, 100), @@ -722,6 +797,8 @@ public abstract class Ability implements IAbility { this.currentTick = 0; this.currentTarget = target; this.executionStartTime = System.currentTimeMillis(); + this.burstIndex = 0; + this.burstEntities.clear(); if (windUpTicks <= 0) { this.phase = AbilityPhase.ACTIVE; @@ -764,6 +841,19 @@ public abstract class Ability implements IAbility { return true; } break; + + case BURST_DELAY: + // Waiting between burst repetitions - free movement/rotation + if (currentTick >= burstDelay) { + if (burstReplayAnimations && getWindUpTicks() > 0) { + phase = AbilityPhase.WINDUP; + } else { + phase = AbilityPhase.ACTIVE; + } + currentTick = 0; + return true; + } + break; } return false; } @@ -777,6 +867,19 @@ public abstract class Ability implements IAbility { */ public boolean signalCompletion() { if (phase == AbilityPhase.ACTIVE) { + // Check if more burst iterations remain + if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) { + if (!burstOverlap) { + cleanup(); + } + burstIndex++; + phase = AbilityPhase.BURST_DELAY; + currentTick = 0; + return true; + } + + // Final completion - let burst entities die naturally (don't force-kill) + burstEntities.clear(); cleanup(); phase = AbilityPhase.IDLE; currentTick = 0; @@ -790,9 +893,10 @@ public abstract class Ability implements IAbility { * Called when NPC takes direct damage during WINDUP. */ public void interrupt() { + cleanupBurstEntities(); cleanup(); - if (interruptible && phase == AbilityPhase.WINDUP) { - // Interrupted during windup - go to dazed state + if (interruptible && (phase == AbilityPhase.WINDUP || phase == AbilityPhase.BURST_DELAY)) { + // Interrupted during windup or burst delay - go to dazed state phase = AbilityPhase.DAZED; currentTick = 0; } else { @@ -800,6 +904,7 @@ public abstract class Ability implements IAbility { phase = AbilityPhase.IDLE; currentTick = 0; } + burstIndex = 0; currentTarget = null; telegraphInstance = null; } @@ -820,7 +925,7 @@ public abstract class Ability implements IAbility { * @return true if the ability should be interrupted */ public boolean canInterrupt(DamageSource source) { - if (!interruptible || phase != AbilityPhase.WINDUP) { + if (!interruptible || (phase != AbilityPhase.WINDUP && phase != AbilityPhase.BURST_DELAY)) { return false; } @@ -847,9 +952,11 @@ public abstract class Ability implements IAbility { * Reset all execution state (called on combat end, NPC death, target lost, etc.) */ public void reset() { + cleanupBurstEntities(); cleanup(); phase = AbilityPhase.IDLE; currentTick = 0; + burstIndex = 0; currentTarget = null; telegraphInstance = null; previewMode = false; @@ -865,6 +972,18 @@ public abstract class Ability implements IAbility { // Override in subclasses to clean up spawned entities, etc. } + /** + * Kill all entities tracked during burst overlap and clear the list. + */ + protected void cleanupBurstEntities() { + for (Entity e : burstEntities) { + if (e != null && !e.isDead) { + killAbilityEntity(e); + } + } + burstEntities.clear(); + } + // ═══════════════════════════════════════════════════════════════════ // PREVIEW MODE SUPPORT // ═══════════════════════════════════════════════════════════════════ @@ -896,6 +1015,9 @@ public abstract class Ability implements IAbility { } else { world.spawnEntityInWorld(entity); } + if (burstEnabled && burstOverlap) { + burstEntities.add(entity); + } } /** @@ -979,6 +1101,13 @@ public abstract class Ability implements IAbility { nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); + // Burst + nbt.setBoolean("burstEnabled", burstEnabled); + nbt.setInteger("burstAmount", burstAmount); + nbt.setInteger("burstDelay", burstDelay); + nbt.setBoolean("burstReplayAnimations", burstReplayAnimations); + nbt.setBoolean("burstOverlap", burstOverlap); + // Conditions NBTTagList condList = new NBTTagList(); for (Condition c : conditions) condList.appendTag(c.writeNBT()); @@ -1059,6 +1188,13 @@ public abstract class Ability implements IAbility { allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH; ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown"); + // Burst + burstEnabled = nbt.hasKey("burstEnabled") && nbt.getBoolean("burstEnabled"); + burstAmount = nbt.hasKey("burstAmount") ? nbt.getInteger("burstAmount") : 0; + burstDelay = nbt.hasKey("burstDelay") ? nbt.getInteger("burstDelay") : 0; + burstReplayAnimations = !nbt.hasKey("burstReplayAnimations") || nbt.getBoolean("burstReplayAnimations"); + burstOverlap = nbt.hasKey("burstOverlap") && nbt.getBoolean("burstOverlap"); + // Conditions conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); @@ -1313,6 +1449,8 @@ public abstract class Ability implements IAbility { return isMovementLockedDuringWindup(); case ACTIVE: return isMovementLockedDuringActive(); + case BURST_DELAY: + return false; // Free movement during burst delay default: return false; } @@ -1327,6 +1465,8 @@ public abstract class Ability implements IAbility { return isRotationLockedDuringWindup(); case ACTIVE: return isRotationLockedDuringActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay default: return false; } @@ -1342,6 +1482,8 @@ public abstract class Ability implements IAbility { return rotationPhase.locksWindup(); case ACTIVE: return rotationPhase.locksActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay default: return false; } @@ -1530,6 +1672,52 @@ public abstract class Ability implements IAbility { effects.clear(); } + // Burst getters/setters + + public boolean isBurstEnabled() { + return burstEnabled; + } + + public void setBurstEnabled(boolean burstEnabled) { + this.burstEnabled = burstEnabled; + } + + public int getBurstAmount() { + return burstAmount; + } + + public void setBurstAmount(int burstAmount) { + this.burstAmount = Math.max(0, burstAmount); + } + + public int getBurstDelay() { + return burstDelay; + } + + public void setBurstDelay(int burstDelay) { + this.burstDelay = Math.max(0, burstDelay); + } + + public boolean isBurstReplayAnimations() { + return burstReplayAnimations; + } + + public void setBurstReplayAnimations(boolean burstReplayAnimations) { + this.burstReplayAnimations = burstReplayAnimations; + } + + public boolean isBurstOverlap() { + return burstOverlap; + } + + public void setBurstOverlap(boolean burstOverlap) { + this.burstOverlap = burstOverlap; + } + + public int getBurstIndex() { + return burstIndex; + } + /** * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). */ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 05110f553..294f9a765 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -45,6 +45,9 @@ public class AbilityController implements IAbilityHandler { /** External field providers for ability GUI (e.g., DBC Addon). Client-side only. */ private final List fieldProviders = new ArrayList<>(); + /** External variant definitions registered by addons, keyed by typeId. */ + private final Map> externalVariants = new LinkedHashMap<>(); + public AbilityController() { registerBuiltinTypes(); } @@ -432,13 +435,9 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:sweeper", AbilitySweeper::new); registerType("cnpc:projectile", AbilityProjectile::new); registerType("cnpc:orb", AbilityOrb::new); - registerType("cnpc:dual_orb", AbilityOrbDual::new); - registerType("cnpc:orb_barrage", AbilityOrbBarrage::new); - registerType("cnpc:dual_disc", AbilityDisc::new); - registerType("cnpc:dual_disc", AbilityDiscDual::new); + registerType("cnpc:disc", AbilityDisc::new); registerType("cnpc:laser_shot", AbilityLaserShot::new); registerType("cnpc:beam", AbilityBeam::new); - registerType("cnpc:dual_beam", AbilityBeamDual::new); // Movement abilities registerType("cnpc:charge", AbilityCharge::new); @@ -490,4 +489,41 @@ public class AbilityController implements IAbilityHandler { public List getFieldProviders() { return fieldProviders; } + + // ═══════════════════════════════════════════════════════════════════════════ + // EXTERNAL VARIANT REGISTRY + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Register an external variant for an ability type. + * External mods can call this to add variant presets that appear + * alongside built-in variants in the variant selection SubGui. + * + * @param typeId The ability typeId (e.g., "ability.cnpc.beam") + * @param variant The variant to register + */ + public void registerVariant(String typeId, AbilityVariant variant) { + externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant); + } + + /** + * Get all variants for a given ability type (built-in + external). + * Returns the combined list of variants from the ability's getVariants() + * and any externally registered variants. + * + * @param typeId The ability typeId + * @return Combined list of variants, empty if none + */ + public List getVariantsForType(String typeId) { + List result = new ArrayList<>(); + Ability temp = create(typeId); + if (temp != null) { + result.addAll(temp.getVariants()); + } + List ext = externalVariants.get(typeId); + if (ext != null) { + result.addAll(ext); + } + return result; + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java index 0611a0274..af1bd8d30 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java @@ -4,5 +4,6 @@ public enum AbilityPhase { IDLE, // Not executing WINDUP, // Charging up (telegraph visible) ACTIVE, // Executing (damage happens) - DAZED // Stunned after interrupt during WINDUP (cannot attack) + DAZED, // Stunned after interrupt during WINDUP (cannot attack) + BURST_DELAY // Waiting between burst repetitions (free movement/rotation) } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java new file mode 100644 index 000000000..91d151a85 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java @@ -0,0 +1,39 @@ +package kamkeel.npcs.controllers.data.ability; + +import java.util.function.Consumer; + +/** + * Represents a variant/template for an ability type. + * When a user creates an ability that has registered variants, + * they are presented with a selection dialog before the ability is created. + * + * Each variant has a display name (lang key) and a configurator that + * applies preset values to the newly created ability. + */ +public class AbilityVariant { + + private final String displayKey; + private final Consumer configurator; + + /** + * @param displayKey Lang key for the variant display name (e.g., "ability.variant.dual") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, Consumer configurator) { + this.displayKey = displayKey; + this.configurator = configurator; + } + + public String getDisplayKey() { + return displayKey; + } + + /** + * Apply this variant's preset configuration to the given ability. + */ + public void apply(Ability ability) { + if (configurator != null) { + configurator.accept(ability); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java new file mode 100644 index 000000000..49ee50f7e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -0,0 +1,60 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Per-projectile data: anchor point + optional color override. + * All projectiles share the primary EnergyDisplayData; this class + * allows individual projectiles to override just the inner/outer colors. + */ +public class ProjectileData { + public EnergyAnchorData anchor; + public boolean colorOverride = false; + public int innerColor = 0xFFFFFF; + public int outerColor = 0x8888FF; + + public ProjectileData(AnchorPoint defaultAnchor) { + this.anchor = new EnergyAnchorData(defaultAnchor); + } + + /** + * Returns the display data to use for this projectile. + * If colorOverride is false, returns the primary display data directly. + * If colorOverride is true, returns a copy with overridden inner/outer colors. + */ + public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) { + if (!colorOverride) return primary; + EnergyDisplayData resolved = primary.copy(); + resolved.innerColor = this.innerColor; + resolved.outerColor = this.outerColor; + return resolved; + } + + public void writeNBT(NBTTagCompound nbt) { + anchor.writeNBT(nbt); + nbt.setBoolean("colorOverride", colorOverride); + if (colorOverride) { + nbt.setInteger("overrideInnerColor", innerColor); + nbt.setInteger("overrideOuterColor", outerColor); + } + } + + public void readNBT(NBTTagCompound nbt) { + anchor.readNBT(nbt); + colorOverride = nbt.getBoolean("colorOverride"); + if (colorOverride) { + innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF; + outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF; + } + } + + public ProjectileData copy() { + ProjectileData copy = new ProjectileData(anchor.anchorPoint); + copy.anchor = anchor.copy(); + copy.colorOverride = colorOverride; + copy.innerColor = innerColor; + copy.outerColor = outerColor; + return copy; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 356c1c4e9..5f12cc183 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -13,7 +13,6 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; @@ -24,30 +23,39 @@ import noppes.npcs.api.ability.type.IAbilityEnergyBeam; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** * Energy Beam ability: A homing head with a trailing path. - * The beam stays attached to the origin and curves as it homes in on target. - * Cannot cross over itself (self-intersection prevention). + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { - // Shape properties (standalone) + private static final int MAX_PROJECTILES = 8; + + // Beam shape properties (shared) private float beamWidth = 0.4f; private float headSize = 0.6f; - // Data classes - private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); + // Projectile count and fire stagger + private int projectileCount = 1; + private int fireDelay = 0; + + // Shared visual data (all projectiles use these) + private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); + private EnergyLightningData lightningData = new EnergyLightningData(); + private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + + // Shared combat/movement data private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); - private final EnergyLightningData lightningData = new EnergyLightningData(); private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - // Transient state for beam entity (used during windup charging) - private transient EntityAbilityBeam beamEntity = null; + // Per-projectile data (anchor + optional color override) + private ProjectileData[] projectiles; + + // Transient entity state + private transient EntityAbilityBeam[] beamEntities; public AbilityBeam() { this.typeId = "ability.cnpc.beam"; @@ -62,9 +70,88 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Beam_Windup"; this.activeAnimationName = "Ability_Beam_Active"; + initProjectiles(1); + } + + private void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + private AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { + return projectileCount; + } + + public int getFireDelay() { + return fireDelay; + } + + public void setFireDelay(int delay) { + this.fireDelay = Math.max(0, delay); + } + + // Legacy compat + public int getDualFireDelay() { return fireDelay; } + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Beam"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityBeam beam = (AbilityBeam) a; + a.setName("Dual Beam"); + beam.setProjectileCount(2); + beam.setFireDelay(0); + // Set color override for second beam + beam.projectiles[1].colorOverride = true; + beam.projectiles[1].innerColor = 0xFFFFFF; + beam.projectiles[1].outerColor = 0xFF0000; + a.setWindUpTicks(80); + a.setWindUpAnimationName("Ability_BeamDual_Windup"); + a.setActiveAnimationName("Ability_BeamDual_Active"); + }) + ); + } + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); } @Override @@ -77,20 +164,34 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; + private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) { + EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount]; + float offsetDist = 1.0f; + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor, offsetDist); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + entities[i] = new EntityAbilityBeam( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + beamWidth, headSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + lockMovement.locksActive()); + entities[i].setEffects(this.effects); + entities[i].setSourceAbility(this); } + if (projectileCount == 2 && entities[0] != null && entities[1] != null) { + entities[0].setSiblingEntityId(entities[1].getEntityId()); + entities[1].setSiblingEntityId(entities[0].getEntityId()); + } + return entities; + } - // Start firing the beam that was spawned during windup - if (beamEntity != null && !beamEntity.isDead) { - if (isPreview()) { - beamEntity.startPreviewFiring(); - } else { - beamEntity.startFiring(target); - } + private void fireBeamEntity(EntityAbilityBeam beam, EntityLivingBase target) { + if (beam == null || beam.isDead) return; + if (isPreview()) { + beam.startPreviewFiring(); + } else { + beam.startFiring(target); } } @@ -98,35 +199,73 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { if (world.isRemote && !isPreview()) return; - // Spawn beam in charging mode on first tick of windup if (tick == 1) { + beamEntities = createBeamEntities(caster, target, world); float offsetDist = 1.0f; - - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData, offsetDist); - beamEntity = new EntityAbilityBeam( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - beamWidth, headSize, - colorData, combatData, homingData, lightningData, lifespanData, trajectoryData, - lockMovement.locksActive()); - - if (isPreview()) { - beamEntity.setupPreview(caster, beamWidth, headSize, colorData, lightningData, anchorData, windUpTicks, offsetDist); - } else { - beamEntity.setupCharging(anchorData, windUpTicks, offsetDist); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + beamEntities[i].setupPreview(caster, beamWidth, headSize, resolved, lightningData, projectiles[i].anchor, windUpTicks, offsetDist); + } else { + beamEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, offsetDist); + } + spawnAbilityEntity(world, beamEntities[i]); } + } + } - beamEntity.setEffects(this.effects); - beamEntity.setSourceAbility(this); - spawnAbilityEntity(world, beamEntity); + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + beamEntities = createBeamEntities(caster, target, world); + for (EntityAbilityBeam beam : beamEntities) { + spawnAbilityEntity(world, beam); + } + for (EntityAbilityBeam beam : beamEntities) { + fireBeamEntity(beam, target); + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + if (world.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (beamEntities == null) return; + + fireBeamEntity(beamEntities[0], target); + + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireBeamEntity(beamEntities[i], target); + } } } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (beamEntity == null || beamEntity.isDead) { - beamEntity = null; + if (beamEntities == null) { + signalCompletion(); + return; + } + + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireBeamEntity(beamEntities[i], target); + } + } + } + + boolean allDead = true; + for (EntityAbilityBeam beam : beamEntities) { + if (beam != null && !beam.isDead) { + allDead = false; + break; + } + } + if (allDead) { signalCompletion(); } } @@ -142,11 +281,15 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { @Override public void cleanup() { - // Despawn beam entity if still alive - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.setDead(); + if (beamEntities != null) { + for (int i = 0; i < beamEntities.length; i++) { + if (beamEntities[i] != null && !beamEntities[i].isDead) { + beamEntities[i].setDead(); + } + beamEntities[i] = null; + } } - beamEntity = null; + beamEntities = null; } @Override @@ -155,7 +298,6 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { return null; } - // Create circle telegraph at target position Telegraph telegraph = Telegraph.circle(headSize * 2.0f); telegraph.setDurationTicks(windUpTicks); telegraph.setColor(windUpColor); @@ -163,7 +305,6 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); telegraph.setHeightOffset(telegraphHeightOffset); - // Position at target and follow target during windup TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); instance.setEntityIdToFollow(target.getEntityId()); @@ -180,172 +321,307 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("beamWidth", beamWidth); nbt.setFloat("headSize", headSize); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared visual data + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + + // Shared combat/movement data combatData.writeNBT(nbt); homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); lifespanData.writeNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } } @Override public void readTypeNBT(NBTTagCompound nbt) { this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); + + int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + initProjectiles(count); + + if (nbt.hasKey("fireDelay")) { + this.fireDelay = nbt.getInteger("fireDelay"); + } else if (nbt.hasKey("dualFireDelay")) { + this.fireDelay = nbt.getInteger("dualFireDelay"); + } else { + this.fireDelay = 0; + } + combatData.readNBT(nbt); homingData.readNBT(nbt); - lightningData.readNBT(nbt); lifespanData.readNBT(nbt); + + if (nbt.hasKey("Projectile_0")) { + NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); + if (proj0.hasKey("colorOverride")) { + // NEW format + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } else { + // OLD per-projectile format + displayData.readNBT(proj0); + lightningData.readNBT(proj0); + projectiles[0].anchor.readNBT(proj0); + + for (int i = 1; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); + projectiles[i].anchor.readNBT(projNbt); + + EnergyDisplayData tempDisplay = new EnergyDisplayData(); + tempDisplay.readNBT(projNbt); + if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { + projectiles[i].colorOverride = true; + projectiles[i].innerColor = tempDisplay.innerColor; + projectiles[i].outerColor = tempDisplay.outerColor; + } + } + } + } + } else { + // LEGACY flat format + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + projectiles[0].anchor.readNBT(nbt); + } } - // Getters & Setters - Standalone fields + // ═══════════════════════════════════════════════════════════════════ + // API GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + public float getBeamWidth() { return beamWidth; } public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } + public float getHeadSize() { return headSize; } public void setHeadSize(float headSize) { this.headSize = headSize; } - // Getters & Setters - Color data - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { this.colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { this.colorData.outerColor = outerColor; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { this.colorData.outerColorEnabled = outerColorEnabled; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { this.colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { this.colorData.outerColorAlpha = outerColorAlpha; } - public float getRotationSpeed() { return colorData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { this.colorData.rotationSpeed = rotationSpeed; } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - - // Getters & Setters - Homing data public float getSpeed() { return homingData.speed; } public void setSpeed(float speed) { this.homingData.speed = speed; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { this.homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } - // Getters & Setters - Lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { this.lightningData.lightningEffect = lightningEffect; } - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { this.lightningData.lightningDensity = lightningDensity; } - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; } - - // Getters & Setters - Lifespan data public float getMaxDistance() { return lifespanData.maxDistance; } public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } + public int getMaxLifetime() { return lifespanData.maxLifetime; } public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - // Getters & Setters - Anchor point - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } + public float getDamage() { return combatData.damage; } + public void setDamage(float damage) { this.combatData.damage = damage; } + + public float getKnockback() { return combatData.knockback; } + public void setKnockback(float knockback) { this.combatData.knockback = knockback; } + + public float getKnockbackUp() { return combatData.knockbackUp; } + public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } + + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean homing) { this.homingData.homing = homing; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } + + public boolean isExplosive() { return combatData.explosive; } + public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } + + public float getExplosionRadius() { return combatData.explosionRadius; } + public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } + + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } + + // Shared display data (primary colors) + public int getInnerColor() { return displayData.innerColor; } + public void setInnerColor(int innerColor) { displayData.innerColor = innerColor; } + + public int getOuterColor() { return displayData.outerColor; } + public void setOuterColor(int outerColor) { displayData.outerColor = outerColor; } + + public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + public void setOuterColorEnabled(boolean outerColorEnabled) { displayData.outerColorEnabled = outerColorEnabled; } + + public float getOuterColorWidth() { return displayData.outerColorWidth; } + public void setOuterColorWidth(float outerColorWidth) { displayData.outerColorWidth = outerColorWidth; } + + public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + public void setOuterColorAlpha(float outerColorAlpha) { displayData.outerColorAlpha = outerColorAlpha; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float rotationSpeed) { displayData.rotationSpeed = rotationSpeed; } + + // Shared lightning data + public boolean hasLightningEffect() { return lightningData.lightningEffect; } + public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; } + + public float getLightningDensity() { return lightningData.lightningDensity; } + public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; } + + public float getLightningRadius() { return lightningData.lightningRadius; } + public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int lightningFadeTime) { lightningData.lightningFadeTime = lightningFadeTime; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint anchorPoint) { projectiles[0].anchor.anchorPoint = anchorPoint; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } @Override - public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); } + public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } @Override - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } + + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + private int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); + } @Override public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.beam"), - FieldDef.row( - FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), - FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.row( - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange) - .visibleWhen(this::isHoming) - ), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), - FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) )); + + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.beam")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), + FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), + FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange).visibleWhen(this::isHoming) + )); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); + + // Visual tab - shared primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Visual tab - shared effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java deleted file mode 100644 index daf04a446..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java +++ /dev/null @@ -1,528 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -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.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -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.EntityAbilityBeam; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.Arrays; -import java.util.List; - -public class AbilityBeamDual extends Ability { - private float beamWidth = 0.4f; - private float headSize = 0.6f; - private boolean dualFire= true; - private int dualFireDelay = 0; - - // Data classes - private final EnergyDisplayData[] displayData = new EnergyDisplayData[]{ - new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f), - new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 6.0f), - }; - private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); - private final EnergyLightningData[] lightningData = new EnergyLightningData[]{ - new EnergyLightningData(), new EnergyLightningData() - }; - private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.RIGHT_HAND), new EnergyAnchorData(AnchorPoint.LEFT_HAND) - }; - private final EnergyTrajectoryData[] trajectoryData = new EnergyTrajectoryData[]{ - new EnergyTrajectoryData(), new EnergyTrajectoryData() - }; - - // Transient state for beam entity (used during windup charging) - private transient EntityAbilityBeam beamEntity = null; - private transient EntityAbilityBeam beamEntity2 = null; - - public AbilityBeamDual() { - this.typeId = "ability.cnpc.beam_dual"; - this.name = "Beam Dual"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 20.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 80; - this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animations - this.windUpAnimationName = "Ability_BeamDual_Windup"; - this.activeAnimationName = "Ability_BeamDual_Active"; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - // Start firing the beam that was spawned during windup - if (beamEntity != null && !beamEntity.isDead) { - if (isPreview()) { - beamEntity.startPreviewFiring(); - } else { - beamEntity.startFiring(target); - } - } - - if (dualFire) { - if (beamEntity2 != null && !beamEntity2.isDead && dualFireDelay <= 0) { - if (isPreview()) { - beamEntity2.startPreviewFiring(); - } else { - beamEntity2.startFiring(target); - } - } - } else if (beamEntity2 != null) { - beamEntity2.setDead(); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - // Spawn beam in charging mode on first tick of windup - if (tick == 1) { - float offsetDist = 1.0f; - - Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0], offsetDist); - beamEntity = new EntityAbilityBeam( - world, caster, target, - spawnPos1.xCoord, spawnPos1.yCoord, spawnPos1.zCoord, - beamWidth, headSize, - displayData[0], combatData, homingData, lightningData[0], lifespanData, trajectoryData[0], - lockMovement.locksActive()); - - Vec3 spawnPos2 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[1], offsetDist); - beamEntity2 = new EntityAbilityBeam( - world, caster, target, - spawnPos2.xCoord, spawnPos2.yCoord, spawnPos2.zCoord, - beamWidth, headSize, - displayData[1], combatData, homingData, lightningData[1], lifespanData, trajectoryData[1], - lockMovement.locksActive()); - - beamEntity.setSiblingEntityId(beamEntity2.getEntityId()); - beamEntity2.setSiblingEntityId(beamEntity.getEntityId()); - - if (isPreview()) { - beamEntity.setupPreview(caster, beamWidth, headSize, displayData[0], lightningData[0], anchorData[0], windUpTicks, offsetDist); - beamEntity2.setupPreview(caster, beamWidth, headSize, displayData[1], lightningData[1], anchorData[1], windUpTicks, offsetDist); - } else { - beamEntity.setupCharging(anchorData[0], windUpTicks, offsetDist); - beamEntity2.setupCharging(anchorData[1], windUpTicks, offsetDist); - } - - beamEntity.setEffects(this.effects); - if (dualFire) beamEntity2.setEffects(this.effects); - - beamEntity.setSourceAbility(this); - beamEntity2.setSourceAbility(this); - spawnAbilityEntity(world, beamEntity); - spawnAbilityEntity(world, beamEntity2); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (dualFire) { - if ((beamEntity == null || beamEntity.isDead) && (beamEntity2 == null || beamEntity2.isDead)) { - beamEntity = null; - beamEntity2 = null; - signalCompletion(); - } - - if (tick == dualFireDelay && beamEntity2 != null && !beamEntity2.isDead) { - beamEntity2.startFiring(target); - } - } else { - if (beamEntity == null || beamEntity.isDead) { - beamEntity = null; - signalCompletion(); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn beam entity if still alive - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.setDead(); - } - - if (beamEntity2 != null && !beamEntity2.isDead) { - beamEntity2.setDead(); - } - - beamEntity = null; - beamEntity2 = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(headSize * 2.0f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return headSize * 2.0f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("beamWidth", beamWidth); - nbt.setFloat("headSize", headSize); - nbt.setBoolean("dualFire", dualFire); - nbt.setInteger("dualFireDelay", dualFireDelay); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - NBTTagCompound beam1 = new NBTTagCompound(); - NBTTagCompound beam2 = new NBTTagCompound(); - - for (int i = 0; i < 2; i++) { - NBTTagCompound beam = i == 0 ? beam1 : beam2; - anchorData[i].writeNBT(beam); - displayData[i].writeNBT(beam); - lightningData[i].writeNBT(beam); - trajectoryData[i].writeNBT(beam); - } - - nbt.setTag("Beam_1", beam1); - nbt.setTag("Beam_2", beam2); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - NBTTagCompound beam1 = nbt.hasKey("Beam_1") ? nbt.getCompoundTag("Beam_1") : new NBTTagCompound(); - NBTTagCompound beam2 = nbt.hasKey("Beam_2") ? nbt.getCompoundTag("Beam_2") : new NBTTagCompound(); - - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; - this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); - this.dualFireDelay = nbt.hasKey("dualFireDelay") ? nbt.getInteger("dualFireDelay") : 0; - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - for (int i = 0; i < 2; i++) { - NBTTagCompound beam = i == 0 ? beam1 : beam2; - anchorData[i].readNBT(beam); - displayData[i].readNBT(beam); - lightningData[i].readNBT(beam); - trajectoryData[i].readNBT(beam); - } - } - - // Getters & Setters - Standalone fields - public float getBeamWidth() { return beamWidth; } - public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } - public float getHeadSize() { return headSize; } - public void setHeadSize(float headSize) { this.headSize = headSize; } - public boolean isDualFire() { return dualFire; } - public void setDualFire(boolean dualFire) { this.dualFire = dualFire; } - public int getDualFireDelay() { return dualFireDelay; } - public void setDualFireDelay(int dualFireDelay) { this.dualFireDelay = dualFireDelay; } - - private EnergyDisplayData getColorData(int beam) { - beam = ValueUtil.clamp(beam, 0, 1); - return displayData[beam]; - } - private EnergyLightningData getLightningData(int beam) { - beam = ValueUtil.clamp(beam, 0, 1); - return lightningData[beam]; - } - private EnergyAnchorData getAnchorData(int beam) { - beam = ValueUtil.clamp(beam, 0, 1); - return anchorData[beam]; - } - - // Getters & Setters - Color data - public int getInnerColor(int beam) { return getColorData(beam).innerColor; } - public void setInnerColor(int beam, int innerColor) { getColorData(beam).innerColor = innerColor; } - public int getOuterColor(int beam) { return getColorData(beam).outerColor; } - public void setOuterColor(int beam, int outerColor) { getColorData(beam).outerColor = outerColor; } - public boolean isOuterColorEnabled(int beam) { return getColorData(beam).outerColorEnabled; } - public void setOuterColorEnabled(int beam, boolean enabled) { getColorData(beam).outerColorEnabled = enabled; } - public float getOuterColorWidth(int beam) { return getColorData(beam).outerColorWidth; } - public void setOuterColorWidth(int beam, float width) { getColorData(beam).outerColorWidth = width; } - public float getOuterColorAlpha(int beam) { return getColorData(beam).outerColorAlpha; } - public void setOuterColorAlpha(int beam, float alpha) { getColorData(beam).outerColorAlpha = alpha; } - public float getRotationSpeed(int beam) { return getColorData(beam).rotationSpeed; } - public void setRotationSpeed(int beam, float speed) { getColorData(beam).rotationSpeed = speed; } - - - public int getInnerColor() { return getInnerColor(0); } - public void setInnerColor(int innerColor) { setInnerColor(0, innerColor); } - public int getOuterColor() { return getOuterColor(0); } - public void setOuterColor(int outerColor) { setOuterColor(0, outerColor); } - public boolean isOuterColorEnabled() { return isOuterColorEnabled(0); } - public void setOuterColorEnabled(boolean enabled) { setOuterColorEnabled(0, enabled); } - public float getOuterColorWidth() { return getOuterColorWidth(0); } - public void setOuterColorWidth(float width) { setOuterColorWidth(0, width); } - public float getOuterColorAlpha() { return getOuterColorAlpha(0); } - public void setOuterColorAlpha(float alpha) { setOuterColorAlpha(0, alpha); } - public float getRotationSpeed() { return getRotationSpeed(0); } - public void setRotationSpeed(float speed) { setRotationSpeed(0, speed); } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - - // Getters & Setters - Homing data - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { this.homingData.speed = speed; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { this.homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } - - // Getters & Setters - Lightning data - public boolean hasLightningEffect(int beam) { return getLightningData(beam).lightningEffect; } - public void setLightningEffect(int beam, boolean lightningEffect) { getLightningData(beam).lightningEffect = lightningEffect; } - public float getLightningDensity(int beam) { return getLightningData(beam).lightningDensity; } - public void setLightningDensity(int beam, float lightningDensity) { getLightningData(beam).lightningDensity = lightningDensity; } - public float getLightningRadius(int beam) { return getLightningData(beam).lightningRadius; } - public void setLightningRadius(int beam, float lightningRadius) { getLightningData(beam).lightningRadius = lightningRadius; } - - public boolean hasLightningEffect() { return hasLightningEffect(0); } - public void setLightningEffect(boolean lightningEffect) { setLightningEffect(0, lightningEffect); } - public float getLightningDensity() { return getLightningDensity(0); } - public void setLightningDensity(float lightningDensity) { setLightningDensity(0, lightningDensity); } - public float getLightningRadius() { return getLightningRadius(0); } - public void setLightningRadius(float lightningRadius) { setLightningRadius(0, lightningRadius); } - - - // Getters & Setters - Lifespan data - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - // Getters & Setters - Anchor point - public AnchorPoint getAnchorPointEnum(int beam) { return getAnchorData(beam).anchorPoint; } - public void setAnchorPointEnum(int beam, AnchorPoint anchorPoint) { getAnchorData(beam).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int beam) { return getAnchorData(beam).anchorOffsetX; } - public void setAnchorOffsetX(int beam, float x) { getAnchorData(beam).anchorOffsetX = x; } - public float getAnchorOffsetY(int beam) { return getAnchorData(beam).anchorOffsetY; } - public void setAnchorOffsetY(int beam, float y) { getAnchorData(beam).anchorOffsetY = y; } - public float getAnchorOffsetZ(int beam) { return getAnchorData(beam).anchorOffsetZ; } - public void setAnchorOffsetZ(int beam, float z) { getAnchorData(beam).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int beam) { return getAnchorData(beam).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int beam, int point) { getAnchorData(beam).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.beam"), - FieldDef.row( - FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), - FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.dual"), - FieldDef.boolField("ability.dualFire", this::isDualFire, this::setDualFire), - FieldDef.intField("ability.dualFireDelay", this::getDualFireDelay, this::setDualFireDelay) - .visibleWhen(this::isDualFire), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.row( - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange) - .visibleWhen(this::isHoming) - ), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - Beam 1 - FieldDef.section("ability.section.beam1").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(0), v -> setAnchorOffsetX(0, v)), - FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(0), v -> setAnchorOffsetY(0, v)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(0), v -> setAnchorOffsetZ(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(0), v -> setInnerColor(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(0), v -> setOuterColorEnabled(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(0), v -> setOuterColor(0, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(0), v -> setOuterColorWidth(0, v)) - .visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(0), v -> setOuterColorAlpha(0, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(0)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(0), v -> setRotationSpeed(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(0), v -> setLightningEffect(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(0), v -> setLightningDensity(0, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(0)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(0), v -> setLightningRadius(0, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(0)) - ).tab("ability.tab.visual"), - // Visual tab - Beam 2 - FieldDef.section("ability.section.beam2").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(1), v -> setAnchorOffsetX(1, v)), - FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(1), v -> setAnchorOffsetY(1, v)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(1), v -> setAnchorOffsetZ(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(1), v -> setInnerColor(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(1), v -> setOuterColorEnabled(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(1), v -> setOuterColor(1, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(1), v -> setOuterColorWidth(1, v)) - .visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(1), v -> setOuterColorAlpha(1, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(1)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(1), v -> setRotationSpeed(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(1), v -> setLightningEffect(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(1), v -> setLightningDensity(1, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(1)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(1), v -> setLightningRadius(1, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(1)) - ).tab("ability.tab.visual") - )); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 98fe9eaac..d38d6a0b2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -22,33 +22,45 @@ import noppes.npcs.api.ability.type.IAbilityDisc; import java.util.Arrays; import java.util.List; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** * Disc ability: Spawns a flat spinning disc projectile. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. * Has optional boomerang behavior to return to owner. */ public class AbilityDisc extends Ability implements IAbilityDisc { - // Disc geometry + private static final int MAX_PROJECTILES = 8; + + // Disc geometry (shared) private float discRadius = 1.0f; private float discThickness = 0.2f; private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) - // Boomerang properties + // Boomerang properties (shared) private boolean boomerang = false; private int boomerangDelay = 40; - // Energy data classes - private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); + // Projectile count and fire stagger + private int projectileCount = 1; + private int fireDelay = 0; + + // Shared visual data (all projectiles use these) + private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); + private EnergyLightningData lightningData = new EnergyLightningData(); + private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + + // Shared combat/movement data private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); - private final EnergyLightningData lightningData = new EnergyLightningData(); private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - // Transient state for disc entity (used during windup charging) - private transient EntityAbilityDisc discEntity = null; + // Per-projectile data (anchor + optional color override) + private ProjectileData[] projectiles; + + // Transient entity state + private transient EntityAbilityDisc[] discEntities; public AbilityDisc() { this.typeId = "ability.cnpc.disc"; @@ -61,9 +73,90 @@ public class AbilityDisc extends Ability implements IAbilityDisc { this.lockMovement = LockMovementType.WINDUP; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Disc_Windup"; this.activeAnimationName = "Ability_Disc_Active"; + initProjectiles(1); + } + + private void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + /** + * Disc anchor order is REVERSED from Orb/Beam: [0]=LEFT_HAND, [1]=RIGHT_HAND + */ + private AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.LEFT_HAND; + case 1: return AnchorPoint.RIGHT_HAND; + default: return AnchorPoint.FRONT; + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { + return projectileCount; + } + + public int getFireDelay() { + return fireDelay; + } + + public void setFireDelay(int delay) { + this.fireDelay = Math.max(0, delay); + } + + // Legacy compat + public int getDualFireDelay() { return fireDelay; } + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Disc"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityDisc disc = (AbilityDisc) a; + a.setName("Dual Disc"); + disc.setProjectileCount(2); + disc.setFireDelay(10); + // Set color override for second disc + disc.projectiles[1].colorOverride = true; + disc.projectiles[1].innerColor = 0xFFFFFF; + disc.projectiles[1].outerColor = 0x8800FF; + a.setWindUpAnimationName("Ability_DiscDual_Windup"); + a.setActiveAnimationName("Ability_DiscDual_Active"); + }) + ); + } + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); } @Override @@ -76,20 +169,33 @@ public class AbilityDisc extends Ability implements IAbilityDisc { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; + private EntityAbilityDisc[] createDiscEntities(EntityLivingBase caster, EntityLivingBase target, World world) { + EntityAbilityDisc[] entities = new EntityAbilityDisc[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + entities[i] = new EntityAbilityDisc( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + discRadius, discThickness, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + boomerang, boomerangDelay); + entities[i].setEffects(this.effects); + entities[i].setSourceAbility(this); } + if (projectileCount == 2 && entities[0] != null && entities[1] != null) { + entities[0].setSiblingEntityId(entities[1].getEntityId()); + entities[1].setSiblingEntityId(entities[0].getEntityId()); + } + return entities; + } - // Start moving the disc that was spawned during windup - if (discEntity != null && !discEntity.isDead) { - if (isPreview()) { - discEntity.startPreviewFiring(); - } else { - discEntity.startMoving(target); - } + private void fireDiscEntity(EntityAbilityDisc disc, EntityLivingBase target) { + if (disc == null || disc.isDead) return; + if (isPreview()) { + disc.startPreviewFiring(); + } else { + disc.startMoving(target); } } @@ -97,33 +203,76 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { if (world.isRemote && !isPreview()) return; - // Spawn disc in charging mode on first tick of windup if (tick == 1) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - discEntity = new EntityAbilityDisc( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - discRadius, discThickness, - colorData, combatData, homingData, lightningData, lifespanData, trajectoryData, - boomerang, boomerangDelay); - - if (isPreview()) { - discEntity.setupPreview(caster, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks, vertical); - } else { - discEntity.setupCharging(anchorData, windUpTicks, vertical); + discEntities = createDiscEntities(caster, target, world); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + discEntities[i].setupPreview(caster, discRadius, discThickness, resolved, lightningData, projectiles[i].anchor, windUpTicks, vertical); + } else { + discEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, vertical); + } + spawnAbilityEntity(world, discEntities[i]); } + } + } - discEntity.setEffects(this.effects); - discEntity.setSourceAbility(this); - spawnAbilityEntity(world, discEntity); + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + discEntities = createDiscEntities(caster, target, world); + for (EntityAbilityDisc disc : discEntities) { + spawnAbilityEntity(world, disc); + } + for (EntityAbilityDisc disc : discEntities) { + fireDiscEntity(disc, target); + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + if (world.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (discEntities == null) return; + + // Fire first projectile immediately + fireDiscEntity(discEntities[0], target); + + // Fire remaining projectiles if no delay + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireDiscEntity(discEntities[i], target); + } } } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (discEntity == null || discEntity.isDead) { - discEntity = null; + if (discEntities == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireDiscEntity(discEntities[i], target); + } + } + } + + // Check if all entities are dead + boolean allDead = true; + for (EntityAbilityDisc disc : discEntities) { + if (disc != null && !disc.isDead) { + allDead = false; + break; + } + } + if (allDead) { signalCompletion(); } } @@ -139,11 +288,15 @@ public class AbilityDisc extends Ability implements IAbilityDisc { @Override public void cleanup() { - // Despawn disc entity if still alive - if (discEntity != null && !discEntity.isDead) { - discEntity.setDead(); + if (discEntities != null) { + for (int i = 0; i < discEntities.length; i++) { + if (discEntities[i] != null && !discEntities[i].isDead) { + discEntities[i].setDead(); + } + discEntities[i] = null; + } } - discEntity = null; + discEntities = null; } @Override @@ -180,12 +333,24 @@ public class AbilityDisc extends Ability implements IAbilityDisc { nbt.setBoolean("vertical", vertical); nbt.setBoolean("boomerang", boomerang); nbt.setInteger("boomerangDelay", boomerangDelay); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared visual data + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + + // Shared combat/movement data combatData.writeNBT(nbt); homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); lifespanData.writeNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } } @Override @@ -195,157 +360,303 @@ public class AbilityDisc extends Ability implements IAbilityDisc { this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); + + int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + initProjectiles(count); + + // Read fireDelay with fallback to old dualFireDelay key + if (nbt.hasKey("fireDelay")) { + this.fireDelay = nbt.getInteger("fireDelay"); + } else if (nbt.hasKey("dualFireDelay")) { + this.fireDelay = nbt.getInteger("dualFireDelay"); + } else { + this.fireDelay = 0; + } + + // Shared combat/movement data combatData.readNBT(nbt); homingData.readNBT(nbt); - lightningData.readNBT(nbt); lifespanData.readNBT(nbt); + + // Determine format and read accordingly + if (nbt.hasKey("Projectile_0")) { + NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); + if (proj0.hasKey("colorOverride")) { + // NEW format: shared visuals at root + ProjectileData per projectile + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } else { + // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) + // Read primary visuals from Projectile_0 + displayData.readNBT(proj0); + lightningData.readNBT(proj0); + projectiles[0].anchor.readNBT(proj0); + + // Read remaining projectiles, set color override if colors differ + for (int i = 1; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); + projectiles[i].anchor.readNBT(projNbt); + + // Check if this projectile had different colors + EnergyDisplayData tempDisplay = new EnergyDisplayData(); + tempDisplay.readNBT(projNbt); + if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { + projectiles[i].colorOverride = true; + projectiles[i].innerColor = tempDisplay.innerColor; + projectiles[i].outerColor = tempDisplay.outerColor; + } + } + } + } + } else { + // LEGACY flat format: all data at root level + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + projectiles[0].anchor.readNBT(nbt); + } } - // Getters & Setters + // ═══════════════════════════════════════════════════════════════════ + // API GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + public float getSpeed() { return homingData.speed; } public void setSpeed(float speed) { homingData.speed = speed; } + public float getDiscRadius() { return discRadius; } public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } + public float getDiscThickness() { return discThickness; } public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } + public boolean isVertical() { return vertical; } public void setVertical(boolean vertical) { this.vertical = vertical; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { homingData.homingRange = homingRange; } + public boolean isBoomerang() { return boomerang; } public void setBoomerang(boolean boomerang) { this.boomerang = boomerang; } + public int getBoomerangDelay() { return boomerangDelay; } public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; } + + public float getMaxDistance() { return lifespanData.maxDistance; } + public void setMaxDistance(float d) { lifespanData.maxDistance = d; } + + public int getMaxLifetime() { return lifespanData.maxLifetime; } + public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } + + public float getDamage() { return combatData.damage; } + public void setDamage(float d) { combatData.damage = d; } + + public float getKnockback() { return combatData.knockback; } + public void setKnockback(float k) { combatData.knockback = k; } + + public float getKnockbackUp() { return combatData.knockbackUp; } + public void setKnockbackUp(float k) { combatData.knockbackUp = k; } + + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean h) { homingData.homing = h; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float s) { homingData.homingStrength = s; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float r) { homingData.homingRange = r; } + public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { combatData.explosive = explosive; } + public void setExplosive(boolean e) { combatData.explosive = e; } + public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } + public void setExplosionRadius(float r) { combatData.explosionRadius = r; } + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { combatData.explosionDamageFalloff = explosionDamageFalloff; } - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { colorData.outerColor = outerColor; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { colorData.outerColorAlpha = outerColorAlpha; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } - public float getRotationSpeed() { return colorData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { colorData.rotationSpeed = rotationSpeed; } + public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } + + // Shared display data (primary colors) + public int getInnerColor() { return displayData.innerColor; } + public void setInnerColor(int c) { displayData.innerColor = c; } + + public int getOuterColor() { return displayData.outerColor; } + public void setOuterColor(int c) { displayData.outerColor = c; } + + public float getOuterColorWidth() { return displayData.outerColorWidth; } + public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } + + public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } + + public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } + + // Shared lightning data public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; } + public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } + public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; } + public void setLightningDensity(float d) { lightningData.lightningDensity = d; } + public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; } - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } + public void setLightningRadius(float r) { lightningData.lightningRadius = r; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } @Override - public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); } + public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } @Override - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } + + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + private int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); + } @Override public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.disc"), - FieldDef.row( - FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), - FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) - ), - FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) - .hover("ability.hover.vertical"), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.section("ability.section.boomerang"), - FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang) - .hover("ability.hover.boomerang"), - FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay) - .visibleWhen(this::isBoomerang), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), - FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + // Type tab - projectile count and fire delay + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) )); + + // Type tab - disc properties + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.disc")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), + FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) + )); + defs.add(FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) + .hover("ability.hover.vertical")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming)); + defs.add(FieldDef.section("ability.section.boomerang")); + defs.add(FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang).hover("ability.hover.boomerang")); + defs.add(FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay).visibleWhen(this::isBoomerang)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); + + // Visual tab - shared primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Visual tab - shared effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + // Anchor point + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java deleted file mode 100644 index 87d7fffd5..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java +++ /dev/null @@ -1,551 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -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.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -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.EntityAbilityDisc; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.util.ValueUtil; - -import java.util.Arrays; -import java.util.List; - -public class AbilityDiscDual extends Ability { - - // Disc geometry - private float discRadius = 1.0f; - private float discThickness = 0.2f; - private boolean vertical = false; - - // Boomerang properties - private boolean boomerang = false; - private int boomerangDelay = 40; - - // Dual properties - private boolean dualFire = true; - private int dualFireDelay = 10; - - // Energy data classes - private final EnergyDisplayData[] displayData = new EnergyDisplayData[]{ - new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f), - new EnergyDisplayData(0xFFFFFF, 0x8800FF, true, 0.4f, 0.5f, 5.0f) - }; - private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); - private final EnergyLightningData[] lightningData = new EnergyLightningData[]{ - new EnergyLightningData(), new EnergyLightningData() - }; - private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.LEFT_HAND), new EnergyAnchorData(AnchorPoint.RIGHT_HAND) - }; - private final EnergyTrajectoryData[] trajectoryData = new EnergyTrajectoryData[]{ - new EnergyTrajectoryData(), new EnergyTrajectoryData() - }; - - // Transient state for disc entity (used during windup charging) - private transient EntityAbilityDisc discEntity = null; - private transient EntityAbilityDisc discEntity2 = null; - - public AbilityDiscDual() { - this.typeId = "ability.cnpc.disc_dual"; - this.name = "Disc Dual"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 30.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 60; - this.lockMovement = LockMovementType.WINDUP; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animations - this.windUpAnimationName = "Ability_DiscDual_Windup"; - this.activeAnimationName = "Ability_DiscDual_Active"; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - // Start moving the disc that was spawned during windup - if (discEntity != null && !discEntity.isDead) { - if (isPreview()) { - discEntity.startPreviewFiring(); - } else { - discEntity.startMoving(target); - } - } - - if (dualFire) { - if (discEntity2 != null && !discEntity2.isDead && dualFireDelay <= 0) { - if (isPreview()) { - discEntity2.startPreviewFiring(); - } else { - discEntity2.startMoving(target); - } - } - } else if (discEntity2 != null) { - discEntity2.setDead(); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - // Spawn disc in charging mode on first tick of windup - if (tick == 1) { - // Create disc in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0]); - discEntity = new EntityAbilityDisc( - world, caster, target, - spawnPos1.xCoord, spawnPos1.yCoord, spawnPos1.zCoord, - discRadius, discThickness, - displayData[0], combatData, homingData, lightningData[0], lifespanData, trajectoryData[0], - boomerang, boomerangDelay); - - Vec3 spawnPos2 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[1]); - discEntity2 = new EntityAbilityDisc( - world, caster, target, - spawnPos2.xCoord, spawnPos2.yCoord, spawnPos2.zCoord, - discRadius, discThickness, - displayData[1], combatData, homingData, lightningData[1], lifespanData, trajectoryData[1], - boomerang, boomerangDelay); - - discEntity.setSiblingEntityId(discEntity2.getEntityId()); - discEntity2.setSiblingEntityId(discEntity.getEntityId()); - - if (isPreview()) { - discEntity.setupPreview(caster, discRadius, discThickness, displayData[0], lightningData[0], anchorData[0], windUpTicks, vertical); - discEntity2.setupPreview(caster, discRadius, discThickness, displayData[1], lightningData[1], anchorData[1], windUpTicks, vertical); - } else { - discEntity.setupCharging(anchorData[0], windUpTicks, vertical); - discEntity2.setupCharging(anchorData[1], windUpTicks, vertical); - } - - discEntity.setEffects(this.effects); - - if (dualFire) { - discEntity2.setEffects(this.effects); - } - - discEntity.setSourceAbility(this); - discEntity2.setSourceAbility(this); - spawnAbilityEntity(world, discEntity); - spawnAbilityEntity(world, discEntity2); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (dualFire) { - if ((discEntity == null || discEntity.isDead) && (discEntity2 == null || discEntity2.isDead)) { - discEntity = null; - discEntity2 = null; - signalCompletion(); - } - - if (tick == dualFireDelay && discEntity2 != null && !discEntity2.isDead) { - if (isPreview()) { - discEntity2.startPreviewFiring(); - } else { - discEntity2.startMoving(target); - } - } - } else { - if (discEntity == null || discEntity.isDead) { - discEntity = null; - signalCompletion(); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn disc entity if still alive - if (discEntity != null && !discEntity.isDead) { - discEntity.setDead(); - } - - if (discEntity2 != null && !discEntity2.isDead) { - discEntity2.setDead(); - } - - discEntity = null; - discEntity2 = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(discRadius * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return discRadius * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("discRadius", discRadius); - nbt.setFloat("discThickness", discThickness); - nbt.setBoolean("vertical", vertical); - nbt.setBoolean("boomerang", boomerang); - nbt.setInteger("boomerangDelay", boomerangDelay); - nbt.setBoolean("dualFire", dualFire); - nbt.setInteger("dualFireDelay", dualFireDelay); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - NBTTagCompound disc1 = new NBTTagCompound(); - NBTTagCompound disc2 = new NBTTagCompound(); - - for (int i = 0; i < 2; i++) { - NBTTagCompound disc = i == 0 ? disc1 : disc2; - anchorData[i].writeNBT(disc); - displayData[i].writeNBT(disc); - lightningData[i].writeNBT(disc); - trajectoryData[i].writeNBT(disc); - } - - nbt.setTag("Disc_1", disc1); - nbt.setTag("Disc_2", disc2); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - NBTTagCompound disc1 = nbt.hasKey("Disc_1") ? nbt.getCompoundTag("Disc_1") : new NBTTagCompound(); - NBTTagCompound disc2 = nbt.hasKey("Disc_2") ? nbt.getCompoundTag("Disc_2") : new NBTTagCompound(); - - this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; - this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; - this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); - this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); - this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; - this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); - this.dualFireDelay = nbt.hasKey("dualFireDelay") ? nbt.getInteger("dualFireDelay") : 0; - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - for (int i = 0; i < 2; i++) { - NBTTagCompound disc = i == 0 ? disc1 : disc2; - anchorData[i].readNBT(disc); - displayData[i].readNBT(disc); - lightningData[i].readNBT(disc); - trajectoryData[i].readNBT(disc); - } - } - - // Getters & Setters - private EnergyDisplayData getColorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return displayData[orb]; - } - private EnergyLightningData getLightningData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return lightningData[orb]; - } - private EnergyAnchorData getAnchorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return anchorData[orb]; - } - - public boolean isDualFire() { return dualFire; } - public void setDualFire(boolean dualFire) { this.dualFire = dualFire; } - public int getDualFireDelay() { return dualFireDelay; } - public void setDualFireDelay(int dualFireDelay) { this.dualFireDelay = dualFireDelay; } - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { homingData.speed = speed; } - public float getDiscRadius() { return discRadius; } - public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } - public float getDiscThickness() { return discThickness; } - public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } - public boolean isVertical() { return vertical; } - public void setVertical(boolean vertical) { this.vertical = vertical; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { homingData.homingRange = homingRange; } - public boolean isBoomerang() { return boomerang; } - public void setBoomerang(boolean boomerang) { this.boomerang = boomerang; } - public int getBoomerangDelay() { return boomerangDelay; } - public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { combatData.explosionDamageFalloff = explosionDamageFalloff; } - - - public int getInnerColor(int orb) { return getColorData(orb).innerColor; } - public void setInnerColor(int orb, int innerColor) { getColorData(orb).innerColor = innerColor; } - public int getOuterColor(int orb) { return getColorData(orb).outerColor; } - public void setOuterColor(int orb, int outerColor) { getColorData(orb).outerColor = outerColor; } - public boolean isOuterColorEnabled(int orb) { return getColorData(orb).outerColorEnabled; } - public void setOuterColorEnabled(int orb, boolean enabled) { getColorData(orb).outerColorEnabled = enabled; } - public float getOuterColorWidth(int orb) { return getColorData(orb).outerColorWidth; } - public void setOuterColorWidth(int orb, float width) { getColorData(orb).outerColorWidth = width; } - public float getOuterColorAlpha(int orb) { return getColorData(orb).outerColorAlpha; } - public void setOuterColorAlpha(int orb, float alpha) { getColorData(orb).outerColorAlpha = alpha; } - public float getRotationSpeed(int orb) { return getColorData(orb).rotationSpeed; } - public void setRotationSpeed(int orb, float speed) { getColorData(orb).rotationSpeed = speed; } - - public int getInnerColor() { return getInnerColor(0); } - public void setInnerColor(int innerColor) { setInnerColor(0, innerColor); } - public int getOuterColor() { return getOuterColor(0); } - public void setOuterColor(int outerColor) { setOuterColor(0, outerColor); } - public boolean isOuterColorEnabled() { return isOuterColorEnabled(0); } - public void setOuterColorEnabled(boolean enabled) { setOuterColorEnabled(0, enabled); } - public float getOuterColorWidth() { return getOuterColorWidth(0); } - public void setOuterColorWidth(float width) { setOuterColorWidth(0, width); } - public float getOuterColorAlpha() { return getOuterColorAlpha(0); } - public void setOuterColorAlpha(float alpha) { setOuterColorAlpha(0, alpha); } - public float getRotationSpeed() { return getRotationSpeed(0); } - public void setRotationSpeed(float speed) { setRotationSpeed(0, speed); } - - - public boolean hasLightningEffect(int orb) { return getLightningData(orb).lightningEffect; } - public void setLightningEffect(int orb, boolean lightningEffect) { getLightningData(orb).lightningEffect = lightningEffect; } - public float getLightningDensity(int orb) { return getLightningData(orb).lightningDensity; } - public void setLightningDensity(int orb, float lightningDensity) { getLightningData(orb).lightningDensity = lightningDensity; } - public float getLightningRadius(int orb) { return getLightningData(orb).lightningRadius; } - public void setLightningRadius(int orb, float lightningRadius) { getLightningData(orb).lightningRadius = lightningRadius; } - - public boolean hasLightningEffect() { return hasLightningEffect(0); } - public void setLightningEffect(boolean lightningEffect) { setLightningEffect(0, lightningEffect); } - public float getLightningDensity() { return getLightningDensity(0); } - public void setLightningDensity(float lightningDensity) { setLightningDensity(0, lightningDensity); } - public float getLightningRadius() { return getLightningRadius(0); } - public void setLightningRadius(float lightningRadius) { setLightningRadius(0, lightningRadius); } - - - public AnchorPoint getAnchorPointEnum(int orb) { return getAnchorData(orb).anchorPoint; } - public void setAnchorPointEnum(int orb, AnchorPoint anchorPoint) { getAnchorData(orb).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int orb) { return getAnchorData(orb).anchorOffsetX; } - public void setAnchorOffsetX(int orb, float x) { getAnchorData(orb).anchorOffsetX = x; } - public float getAnchorOffsetY(int orb) { return getAnchorData(orb).anchorOffsetY; } - public void setAnchorOffsetY(int orb, float y) { getAnchorData(orb).anchorOffsetY = y; } - public float getAnchorOffsetZ(int orb) { return getAnchorData(orb).anchorOffsetZ; } - public void setAnchorOffsetZ(int orb, float z) { getAnchorData(orb).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int orb) { return getAnchorData(orb).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int orb, int point) { getAnchorData(orb).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.disc"), - FieldDef.row( - FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), - FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) - ), - FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) - .hover("ability.hover.vertical"), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.dual"), - FieldDef.boolField("ability.dualFire", this::isDualFire, this::setDualFire), - FieldDef.intField("ability.dualFireDelay", this::getDualFireDelay, this::setDualFireDelay) - .visibleWhen(this::isDualFire), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.section("ability.section.boomerang"), - FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang) - .hover("ability.hover.boomerang"), - FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay) - .visibleWhen(this::isBoomerang), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - Disc 1 - FieldDef.section("ability.section.disc1").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(0), v -> setAnchorOffsetX(0, v)), - FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(0), v -> setAnchorOffsetY(0, v)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(0), v -> setAnchorOffsetZ(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(0), v -> setInnerColor(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(0), v -> setOuterColorEnabled(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(0), v -> setOuterColor(0, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(0), v -> setOuterColorWidth(0, v)) - .visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(0), v -> setOuterColorAlpha(0, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(0)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(0), v -> setRotationSpeed(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(0), v -> setLightningEffect(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(0), v -> setLightningDensity(0, v)) - .range(0.01f, 5.0f).visibleWhen(() -> hasLightningEffect(0)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(0), v -> setLightningRadius(0, v)) - .range(0.1f, 10.0f).visibleWhen(() -> hasLightningEffect(0)) - ).tab("ability.tab.visual"), - // Visual tab - Disc 2 - FieldDef.section("ability.section.disc2").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(1), v -> setAnchorOffsetX(1, v)), - FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(1), v -> setAnchorOffsetY(1, v)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(1), v -> setAnchorOffsetZ(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(1), v -> setInnerColor(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(1), v -> setOuterColorEnabled(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(1), v -> setOuterColor(1, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(1), v -> setOuterColorWidth(1, v)) - .visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(1), v -> setOuterColorAlpha(1, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(1)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(1), v -> setRotationSpeed(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(1), v -> setLightningEffect(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(1), v -> setLightningDensity(1, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(1)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(1), v -> setLightningRadius(1, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(1)) - ).tab("ability.tab.visual") - )); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} 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 ec9f157f9..477be2cc4 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 @@ -70,6 +70,11 @@ public class AbilityGuard extends Ability implements IAbilityGuard { return false; } + @Override + public boolean allowBurst() { + return false; + } + public enum CounterType { FLAT, PERCENT; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 112b2a637..70696eb8f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -113,6 +113,11 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.telegraphType = TelegraphType.CIRCLE; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index b60c46d9d..d913fe586 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -63,6 +63,11 @@ public class AbilityHeal extends Ability implements IAbilityHeal { return false; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index d5b48f1fd..7ddfcc0e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -63,6 +63,11 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { this.activeAnimationName = "Ability_Laser_Active"; } + @Override + public boolean allowOverlap() { + return true; + } + @Override public boolean isTargetingModeLocked() { return false; @@ -83,32 +88,47 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { return laserWidth * 2.0f; // Make telegraph slightly wider for visibility } + private EntityAbilityLaser spawnLaserEntity(EntityLivingBase caster, EntityLivingBase target, World world) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); + EntityAbilityLaser entity = new EntityAbilityLaser( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + laserWidth, + colorData, combatData, lightningData, lifespanData, trajectoryData, + expansionSpeed, lingerTicks + ); + entity.setEffects(this.effects); + entity.setSourceAbility(this); + spawnAbilityEntity(world, entity); + return entity; + } + + private void fireLaserEntity(EntityAbilityLaser laser, EntityLivingBase target) { + if (laser == null || laser.isDead) return; + laser.setLockVerticalDirection(true); + laser.startMoving(target); + } + @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { if (world.isRemote && !isPreview()) return; if (tick == 1) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - laserEntity = new EntityAbilityLaser( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - laserWidth, - colorData, combatData, lightningData, lifespanData, trajectoryData, - expansionSpeed, lingerTicks - ); - + laserEntity = spawnLaserEntity(caster, target, world); if (isPreview()) { laserEntity.setupPreview(caster, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); } else { laserEntity.setupCharging(anchorData, windUpTicks); } - - laserEntity.setEffects(this.effects); - laserEntity.setSourceAbility(this); - spawnAbilityEntity(world, laserEntity); } } + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + laserEntity = spawnLaserEntity(caster, target, world); + fireLaserEntity(laserEntity, target); + } + @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { if (world.isRemote && !isPreview()) { @@ -121,8 +141,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { return; } - laserEntity.setLockVerticalDirection(true); - laserEntity.startMoving(target); + fireLaserEntity(laserEntity, target); } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 1f1cb5e7d..024fe2912 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -12,7 +12,6 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityOrb; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; @@ -23,29 +22,38 @@ import noppes.npcs.api.ability.type.IAbilityOrb; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** - * Orb ability: Spawns a homing projectile sphere that tracks target. - * The EntityAbilityOrb handles all movement, collision, and damage logic. - * This ability just configures and spawns the orb entity. + * Orb ability: Spawns homing projectile sphere(s) that track target. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ public class AbilityOrb extends Ability implements IAbilityOrb { - // Ability-specific properties + private static final int MAX_PROJECTILES = 8; + + // Orb properties private float orbSize = 1.0f; - // Data classes for energy properties - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyCombatData combatData = new EnergyCombatData(); - private final EnergyDisplayData displayData = new EnergyDisplayData(); - private final EnergyHomingData homingData = new EnergyHomingData(); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + // Projectile count and fire stagger + private int projectileCount = 1; + private int fireDelay = 0; - // Transient state for orb entity (used during windup charging) - private transient EntityAbilityOrb orbEntity = null; + // Shared visual data (all projectiles use these) + private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); + private EnergyLightningData lightningData = new EnergyLightningData(); + private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + + // Shared combat/movement data + private final EnergyCombatData combatData = new EnergyCombatData(); + private final EnergyHomingData homingData = new EnergyHomingData(); + private final EnergyLifespanData lifespanData = new EnergyLifespanData(); + + // Per-projectile data (anchor + optional color override) + private ProjectileData[] projectiles; + + // Transient entity state + private transient EntityAbilityOrb[] orbEntities; public AbilityOrb() { this.typeId = "ability.cnpc.orb"; @@ -58,9 +66,100 @@ public class AbilityOrb extends Ability implements IAbilityOrb { this.lockMovement = LockMovementType.WINDUP; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animation this.windUpAnimationName = "Ability_Orb_Windup"; this.activeAnimationName = "Ability_Orb_Active"; + initProjectiles(1); + } + + private void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + private AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + // Preserve existing projectile data + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { + return projectileCount; + } + + public int getFireDelay() { + return fireDelay; + } + + public void setFireDelay(int delay) { + this.fireDelay = Math.max(0, delay); + } + + // Legacy compat + public int getDualFireDelay() { return fireDelay; } + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Orb"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityOrb orb = (AbilityOrb) a; + a.setName("Dual Orb"); + orb.setProjectileCount(2); + orb.setFireDelay(5); + a.setWindUpAnimationName("Ability_OrbDual_Windup"); + a.setActiveAnimationName("Ability_OrbDual_Active"); + }), + new AbilityVariant("ability.variant.barrage", a -> { + AbilityOrb orb = (AbilityOrb) a; + a.setName("Orb Barrage"); + orb.setOrbSize(0.5f); + orb.setDamage(4.0f); + orb.setKnockback(0.0f); + orb.setKnockbackUp(0.0f); + a.setMaxRange(75.0f); + a.setBurstEnabled(true); + a.setBurstAmount(15); + a.setBurstDelay(10); + a.setBurstReplayAnimations(false); + a.setBurstOverlap(true); + a.setWindUpAnimationName("Ability_BeamDual_Windup"); + a.setActiveAnimationName("Ability_BeamDual_Active"); + }) + ); + } + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); } @Override @@ -73,6 +172,63 @@ public class AbilityOrb extends Ability implements IAbilityOrb { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } + private EntityAbilityOrb[] createOrbEntities(EntityLivingBase caster, EntityLivingBase target, World world) { + EntityAbilityOrb[] entities = new EntityAbilityOrb[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + entities[i] = new EntityAbilityOrb( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData); + entities[i].setEffects(this.effects); + entities[i].setSourceAbility(this); + } + if (projectileCount == 2 && entities[0] != null && entities[1] != null) { + entities[0].setSiblingEntityId(entities[1].getEntityId()); + entities[1].setSiblingEntityId(entities[0].getEntityId()); + } + return entities; + } + + private void fireOrbEntity(EntityAbilityOrb orb, EntityLivingBase target) { + if (orb == null || orb.isDead) return; + if (isPreview()) { + orb.startPreviewFiring(); + } else { + orb.startMoving(target); + } + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + if (world.isRemote && !isPreview()) return; + + if (tick == 1) { + orbEntities = createOrbEntities(caster, target, world); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + orbEntities[i].setupPreview(caster, orbSize, resolved, lightningData, projectiles[i].anchor, windUpTicks); + } else { + orbEntities[i].setupCharging(projectiles[i].anchor, windUpTicks); + } + spawnAbilityEntity(world, orbEntities[i]); + } + } + } + + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + orbEntities = createOrbEntities(caster, target, world); + for (EntityAbilityOrb orb : orbEntities) { + spawnAbilityEntity(world, orb); + } + for (EntityAbilityOrb orb : orbEntities) { + fireOrbEntity(orb, target); + } + } + @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { if (world.isRemote && !isPreview()) { @@ -80,55 +236,50 @@ public class AbilityOrb extends Ability implements IAbilityOrb { return; } - // Start moving the orb that was spawned during windup - if (orbEntity != null && !orbEntity.isDead) { - if (isPreview()) { - orbEntity.startPreviewFiring(); - } else { - orbEntity.startMoving(target); + if (orbEntities == null) return; + + // Fire first projectile immediately + fireOrbEntity(orbEntities[0], target); + + // Fire remaining projectiles if no delay + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireOrbEntity(orbEntities[i], target); } } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - // Spawn orb in charging mode on first tick of windup - if (tick == 1) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - displayData, combatData, homingData, lightningData, lifespanData, trajectoryData); - - if (isPreview()) { - orbEntity.setupPreview(caster, orbSize, displayData, lightningData, anchorData, windUpTicks); - } else { - orbEntity.setupCharging(anchorData, windUpTicks); - } - - orbEntity.setEffects(this.effects); - orbEntity.setSourceAbility(this); - spawnAbilityEntity(world, orbEntity); - } } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (orbEntity == null || orbEntity.isDead) { - orbEntity = null; + if (orbEntities == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireOrbEntity(orbEntities[i], target); + } + } + } + + // Check if all entities are dead + boolean allDead = true; + for (EntityAbilityOrb orb : orbEntities) { + if (orb != null && !orb.isDead) { + allDead = false; + break; + } + } + if (allDead) { signalCompletion(); } } @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - // Nothing to clean up - entity manages itself } @Override @@ -138,11 +289,15 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void cleanup() { - // Despawn orb entity if still alive - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); + if (orbEntities != null) { + for (int i = 0; i < orbEntities.length; i++) { + if (orbEntities[i] != null && !orbEntities[i].isDead) { + orbEntities[i].setDead(); + } + orbEntities[i] = null; + } } - orbEntity = null; + orbEntities = null; } @Override @@ -151,7 +306,6 @@ public class AbilityOrb extends Ability implements IAbilityOrb { return null; } - // Create small circle telegraph at target position Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); telegraph.setDurationTicks(windUpTicks); telegraph.setColor(windUpColor); @@ -159,7 +313,6 @@ public class AbilityOrb extends Ability implements IAbilityOrb { telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); telegraph.setHeightOffset(telegraphHeightOffset); - // Position at target and follow target during windup TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); instance.setEntityIdToFollow(target.getEntityId()); @@ -175,241 +328,217 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("orbSize", orbSize); - anchorData.writeNBT(nbt); - combatData.writeNBT(nbt); + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared visual data displayData.writeNBT(nbt); - homingData.writeNBT(nbt); lightningData.writeNBT(nbt); + + // Shared combat/movement data + combatData.writeNBT(nbt); + homingData.writeNBT(nbt); lifespanData.writeNBT(nbt); - trajectoryData.writeNBT(nbt); - // Backward compat: old key was "orbSpeed" + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } + + // Backward compat write nbt.setFloat("orbSpeed", homingData.speed); } @Override public void readTypeNBT(NBTTagCompound nbt) { this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - anchorData.readNBT(nbt); + + int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + initProjectiles(count); + + // Read fireDelay with fallback to old dualFireDelay key + if (nbt.hasKey("fireDelay")) { + this.fireDelay = nbt.getInteger("fireDelay"); + } else if (nbt.hasKey("dualFireDelay")) { + this.fireDelay = nbt.getInteger("dualFireDelay"); + } else { + this.fireDelay = 0; + } + + // Shared combat/movement data combatData.readNBT(nbt); - displayData.readNBT(nbt); homingData.readNBT(nbt); - lightningData.readNBT(nbt); lifespanData.readNBT(nbt); - trajectoryData.readNBT(nbt); - // Backward compat: old key was "orbSpeed" + + // Determine format and read accordingly + if (nbt.hasKey("Projectile_0")) { + NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); + if (proj0.hasKey("colorOverride")) { + // NEW format: shared visuals at root + ProjectileData per projectile + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } else { + // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) + // Read primary visuals from Projectile_0 + displayData.readNBT(proj0); + lightningData.readNBT(proj0); + projectiles[0].anchor.readNBT(proj0); + + // Read remaining projectiles, set color override if colors differ + for (int i = 1; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); + projectiles[i].anchor.readNBT(projNbt); + + // Check if this projectile had different colors + EnergyDisplayData tempDisplay = new EnergyDisplayData(); + tempDisplay.readNBT(projNbt); + if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { + projectiles[i].colorOverride = true; + projectiles[i].innerColor = tempDisplay.innerColor; + projectiles[i].outerColor = tempDisplay.outerColor; + } + } + } + } + } else { + // LEGACY flat format: all data at root level + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + projectiles[0].anchor.readNBT(nbt); + } + + // Backward compat if (nbt.hasKey("orbSpeed")) { homingData.speed = nbt.getFloat("orbSpeed"); } } - // Getters & Setters - public float getOrbSpeed() { - return homingData.speed; - } + // ═══════════════════════════════════════════════════════════════════ + // API GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; - } + public float getOrbSpeed() { return homingData.speed; } + public void setOrbSpeed(float speed) { homingData.speed = speed; } - public float getOrbSize() { - return orbSize; - } + public float getOrbSize() { return orbSize; } + public void setOrbSize(float size) { this.orbSize = size; } - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } + public float getMaxDistance() { return lifespanData.maxDistance; } + public void setMaxDistance(float d) { lifespanData.maxDistance = d; } - public float getMaxDistance() { - return lifespanData.maxDistance; - } + public int getMaxLifetime() { return lifespanData.maxLifetime; } + public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } + public float getDamage() { return combatData.damage; } + public void setDamage(float d) { combatData.damage = d; } - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } + public float getKnockback() { return combatData.knockback; } + public void setKnockback(float k) { combatData.knockback = k; } - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } + public float getKnockbackUp() { return combatData.knockbackUp; } + public void setKnockbackUp(float k) { combatData.knockbackUp = k; } - public float getDamage() { - return combatData.damage; - } + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean h) { homingData.homing = h; } - public void setDamage(float damage) { - combatData.damage = damage; - } + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float s) { homingData.homingStrength = s; } - public float getKnockback() { - return combatData.knockback; - } + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float r) { homingData.homingRange = r; } - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } + public boolean isExplosive() { return combatData.explosive; } + public void setExplosive(boolean e) { combatData.explosive = e; } - public float getKnockbackUp() { - return combatData.knockbackUp; - } + public float getExplosionRadius() { return combatData.explosionRadius; } + public void setExplosionRadius(float r) { combatData.explosionRadius = r; } - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } - public boolean isHoming() { - return homingData.homing; - } + // Shared display data (primary colors) + public int getInnerColor() { return displayData.innerColor; } + public void setInnerColor(int c) { displayData.innerColor = c; } - public void setHoming(boolean homing) { - homingData.homing = homing; - } + public int getOuterColor() { return displayData.outerColor; } + public void setOuterColor(int c) { displayData.outerColor = c; } - public float getHomingStrength() { - return homingData.homingStrength; - } + public float getOuterColorWidth() { return displayData.outerColorWidth; } + public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } + public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } - public float getHomingRange() { - return homingData.homingRange; - } + public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } - public boolean isExplosive() { - return combatData.explosive; - } + // Shared lightning data + public boolean hasLightningEffect() { return lightningData.lightningEffect; } + public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } + public float getLightningDensity() { return lightningData.lightningDensity; } + public void setLightningDensity(float d) { lightningData.lightningDensity = d; } - public float getExplosionRadius() { - return combatData.explosionRadius; - } + public float getLightningRadius() { return lightningData.lightningRadius; } + public void setLightningRadius(float r) { lightningData.lightningRadius = r; } - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } - public int getInnerColor() { - return displayData.innerColor; - } + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } - public void setInnerColor(int innerColor) { - displayData.innerColor = innerColor; - } - - public int getOuterColor() { - return displayData.outerColor; - } - - public void setOuterColor(int outerColor) { - displayData.outerColor = outerColor; - } - - public float getOuterColorWidth() { - return displayData.outerColorWidth; - } - - public void setOuterColorWidth(float outerColorWidth) { - displayData.outerColorWidth = outerColorWidth; - } - - public float getOuterColorAlpha() { - return displayData.outerColorAlpha; - } - - public void setOuterColorAlpha(float outerColorAlpha) { - displayData.outerColorAlpha = outerColorAlpha; - } - - public boolean isOuterColorEnabled() { - return displayData.outerColorEnabled; - } - - public void setOuterColorEnabled(boolean outerColorEnabled) { - displayData.outerColorEnabled = outerColorEnabled; - } - - public float getRotationSpeed() { - return displayData.rotationSpeed; - } - - public void setRotationSpeed(float rotationSpeed) { - displayData.rotationSpeed = rotationSpeed; - } - - public boolean hasLightningEffect() { - return lightningData.lightningEffect; - } - - public void setLightningEffect(boolean lightningEffect) { - lightningData.lightningEffect = lightningEffect; - } - - public float getLightningDensity() { - return lightningData.lightningDensity; - } - - public void setLightningDensity(float lightningDensity) { - lightningData.lightningDensity = lightningDensity; - } - - public float getLightningRadius() { - return lightningData.lightningRadius; - } - - public void setLightningRadius(float lightningRadius) { - lightningData.lightningRadius = lightningRadius; - } - - public int getLightningFadeTime() { - return lightningData.lightningFadeTime; - } - - public void setLightningFadeTime(int lightningFadeTime) { - lightningData.lightningFadeTime = lightningFadeTime; - } - - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - - public int getAnchorPoint() { - return anchorData.anchorPoint.ordinal(); - } + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } + public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } @Override - public void setAnchorPoint(int point) { - this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); + public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } + + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + private int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); } @Override @@ -417,61 +546,95 @@ public class AbilityOrb extends Ability implements IAbilityOrb { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) - ), - FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), - FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed).tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + // Type tab - projectile count and fire delay + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) )); + + // Type tab - orb properties + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) + )); + defs.add(FieldDef.row( + FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); + + // Visual tab - shared primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Visual tab - shared effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + // Anchor point + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java deleted file mode 100644 index f384c4b71..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java +++ /dev/null @@ -1,612 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -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.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -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.EntityAbilityOrb; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.Constants; -import noppes.npcs.client.gui.builder.FieldDef; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class AbilityOrbBarrage extends Ability { - - // Ability-specific properties - private float orbSize = 0.5f; - private int orbAmount = 16; - private int firingSpeed = 2; - private boolean dualCharging = true; - - // Data classes for energy properties - private final EnergyDisplayData colorData = new EnergyDisplayData(); - private final EnergyCombatData combatData = new EnergyCombatData(4.0f, 0.0f, 0.0f, false, 1.5f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.RIGHT_HAND), new EnergyAnchorData(AnchorPoint.LEFT_HAND) - }; - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - - // Array to store entities - private transient List orbEntities = new ArrayList<>(); - private transient EntityAbilityOrb[] chargingEntities = null; - - // Field to keep track of the currently firing orb - private int currentOrb = 0; - - public AbilityOrbBarrage() { - this.typeId = "ability.cnpc.orb_barrage"; - this.name = "Orb Barrage"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 75.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 30; - this.lockMovement = LockMovementType.WINDUP; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animation - this.windUpAnimationName = "Ability_BeamDual_Windup"; - this.activeAnimationName = "Ability_BeamDual_Active"; - } - -// @Override -// @SideOnly(Side.CLIENT) -// public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { -// return new SubGuiAbilityOrbBarrage(this, callback); -// } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - for (int i = 0; i < chargingEntities.length; i++) { - EntityAbilityOrb orbEntity = chargingEntities[i]; - - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - - chargingEntities[i] = null; - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - // Spawn orb in charging mode on first tick of windup - if (tick == 1) { - if (dualCharging) { - chargingEntities = new EntityAbilityOrb[2]; - } else { - chargingEntities = new EntityAbilityOrb[1]; - } - - for (int i = 0; i < chargingEntities.length; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[i]); - - EntityAbilityOrb orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - colorData, combatData, homingData, lightningData, lifespanData, trajectoryData - ); - - if (isPreview()) { - orbEntity.setupPreview(caster, orbSize, colorData, lightningData, anchorData[i], windUpTicks); - } else { - orbEntity.setupCharging(anchorData[i], windUpTicks); - } - orbEntity.setSourceAbility(this); - - chargingEntities[i] = orbEntity; - spawnAbilityEntity(world, orbEntity); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (!orbEntities.isEmpty()) { - boolean allDead = true; - - for (EntityAbilityOrb orbEntity : orbEntities) { - if (orbEntity != null && !orbEntity.isDead) { - allDead = false; - break; - } - } - - if (allDead && currentOrb >= orbAmount) { - signalCompletion(); - return; - } - } - - if (currentOrb >= orbAmount) { - return; - } - - int ticksPerOrb = Math.max(1, 20 / firingSpeed); - - if (tick % ticksPerOrb != 0) { - return; - } - - EnergyAnchorData anchor; - - if (dualCharging) { - anchor = anchorData[currentOrb % 2]; - } else { - anchor = anchorData[0]; - } - - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchor); - - EntityAbilityOrb orb = new EntityAbilityOrb( - world, caster, target, spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - orbSize, colorData, combatData, homingData, lightningData, lifespanData, trajectoryData - ); - - orb.setSourceAbility(this); - world.spawnEntityInWorld(orb); - - orbEntities.add(orb); - currentOrb++; - } - - @Override - public boolean canInterrupt(DamageSource source) { - // Can be interrupted if the caster is hit when the beam is moving - if (!interruptible) { - return false; - } - - // Only direct physical hits can interrupt, not magic, fire, or other indirect damage - if (source == null) { - return false; - } - - // Reject indirect damage types - if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) { - return false; - } - - // Reject damage without a direct attacker entity - if (source.getEntity() == null) { - return false; - } - - // Direct hit from an entity - can interrupt - return true; - } - - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - currentOrb = 0; - - if (chargingEntities != null) { - for (int i = 0; i < chargingEntities.length; i++) { - if (chargingEntities[i] != null && !chargingEntities[i].isDead) { - chargingEntities[i].setDead(); - } - chargingEntities[i] = null; - } - chargingEntities = null; - } - - if (orbEntities != null && !orbEntities.isEmpty()) { - for (EntityAbilityOrb orbEntity : orbEntities) { - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - } - orbEntities.clear(); - } - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create small circle telegraph at target position - Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return orbSize * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("orbSize", orbSize); - nbt.setInteger("orbAmount", orbAmount); - nbt.setInteger("firingSpeed", firingSpeed); - nbt.setBoolean("dualCharging", dualCharging); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - trajectoryData.writeNBT(nbt); - - for (int i = 0; i < anchorData.length; i++) { - NBTTagCompound comp = new NBTTagCompound(); - anchorData[i].writeNBT(comp); - nbt.setTag("Anchor_" + i, comp); - } - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - this.orbAmount = nbt.hasKey("orbAmount") ? nbt.getInteger("orbAmount") : 16; - this.firingSpeed = nbt.hasKey("firingSpeed") ? nbt.getInteger("firingSpeed") : 2; - this.dualCharging = !nbt.hasKey("dualCharging") || nbt.getBoolean("dualCharging"); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); - trajectoryData.readNBT(nbt); - - for (int i = 0; i < anchorData.length; i++) { - if (nbt.hasKey("Anchor_" + i, Constants.NBT.TAG_COMPOUND)) { - anchorData[i].readNBT(nbt.getCompoundTag("Anchor_" + i)); - } else { - anchorData[i] = new EnergyAnchorData(i == 0 ? AnchorPoint.RIGHT_HAND : AnchorPoint.LEFT_HAND); - } - } - } - - // Getters & Setters - public float getOrbSpeed() { - return homingData.speed; - } - - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; - } - - public float getOrbSize() { - return orbSize; - } - - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } - - public int getOrbAmount() { return orbAmount; } - - public void setOrbAmount(int orbAmount) { this.orbAmount = orbAmount; } - - public int getFiringSpeed() { return firingSpeed; } - - public void setFiringSpeed(int firingSpeed) { this.firingSpeed = firingSpeed; } - - public boolean isDualCharging() { return dualCharging; } - - public void setDualCharging(boolean dualCharging) { this.dualCharging = dualCharging; } - - public float getMaxDistance() { - return lifespanData.maxDistance; - } - - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } - - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } - - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } - - public float getDamage() { - return combatData.damage; - } - - public void setDamage(float damage) { - combatData.damage = damage; - } - - public float getKnockback() { - return combatData.knockback; - } - - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } - - public float getKnockbackUp() { - return combatData.knockbackUp; - } - - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } - - public boolean isHoming() { - return homingData.homing; - } - - public void setHoming(boolean homing) { - homingData.homing = homing; - } - - public float getHomingStrength() { - return homingData.homingStrength; - } - - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } - - public float getHomingRange() { - return homingData.homingRange; - } - - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } - - public boolean isExplosive() { - return combatData.explosive; - } - - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } - - public float getExplosionRadius() { - return combatData.explosionRadius; - } - - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } - - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } - - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } - - public int getInnerColor() { - return colorData.innerColor; - } - - public void setInnerColor(int innerColor) { - colorData.innerColor = innerColor; - } - - public int getOuterColor() { - return colorData.outerColor; - } - - public void setOuterColor(int outerColor) { - colorData.outerColor = outerColor; - } - - public float getOuterColorWidth() { - return colorData.outerColorWidth; - } - - public void setOuterColorWidth(float outerColorWidth) { - colorData.outerColorWidth = outerColorWidth; - } - - public float getOuterColorAlpha() { - return colorData.outerColorAlpha; - } - - public void setOuterColorAlpha(float outerColorAlpha) { - colorData.outerColorAlpha = outerColorAlpha; - } - - public boolean isOuterColorEnabled() { - return colorData.outerColorEnabled; - } - - public void setOuterColorEnabled(boolean outerColorEnabled) { - colorData.outerColorEnabled = outerColorEnabled; - } - - public float getRotationSpeed() { - return colorData.rotationSpeed; - } - - public void setRotationSpeed(float rotationSpeed) { - colorData.rotationSpeed = rotationSpeed; - } - - public boolean hasLightningEffect() { - return lightningData.lightningEffect; - } - - public void setLightningEffect(boolean lightningEffect) { - lightningData.lightningEffect = lightningEffect; - } - - public float getLightningDensity() { - return lightningData.lightningDensity; - } - - public void setLightningDensity(float lightningDensity) { - lightningData.lightningDensity = lightningDensity; - } - - public float getLightningRadius() { - return lightningData.lightningRadius; - } - - public void setLightningRadius(float lightningRadius) { - lightningData.lightningRadius = lightningRadius; - } - - public int getLightningFadeTime() { - return lightningData.lightningFadeTime; - } - - public void setLightningFadeTime(int lightningFadeTime) { - lightningData.lightningFadeTime = lightningFadeTime; - } - - private EnergyAnchorData getAnchorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return anchorData[orb]; - } - - public AnchorPoint getAnchorPointEnum(int orb) { return getAnchorData(orb).anchorPoint; } - public void setAnchorPointEnum(int orb, AnchorPoint anchorPoint) { getAnchorData(orb).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int orb) { return getAnchorData(orb).anchorOffsetX; } - public void setAnchorOffsetX(int orb, float x) { getAnchorData(orb).anchorOffsetX = x; } - public float getAnchorOffsetY(int orb) { return getAnchorData(orb).anchorOffsetY; } - public void setAnchorOffsetY(int orb, float y) { getAnchorData(orb).anchorOffsetY = y; } - public float getAnchorOffsetZ(int orb) { return getAnchorData(orb).anchorOffsetZ; } - public void setAnchorOffsetZ(int orb, float z) { getAnchorData(orb).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int orb) { return getAnchorData(orb).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int orb, int point) { getAnchorData(orb).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) - ), - FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.barrage"), - FieldDef.row( - FieldDef.intField("ability.amount", this::getOrbAmount, this::setOrbAmount), - FieldDef.intField("ability.firingSpeed", this::getFiringSpeed, this::setFiringSpeed) - ), - FieldDef.boolField("ability.dualCharge", this::isDualCharging, this::setDualCharging), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), - FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed).tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") - )); - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java deleted file mode 100644 index 3cabf4892..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java +++ /dev/null @@ -1,600 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -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.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -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.EntityAbilityOrb; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.Arrays; -import java.util.List; - -public class AbilityOrbDual extends Ability { - // Ability-specific properties - private float orbSize = 1.0f; - private boolean dualFire= true; - private int dualFireDelay = 5; - - // Data classes for energy properties - public final EnergyDisplayData[] displayData = new EnergyDisplayData[]{ - new EnergyDisplayData(), new EnergyDisplayData() - }; - public final EnergyCombatData combatData = new EnergyCombatData(); - public final EnergyHomingData homingData = new EnergyHomingData(); - public final EnergyLightningData[] lightningData = new EnergyLightningData[]{ - new EnergyLightningData(), new EnergyLightningData() - }; - public final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.RIGHT_HAND), new EnergyAnchorData(AnchorPoint.LEFT_HAND) - }; - private EnergyTrajectoryData[] trajectoryData = new EnergyTrajectoryData[]{ - new EnergyTrajectoryData(), new EnergyTrajectoryData() - }; - - // Transient state for orb entity (used during windup charging) - private transient EntityAbilityOrb orbEntity = null; - private transient EntityAbilityOrb orbEntity2 = null; - - public AbilityOrbDual() { - this.typeId = "ability.cnpc.orb_dual"; - this.name = "Orb Dual"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 25.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 30; - this.lockMovement = LockMovementType.WINDUP; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animation - this.windUpAnimationName = "Ability_OrbDual_Windup"; - this.activeAnimationName = "Ability_OrbDual_Active"; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - // Start moving the orb that was spawned during windup - if (orbEntity != null && !orbEntity.isDead) { - if (isPreview()) { - orbEntity.startPreviewFiring(); - } else { - orbEntity.startMoving(target); - } - } - - if (dualFire) { - if (orbEntity2 != null && !orbEntity2.isDead && dualFireDelay <= 0) { - if (isPreview()) { - orbEntity2.startPreviewFiring(); - } else { - orbEntity2.startMoving(target); - } - } - } else if (orbEntity2 != null) { - orbEntity2.setDead(); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - // Spawn orb in charging mode on first tick of windup - if (tick == 1) { - Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0]); - orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos1.xCoord, spawnPos1.yCoord, spawnPos1.zCoord, orbSize, - displayData[0], combatData, homingData, lightningData[0], lifespanData, trajectoryData[0]); - - Vec3 spawnPos2 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[1]); - orbEntity2 = new EntityAbilityOrb( - world, caster, target, - spawnPos2.xCoord, spawnPos2.yCoord, spawnPos2.zCoord, orbSize, - displayData[1], combatData, homingData, lightningData[1], lifespanData, trajectoryData[1]); - - orbEntity.setSiblingEntityId(orbEntity2.getEntityId()); - orbEntity2.setSiblingEntityId(orbEntity.getEntityId()); - - if (isPreview()) { - orbEntity.setupPreview(caster, orbSize, displayData[0], lightningData[0], anchorData[0], windUpTicks); - orbEntity2.setupPreview(caster, orbSize, displayData[1], lightningData[1], anchorData[1], windUpTicks); - } else { - orbEntity.setupCharging(anchorData[0], windUpTicks); - orbEntity2.setupCharging(anchorData[1], windUpTicks); - } - - orbEntity.setEffects(this.effects); - - if (dualFire) { - orbEntity2.setEffects(this.effects); - } - - orbEntity.setSourceAbility(this); - orbEntity2.setSourceAbility(this); - spawnAbilityEntity(world, orbEntity); - spawnAbilityEntity(world, orbEntity2); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (dualFire) { - if ((orbEntity == null || orbEntity.isDead) && (orbEntity2 == null || orbEntity2.isDead)) { - orbEntity = null; - orbEntity2 = null; - signalCompletion(); - } - - if (tick == dualFireDelay && orbEntity2 != null && !orbEntity2.isDead) { - orbEntity2.startMoving(target); - } - } else { - if (orbEntity == null || orbEntity.isDead) { - orbEntity = null; - signalCompletion(); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn orb entity if still alive - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - - if (orbEntity2 != null && !orbEntity2.isDead) { - orbEntity2.setDead(); - } - - orbEntity = null; - orbEntity2 = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create small circle telegraph at target position - Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return orbSize * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("orbSize", orbSize); - nbt.setBoolean("dualFire", dualFire); - nbt.setInteger("dualFireDelay", dualFireDelay); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - // Backward compat: old key was "orbSpeed" - nbt.setFloat("orbSpeed", homingData.speed); - - NBTTagCompound orb1 = new NBTTagCompound(); - NBTTagCompound orb2 = new NBTTagCompound(); - - for (int i = 0; i < 2; i++) { - NBTTagCompound orb = i == 0 ? orb1 : orb2; - anchorData[i].writeNBT(orb); - displayData[i].writeNBT(orb); - lightningData[i].writeNBT(orb); - trajectoryData[i].writeNBT(orb); - } - - nbt.setTag("Orb_1", orb1); - nbt.setTag("Orb_2", orb2); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - NBTTagCompound orb1 = nbt.hasKey("Orb_1") ? nbt.getCompoundTag("Orb_1") : new NBTTagCompound(); - NBTTagCompound orb2 = nbt.hasKey("Orb_2") ? nbt.getCompoundTag("Orb_2") : new NBTTagCompound(); - - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); - this.dualFireDelay = nbt.hasKey("dualFireDelay") ? nbt.getInteger("dualFireDelay") : 0; - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - // Backward compat: old key was "orbSpeed" - if (nbt.hasKey("orbSpeed")) { - homingData.speed = nbt.getFloat("orbSpeed"); - } - - for (int i = 0; i < 2; i++) { - NBTTagCompound orb = i == 0 ? orb1 : orb2; - anchorData[i].readNBT(orb); - displayData[i].readNBT(orb); - lightningData[i].readNBT(orb); - trajectoryData[i].readNBT(orb); - } - } - - // Getters & Setters - private EnergyDisplayData getColorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return displayData[orb]; - } - private EnergyLightningData getLightningData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return lightningData[orb]; - } - private EnergyAnchorData getAnchorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return anchorData[orb]; - } - - public float getOrbSpeed() { - return homingData.speed; - } - - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; - } - - public float getOrbSize() { - return orbSize; - } - - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } - - public boolean isDualFire() { - return dualFire; - } - - public void setDualFire(boolean dualFire) { - this.dualFire = dualFire; - } - - public int getDualFireDelay() { - return dualFireDelay; - } - - public void setDualFireDelay(int dualFireDelay) { - this.dualFireDelay = dualFireDelay; - } - - public float getMaxDistance() { - return lifespanData.maxDistance; - } - - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } - - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } - - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } - - public float getDamage() { - return combatData.damage; - } - - public void setDamage(float damage) { - combatData.damage = damage; - } - - public float getKnockback() { - return combatData.knockback; - } - - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } - - public float getKnockbackUp() { - return combatData.knockbackUp; - } - - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } - - public boolean isHoming() { - return homingData.homing; - } - - public void setHoming(boolean homing) { - homingData.homing = homing; - } - - public float getHomingStrength() { - return homingData.homingStrength; - } - - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } - - public float getHomingRange() { - return homingData.homingRange; - } - - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } - - public boolean isExplosive() { - return combatData.explosive; - } - - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } - - public float getExplosionRadius() { - return combatData.explosionRadius; - } - - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } - - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } - - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } - - - public int getInnerColor(int orb) { return getColorData(orb).innerColor; } - public void setInnerColor(int orb, int innerColor) { getColorData(orb).innerColor = innerColor; } - public int getOuterColor(int orb) { return getColorData(orb).outerColor; } - public void setOuterColor(int orb, int outerColor) { getColorData(orb).outerColor = outerColor; } - public boolean isOuterColorEnabled(int orb) { return getColorData(orb).outerColorEnabled; } - public void setOuterColorEnabled(int orb, boolean enabled) { getColorData(orb).outerColorEnabled = enabled; } - public float getOuterColorWidth(int orb) { return getColorData(orb).outerColorWidth; } - public void setOuterColorWidth(int orb, float width) { getColorData(orb).outerColorWidth = width; } - public float getOuterColorAlpha(int orb) { return getColorData(orb).outerColorAlpha; } - public void setOuterColorAlpha(int orb, float alpha) { getColorData(orb).outerColorAlpha = alpha; } - public float getRotationSpeed(int orb) { return getColorData(orb).rotationSpeed; } - public void setRotationSpeed(int orb, float speed) { getColorData(orb).rotationSpeed = speed; } - - public int getInnerColor() { return getInnerColor(0); } - public void setInnerColor(int innerColor) { setInnerColor(0, innerColor); } - public int getOuterColor() { return getOuterColor(0); } - public void setOuterColor(int outerColor) { setOuterColor(0, outerColor); } - public boolean isOuterColorEnabled() { return isOuterColorEnabled(0); } - public void setOuterColorEnabled(boolean enabled) { setOuterColorEnabled(0, enabled); } - public float getOuterColorWidth() { return getOuterColorWidth(0); } - public void setOuterColorWidth(float width) { setOuterColorWidth(0, width); } - public float getOuterColorAlpha() { return getOuterColorAlpha(0); } - public void setOuterColorAlpha(float alpha) { setOuterColorAlpha(0, alpha); } - public float getRotationSpeed() { return getRotationSpeed(0); } - public void setRotationSpeed(float speed) { setRotationSpeed(0, speed); } - - - public boolean hasLightningEffect(int orb) { return getLightningData(orb).lightningEffect; } - public void setLightningEffect(int orb, boolean lightningEffect) { getLightningData(orb).lightningEffect = lightningEffect; } - public float getLightningDensity(int orb) { return getLightningData(orb).lightningDensity; } - public void setLightningDensity(int orb, float lightningDensity) { getLightningData(orb).lightningDensity = lightningDensity; } - public float getLightningRadius(int orb) { return getLightningData(orb).lightningRadius; } - public void setLightningRadius(int orb, float lightningRadius) { getLightningData(orb).lightningRadius = lightningRadius; } - - public boolean hasLightningEffect() { return hasLightningEffect(0); } - public void setLightningEffect(boolean lightningEffect) { setLightningEffect(0, lightningEffect); } - public float getLightningDensity() { return getLightningDensity(0); } - public void setLightningDensity(float lightningDensity) { setLightningDensity(0, lightningDensity); } - public float getLightningRadius() { return getLightningRadius(0); } - public void setLightningRadius(float lightningRadius) { setLightningRadius(0, lightningRadius); } - - - public AnchorPoint getAnchorPointEnum(int orb) { return getAnchorData(orb).anchorPoint; } - public void setAnchorPointEnum(int orb, AnchorPoint anchorPoint) { getAnchorData(orb).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int orb) { return getAnchorData(orb).anchorOffsetX; } - public void setAnchorOffsetX(int orb, float x) { getAnchorData(orb).anchorOffsetX = x; } - public float getAnchorOffsetY(int orb) { return getAnchorData(orb).anchorOffsetY; } - public void setAnchorOffsetY(int orb, float y) { getAnchorData(orb).anchorOffsetY = y; } - public float getAnchorOffsetZ(int orb) { return getAnchorData(orb).anchorOffsetZ; } - public void setAnchorOffsetZ(int orb, float z) { getAnchorData(orb).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int orb) { return getAnchorData(orb).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int orb, int point) { getAnchorData(orb).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) - ), - FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.dual"), - FieldDef.boolField("ability.dualFire", this::isDualFire, this::setDualFire), - FieldDef.intField("ability.dualFireDelay", this::getDualFireDelay, this::setDualFireDelay) - .visibleWhen(this::isDualFire), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - Orb 1 - FieldDef.section("ability.section.orb1").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(0), v -> setAnchorOffsetX(0, v)), - FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(0), v -> setAnchorOffsetY(0, v)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(0), v -> setAnchorOffsetZ(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(0), v -> setInnerColor(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(0), v -> setOuterColorEnabled(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(0), v -> setOuterColor(0, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(0), v -> setOuterColorWidth(0, v)) - .visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(0), v -> setOuterColorAlpha(0, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(0)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(0), v -> setRotationSpeed(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(0), v -> setLightningEffect(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(0), v -> setLightningDensity(0, v)) - .range(0.01f, 5.0f).visibleWhen(() -> hasLightningEffect(0)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(0), v -> setLightningRadius(0, v)) - .range(0.1f, 10.0f).visibleWhen(() -> hasLightningEffect(0)) - ).tab("ability.tab.visual"), - // Visual tab - Orb 2 - FieldDef.section("ability.section.orb2").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> getAnchorOffsetX(1), v -> setAnchorOffsetX(1, v)), - FieldDef.floatField("ability.anchor.offsetY", () -> getAnchorOffsetY(1), v -> setAnchorOffsetY(1, v)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", () -> getAnchorOffsetZ(1), v -> setAnchorOffsetZ(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(1), v -> setInnerColor(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(1), v -> setOuterColorEnabled(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(1), v -> setOuterColor(1, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(1), v -> setOuterColorWidth(1, v)) - .visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(1), v -> setOuterColorAlpha(1, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(1)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(1), v -> setRotationSpeed(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(1), v -> setLightningEffect(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(1), v -> setLightningDensity(1, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(1)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(1), v -> setLightningRadius(1, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(1)) - ).tab("ability.tab.visual") - )); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index 75c27a507..b6657ac60 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -50,6 +50,11 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { this.showTelegraph = false; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 3155310ef..9be02101f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -61,6 +61,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { this.showTelegraph = true; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 1623bacd8..5a540d634 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -85,6 +85,11 @@ public class AbilityTrap extends Ability implements IAbilityTrap { this.telegraphType = TelegraphType.CIRCLE; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 606df7742..5e1ff694f 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -174,11 +174,23 @@ public class DataAbilities { // Handle phase-specific logic switch (currentAbility.getPhase()) { case WINDUP: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up telegraph, sound, animation, locks + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(currentAbility, target); + playAbilitySound(currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } currentAbility.onWindUpTick(npc, target, npc.worldObj, currentAbility.getCurrentTick()); break; case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { // Just entered ACTIVE phase - lock telegraph position if it was following // This commits the ability to its current target position TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); @@ -207,6 +219,11 @@ public class DataAbilities { releaseLockedPosition(); } + // Burst re-fire without replay: let entity-spawning abilities spawn+fire in one step + if (oldPhase == AbilityPhase.BURST_DELAY && !currentAbility.isBurstReplayAnimations()) { + currentAbility.onBurstRefire(npc, target, npc.worldObj); + } + // Play active sound and animation playAbilitySound(currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); @@ -240,6 +257,31 @@ public class DataAbilities { handleAbilityCompletion(target); return; } + + // Auto-complete for burst overlap mode (entities fly independently) + // This allows entity-spawning abilities to immediately chain next burst + // without each type needing to check burst state in their onActiveTick() + // Wait until all staggered projectiles have been fired before auto-completing + if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap() + && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() + && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { + currentAbility.signalCompletion(); + } + + // Check if ability entered burst delay during onActiveTick or overlap auto-complete + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + // Release all locks - free movement/rotation during delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + if (hitScanActive) releaseRotationControl(); + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); break; case DAZED: diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index fd8461245..7bc5c3846 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -3,6 +3,7 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilitySlot; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket; @@ -61,6 +62,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Existing preset names for duplicate checking private final Set existingPresetNames = new HashSet<>(); + // Pending variant selection + private String pendingTypeId = null; + public static int modIndex = 0; public static ScrollType scrollType = ScrollType.CNPC; @@ -197,8 +201,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String displayName = availableTypesScroll.getSelected(); String typeId = displayNameToTypeId.get(displayName); if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } Ability newAbility = AbilityController.Instance.create(typeId); if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } newAbility.setId(UUID.randomUUID().toString()); npcSlots.add(AbilitySlot.inline(newAbility)); selectedAbilityIndex = npcSlots.size() - 1; @@ -633,7 +646,24 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiAbilityEditMode) { + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui; + int idx = variantGui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + variantGui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + npcSlots.add(AbilitySlot.inline(newAbility)); + selectedAbilityIndex = npcSlots.size() - 1; + updateNpcAbilitiesList(); + selectAbilityByIndex(selectedAbilityIndex); + save(); + } + } + pendingTypeId = null; + initGui(); + } else if (subgui instanceof SubGuiAbilityEditMode) { int mode = ((SubGuiAbilityEditMode) subgui).getResult(); if (mode < 0) return; // cancelled 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 c8802a1e0..bcfce7687 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -324,7 +324,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi @Override public void unFocused(GuiNpcTextField textField) { if (textField.id < DECLARATIVE_ID_START) return; - builder.handleTextFieldEvent(textField.id, textField); + if (builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); + } } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java new file mode 100644 index 000000000..09d875dbe --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java @@ -0,0 +1,92 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiScrollWindow; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +/** + * SubGui for selecting a variant/template when creating a new ability. + * Uses a scroll window so external mods can register many variants. + */ +public class SubGuiAbilityVariantSelect extends SubGuiInterface { + + private static final int VARIANT_BTN_START = 10; + private static final int BTN_H = 20; + private static final int BTN_PAD = 2; + + private final List variants; + private final List displayNames = new ArrayList<>(); + private int selectedIndex = -1; + + public SubGuiAbilityVariantSelect(List variants) { + this.variants = variants; + for (AbilityVariant variant : variants) { + displayNames.add(StatCollector.translateToLocal(variant.getDisplayKey())); + } + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + addLabel(new GuiNpcLabel(0, "ability.selectVariant", guiLeft + 10, guiTop + 8)); + + // Scroll window for variant buttons + int swX = guiLeft + 5; + int swY = guiTop + 22; + int swW = 190; + int swH = 155; + + GuiScrollWindow sw = new GuiScrollWindow(this, swX, swY, swW, swH, 0); + addScrollableGui(0, sw); // Must register BEFORE adding components (initGui clears them) + + int localY = 2; + int btnW = swW - 14; // Leave room for scrollbar + for (int i = 0; i < displayNames.size(); i++) { + GuiNpcButton btn = new GuiNpcButton(VARIANT_BTN_START + i, 2, localY, btnW, BTN_H, displayNames.get(i)); + if (i == selectedIndex) { + btn.packedFGColour = 0x55FF55; + } + sw.addButton(btn); + localY += BTN_H + BTN_PAD; + } + sw.maxScrollY = Math.max(localY - swH, 0); + + // Select / Cancel buttons + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); + getButton(0).setEnabled(selectedIndex >= 0); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + if (id == 0 && selectedIndex >= 0) { + close(); + } else if (id == 1) { + selectedIndex = -1; + close(); + } else if (id >= VARIANT_BTN_START && id < VARIANT_BTN_START + displayNames.size()) { + selectedIndex = id - VARIANT_BTN_START; + initGui(); + } + } + + public int getSelectedIndex() { + return selectedIndex; + } + + public List getVariants() { + return variants; + } +} 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 42e117ecf..b1f123956 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -120,6 +120,9 @@ public class GuiFieldBuilder { continue; } + // Skip invisible fields + if (!def.isVisible()) continue; + // Section header if (def.getType() == FieldType.SECTION_HEADER) { y += 3; @@ -391,7 +394,7 @@ public class GuiFieldBuilder { /** * Handles text field unfocus events for declarative fields. - * Call from parent GUI's unFocused(). Returns true if the event was handled. + * Call from parent GUI's unFocused(). Returns true if the value actually changed. */ public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { FieldDef def = textFieldMap.get(textFieldId); @@ -399,14 +402,36 @@ public class GuiFieldBuilder { switch (def.getType()) { case FLOAT: - try { def.setValue(Float.parseFloat(field.getText())); } catch (NumberFormatException ignored) {} - return true; + try { + float newVal = Float.parseFloat(field.getText()); + Object old = def.getValue(); + float oldVal = old instanceof Number ? ((Number) old).floatValue() : 0f; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) {} + return false; case INT: - try { def.setValue(Integer.parseInt(field.getText())); } catch (NumberFormatException ignored) {} - return true; + try { + int newVal = Integer.parseInt(field.getText()); + Object old = def.getValue(); + int oldVal = old instanceof Number ? ((Number) old).intValue() : 0; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) {} + return false; case STRING: - def.setValue(field.getText()); - return true; + String newVal = field.getText(); + Object old = def.getValue(); + String oldVal = old != null ? old.toString() : ""; + if (!newVal.equals(oldVal)) { + def.setValue(newVal); + return true; + } + return false; default: return false; } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java index f911c6f43..b06f9d097 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -16,8 +16,10 @@ import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import noppes.npcs.client.NoppesUtil; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect; +import noppes.npcs.client.gui.advanced.SubGuiAbilityVariantSelect; import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm; import noppes.npcs.client.gui.util.AbilityPreviewExecutor; import noppes.npcs.client.gui.util.GuiAbilityInterface; @@ -68,6 +70,9 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private Ability pendingSaveAbility = null; private boolean pendingNewCreation = false; + // ==================== PENDING VARIANT ==================== + private String pendingTypeId = null; + // ==================== PREVIEW ==================== private AbilityPreviewExecutor previewExecutor; private long prevTick = 0; @@ -343,11 +348,41 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiAbilityTypeSelect) { + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui; + int idx = variantGui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + variantGui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + if (hasDuplicateName(newAbility)) { + pendingSaveAbility = newAbility; + pendingNewCreation = true; + pendingTypeId = null; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + pendingTypeId = null; + saveAndOpenConfig(newAbility); + return; + } + } + pendingTypeId = null; + } else if (subgui instanceof SubGuiAbilityTypeSelect) { String typeId = ((SubGuiAbilityTypeSelect) subgui).getSelectedTypeId(); if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } Ability newAbility = AbilityController.Instance.create(typeId); if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } newAbility.setId(UUID.randomUUID().toString()); if (hasDuplicateName(newAbility)) { pendingSaveAbility = newAbility; diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 497134b16..3238d2851 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1605,11 +1605,8 @@ ability.cnpc.slam=Slam ability.cnpc.heavy_hit=Heavy Hit ability.cnpc.cutter=Cutter ability.cnpc.beam=Beam -ability.cnpc.beam_dual=Beam Dual ability.cnpc.projectile=Projectile ability.cnpc.orb=Orb -ability.cnpc.orb_dual=Orb Dual -ability.cnpc.orb_barrage=Orb Barrage ability.cnpc.charge=Charge ability.cnpc.dash=Dash ability.cnpc.teleport=Teleport @@ -1620,7 +1617,6 @@ ability.cnpc.heal=Heal ability.cnpc.hazard=Hazard ability.cnpc.trap=Trap ability.cnpc.disc=Disc -ability.cnpc.disc_dual=Disc Dual ability.cnpc.laser_shot=Laser Shot ability.cnpc.sweeper=Sweeper @@ -1674,14 +1670,16 @@ ability.section.boomerang=Boomerang ability.section.explosive=Explosive ability.section.colors=Colors ability.section.effects=Effects -ability.section.dual=Dual -ability.section.beam1=Beam 1 -ability.section.beam2=Beam 2 -ability.section.disc1=Disc 1 -ability.section.disc2=Disc 2 -ability.section.orb1=Orb 1 -ability.section.orb2=Orb 2 -ability.section.barrage=Barrage +ability.section.burst=Burst +ability.section.visual=Visual +ability.section.projectile1=Projectile 1 +ability.section.projectile2=Projectile 2 +ability.section.projectile3=Projectile 3 +ability.section.projectile4=Projectile 4 +ability.section.projectile5=Projectile 5 +ability.section.projectile6=Projectile 6 +ability.section.projectile7=Projectile 7 +ability.section.projectile8=Projectile 8 ability.section.counter=Counter ability.section.area=Area ability.section.damage=Damage @@ -1828,9 +1826,20 @@ ability.lightning=Lightning ability.lightningDensity=Density ability.lightningRadius=Radius -# Dual Energy Projectile Settings -ability.dualFire=Dual Fire +# Projectile Count / Settings +ability.projectileCount=Count ability.dualFireDelay=Fire Delay +ability.fireDelay=Fire Delay +ability.colorOverride=Color Override + +# Burst System +ability.burstEnabled=Burst +ability.burstAmount=Amount +ability.burstDelay=Delay +ability.burstReplayAnimations=Replay Animations +ability.burstOverlap=Overlap +ability.hover.burstOverlap=When enabled, projectiles from previous bursts keep flying while new ones fire +ability.hover.burstReplay=Replay windup and active animations for each burst iteration # Ability Save/Load ability.save.confirm=Save ability preset @@ -1848,6 +1857,12 @@ ability.edit.mode=How should this ability be edited? ability.cloneModify=Clone & Edit ability.modifyParent=Edit Parent +# Ability Variant Selection +ability.selectVariant=Select Variant +ability.variant.single=Single +ability.variant.dual=Dual +ability.variant.barrage=Barrage + # Ability Type Selection ability.selectType=Select Ability Type: From 12380d838ba69f7968e1d397562ca166e30c9051 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 22:39:47 -0500 Subject: [PATCH 11/76] lighning --- .../renderer/RenderAbilityProjectile.java | 2 +- .../lightning/AttachedLightningRenderer.java | 21 ++++++------------- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java index 2ba840aec..96e8e7b08 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java @@ -31,7 +31,7 @@ public abstract class RenderAbilityProjectile extends Render { */ protected void setupRenderState() { GL11.glPushMatrix(); - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_ALPHA_TEST); diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java index 4fa28cda8..d68c4037b 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -88,17 +88,14 @@ public class AttachedLightningRenderer { /** * Render all active arcs in local space. * Call this after glTranslated to entity position. + * Note: Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). This avoids nesting + * glPushAttrib calls which can overflow the GL attrib stack (depth 16) when + * other mods also push attribs during entity rendering. */ public void render() { if (arcs.isEmpty()) return; - // Setup GL state - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); Tessellator tess = Tessellator.instance; @@ -114,7 +111,6 @@ public class AttachedLightningRenderer { } GL11.glDepthMask(true); - GL11.glPopAttrib(); } public int getArcCount() { @@ -239,6 +235,8 @@ public class AttachedLightningRenderer { /** * Render a single instant lightning arc (no fading, drawn this frame only). + * Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). */ public static void renderInstantArc(float radius, int outerColor, int innerColor) { double theta = rand.nextDouble() * Math.PI * 2; @@ -254,12 +252,6 @@ public class AttachedLightningRenderer { List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement); - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); Tessellator tess = Tessellator.instance; @@ -267,7 +259,6 @@ public class AttachedLightningRenderer { renderBoltPath(tess, points, innerColor, 0.012f, 0.7f); GL11.glDepthMask(true); - GL11.glPopAttrib(); } /** From 4c5e44fb2249eee82515da6c9fc88f0b37e16b5f Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 6 Feb 2026 22:43:07 -0500 Subject: [PATCH 12/76] Add anchor offset methods and update ability variant selection UI --- .../data/ability/AbilityVariant.java | 15 +++ .../data/ability/type/AbilityBeam.java | 3 + .../data/ability/type/AbilityDisc.java | 3 + .../data/ability/type/AbilityOrb.java | 3 + src/main/java/kamkeel/npcs/util/Register.java | 3 +- .../advanced/SubGuiAbilityVariantSelect.java | 126 +++++++++++++----- .../npcs/client/gui/util/GuiCustomScroll.java | 17 ++- 7 files changed, 134 insertions(+), 36 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java index 91d151a85..797e6b20b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java @@ -13,6 +13,7 @@ import java.util.function.Consumer; public class AbilityVariant { private final String displayKey; + private final String group; private final Consumer configurator; /** @@ -20,7 +21,17 @@ public class AbilityVariant { * @param configurator Lambda that configures the ability with preset values */ public AbilityVariant(String displayKey, Consumer configurator) { + this(displayKey, null, configurator); + } + + /** + * @param displayKey Lang key for the variant display name + * @param group Optional group header shown in the variant selection GUI (e.g., "DBC Addon") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, String group, Consumer configurator) { this.displayKey = displayKey; + this.group = group; this.configurator = configurator; } @@ -28,6 +39,10 @@ public class AbilityVariant { return displayKey; } + public String getGroup() { + return group; + } + /** * Apply this variant's preset configuration to the given ability. */ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 5f12cc183..91b0287eb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -521,6 +521,9 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } private int clampIndex(int index) { return Math.max(0, Math.min(index, projectileCount - 1)); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index d38d6a0b2..e0ed1b43c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -551,6 +551,9 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } private int clampIndex(int index) { return Math.max(0, Math.min(index, projectileCount - 1)); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 024fe2912..e0f6bc19f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -536,6 +536,9 @@ public class AbilityOrb extends Ability implements IAbilityOrb { public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } private int clampIndex(int index) { return Math.max(0, Math.min(index, projectileCount - 1)); diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index c97188316..ff6b0f24e 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -29,7 +29,8 @@ public class Register { public static boolean isEmpty(String registryKey) { if (REGISTERED_NAMESPACES.isEmpty()) return true; - if (REGISTERED_NAMESPACES.get(registryKey).isEmpty()) return true; + List list = REGISTERED_NAMESPACES.get(registryKey); + if (list == null || list.isEmpty()) return true; return false; } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java index 09d875dbe..1c65d0dc6 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java @@ -2,10 +2,10 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import net.minecraft.client.gui.GuiButton; -import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiCustomScroll; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; -import noppes.npcs.client.gui.util.GuiScrollWindow; +import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; @@ -13,23 +13,18 @@ import java.util.List; /** * SubGui for selecting a variant/template when creating a new ability. - * Uses a scroll window so external mods can register many variants. + * Uses a scroll list with group headers for external addon variants. */ -public class SubGuiAbilityVariantSelect extends SubGuiInterface { - - private static final int VARIANT_BTN_START = 10; - private static final int BTN_H = 20; - private static final int BTN_PAD = 2; +public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICustomScrollListener { private final List variants; - private final List displayNames = new ArrayList<>(); private int selectedIndex = -1; + // Maps each scroll list index to a variant list index (-1 for non-selectable entries) + private final List scrollToVariantIndex = new ArrayList<>(); + public SubGuiAbilityVariantSelect(List variants) { this.variants = variants; - for (AbilityVariant variant : variants) { - displayNames.add(StatCollector.translateToLocal(variant.getDisplayKey())); - } setBackground("menubg.png"); xSize = 200; ySize = 216; @@ -41,26 +36,78 @@ public class SubGuiAbilityVariantSelect extends SubGuiInterface { addLabel(new GuiNpcLabel(0, "ability.selectVariant", guiLeft + 10, guiTop + 8)); - // Scroll window for variant buttons - int swX = guiLeft + 5; - int swY = guiTop + 22; - int swW = 190; - int swH = 155; + // Build the unsorted scroll list with group headers + List scrollList = new ArrayList<>(); + scrollToVariantIndex.clear(); - GuiScrollWindow sw = new GuiScrollWindow(this, swX, swY, swW, swH, 0); - addScrollableGui(0, sw); // Must register BEFORE adding components (initGui clears them) + boolean hasBaseVariants = false; + boolean hasGroupedVariants = false; - int localY = 2; - int btnW = swW - 14; // Leave room for scrollbar - for (int i = 0; i < displayNames.size(); i++) { - GuiNpcButton btn = new GuiNpcButton(VARIANT_BTN_START + i, 2, localY, btnW, BTN_H, displayNames.get(i)); - if (i == selectedIndex) { - btn.packedFGColour = 0x55FF55; - } - sw.addButton(btn); - localY += BTN_H + BTN_PAD; + for (AbilityVariant v : variants) { + if (v.getGroup() == null) + hasBaseVariants = true; + else + hasGroupedVariants = true; } - sw.maxScrollY = Math.max(localY - swH, 0); + + // Add base (non-grouped) variants first + for (int i = 0; i < variants.size(); i++) { + if (variants.get(i).getGroup() == null) { + scrollList.add(variants.get(i).getDisplayKey()); + scrollToVariantIndex.add(i); + } + } + + // Blank separator between base and grouped variants + if (hasBaseVariants && hasGroupedVariants) { + scrollList.add(""); + scrollToVariantIndex.add(-1); + } + + // Add grouped variants with group headers + String lastGroup = null; + for (int i = 0; i < variants.size(); i++) { + AbilityVariant v = variants.get(i); + if (v.getGroup() == null) + continue; + + if (!v.getGroup().equals(lastGroup)) { + scrollList.add(v.getGroup()); + scrollToVariantIndex.add(-1); + lastGroup = v.getGroup(); + } + + scrollList.add(v.getDisplayKey()); + scrollToVariantIndex.add(i); + } + + GuiCustomScroll scroll = new GuiCustomScroll(this, 0); + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = guiTop + 22; + scroll.setUnsortedList(scrollList); + scroll.setSize(190, 155); + + // Mark blank separators and group headers as non-interactive colored entries + scroll.colors.put("", 0x000000); + if (lastGroup != null) { + for (int i = 0; i < variants.size(); i++) { + String group = variants.get(i).getGroup(); + if (group != null) + scroll.colors.put(group, 0xFFFF00); // Yellow + } + } + + // Restore selection in scroll + if (selectedIndex >= 0) { + for (int s = 0; s < scrollToVariantIndex.size(); s++) { + if (scrollToVariantIndex.get(s) == selectedIndex) { + scroll.selected = s; + break; + } + } + } + + addScroll(scroll); // Select / Cancel buttons addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); @@ -68,6 +115,24 @@ public class SubGuiAbilityVariantSelect extends SubGuiInterface { addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); } + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0 && scroll.selected >= 0 && scroll.selected < scrollToVariantIndex.size()) { + int variantIdx = scrollToVariantIndex.get(scroll.selected); + if (variantIdx >= 0) { + selectedIndex = variantIdx; + getButton(0).setEnabled(true); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (selectedIndex >= 0) { + close(); + } + } + @Override public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; @@ -76,9 +141,6 @@ public class SubGuiAbilityVariantSelect extends SubGuiInterface { } else if (id == 1) { selectedIndex = -1; close(); - } else if (id >= VARIANT_BTN_START && id < VARIANT_BTN_START + displayNames.size()) { - selectedIndex = id - VARIANT_BTN_START; - initGui(); } } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java index e726239b1..f9b3df568 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java @@ -200,7 +200,8 @@ public class GuiCustomScroll extends GuiScreen { int k = (14 * i + 4) - scrollY; if (k >= 4 && k + 12 < ySize) { int xOffset = scrollHeight < ySize - 8 ? 0 : 10; - String displayString = StatCollector.translateToLocal(list.get(i)); + String rawEntry = list.get(i); + String displayString = StatCollector.translateToLocal(rawEntry); String text = ""; float maxWidth = (xSize + xOffset - 8) * 0.8f; @@ -215,7 +216,13 @@ public class GuiCustomScroll extends GuiScreen { text += "..."; } else text = displayString; - if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { + + // Entries with a custom color are non-interactive (headers/separators) + Integer customColor = colors.get(rawEntry); + if (customColor != null) { + if (!text.isEmpty()) + fontRendererObj.drawString(text, j, k, customColor); + } else if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff); drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff); drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff); @@ -239,13 +246,17 @@ public class GuiCustomScroll extends GuiScreen { private int getMouseOver(int i, int j) { i -= guiLeft; j -= guiTop; - //fontRenderer.drawString(".", i , j, 0xffffff); if (i >= 4 && i < xSize - 4 && j >= 4 && j < ySize) { for (int j1 = 0; j1 < list.size(); j1++) { if (!mouseInOption(i, j, j1)) { continue; } + // Skip non-interactive entries (colored headers/separators) + if (colors.containsKey(list.get(j1))) { + continue; + } + return j1; } From 9054abadeb0b1fd39ba0a1c330cb99adfd9ca9be Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 7 Feb 2026 01:54:16 -0500 Subject: [PATCH 13/76] Fix Ability --- src/api | 2 +- .../npcs/controllers/data/ability/type/AbilityDisc.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api b/src/api index 8917e37a6..fd4c77d01 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 8917e37a6d35230a5c7b75ac8f89428edf1aabd2 +Subproject commit fd4c77d015add1f6f3012a1681561b2774f2f997 diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index e0ed1b43c..22832a104 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -91,8 +91,8 @@ public class AbilityDisc extends Ability implements IAbilityDisc { */ private AnchorPoint getDefaultAnchor(int index) { switch (index) { - case 0: return AnchorPoint.LEFT_HAND; - case 1: return AnchorPoint.RIGHT_HAND; + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; default: return AnchorPoint.FRONT; } } From 0fcf37542b244c95627ef729a671421fd1aab2fa Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 7 Feb 2026 15:31:49 -0500 Subject: [PATCH 14/76] Update AbilityDash.java --- .../data/ability/type/AbilityDash.java | 67 ++++++++++--------- 1 file changed, 34 insertions(+), 33 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 f80f336aa..79db9dd42 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 @@ -87,13 +87,14 @@ public class AbilityDash extends Ability implements IAbilityDash { // Type-specific parameters private DashMode dashMode = DashMode.DEFENSIVE; private float dashDistance = 4.0f; - private float dashSpeed = 1.5f; + private float dashSpeed = 0.5f; // Runtime state private transient Vec3 dashDirection; private transient double startX, startY, startZ; private transient double prevTickX, prevTickZ; private transient DashDirection chosenDirection; + private transient int maxActiveTicks; public AbilityDash() { this.typeId = "ability.cnpc.dash"; @@ -139,6 +140,9 @@ public class AbilityDash extends Ability implements IAbilityDash { prevTickX = caster.posX; prevTickZ = caster.posZ; + // Safety timeout: expected ticks + generous buffer to prevent infinite dash + maxActiveTicks = dashSpeed > 0 ? (int)(dashDistance / dashSpeed) + 10 : 10; + // Choose random direction based on mode DashDirection[] directions = dashMode == DashMode.AGGRESSIVE ? AGGRESSIVE_DIRECTIONS @@ -164,22 +168,28 @@ public class AbilityDash extends Ability implements IAbilityDash { 0, Math.cos(yawRad) ); - } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (dashDirection == null) return; + // Safety timeout or missing state: force-complete to prevent stuck NPC + if (!isPreview() && (dashDirection == null || tick > maxActiveTicks)) { + stopDash(caster); + signalCompletion(); + return; + } + + if (dashDirection == null) { + signalCompletion(); + return; + } // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall if (!isPreview() && tick > 1) { - double movedThisTick = Math.sqrt( - Math.pow(caster.posX - prevTickX, 2) + - Math.pow(caster.posZ - prevTickZ, 2)); - if (movedThisTick < 0.01) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + double dx = caster.posX - prevTickX; + double dz = caster.posZ - prevTickZ; + if (dx * dx + dz * dz < 0.0001) { + stopDash(caster); signalCompletion(); return; } @@ -187,28 +197,18 @@ public class AbilityDash extends Ability implements IAbilityDash { prevTickX = caster.posX; prevTickZ = caster.posZ; - // Calculate distance traveled - double distanceTraveled = Math.sqrt( - Math.pow(caster.posX - startX, 2) + - Math.pow(caster.posZ - startZ, 2) - ); - // Check if reached max distance - if (distanceTraveled >= dashDistance) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; - } + double travelDx = caster.posX - startX; + double travelDz = caster.posZ - startZ; + if (travelDx * travelDx + travelDz * travelDz >= (double) dashDistance * dashDistance) { + stopDash(caster); signalCompletion(); return; } // Block detection (skip in preview - no real world collision) if (!isPreview() && isDashBlocked(caster)) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + stopDash(caster); signalCompletion(); return; } @@ -225,8 +225,7 @@ public class AbilityDash extends Ability implements IAbilityDash { } } - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + private void stopDash(EntityLivingBase caster) { caster.motionX = 0; caster.motionZ = 0; if (!isPreview()) { @@ -234,19 +233,21 @@ public class AbilityDash extends Ability implements IAbilityDash { } } + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + stopDash(caster); + } + @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; - } + stopDash(caster); } @Override public void cleanup() { dashDirection = null; chosenDirection = null; + maxActiveTicks = 0; } private boolean isDashBlocked(EntityLivingBase caster) { @@ -281,7 +282,7 @@ public class AbilityDash extends Ability implements IAbilityDash { this.dashMode = DashMode.DEFENSIVE; } this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; - this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 1.5f; + this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 0.5f; } // Getters & Setters From c05b6e60b8b1ef7906dadfed7a3f4a697eee4dbe Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 7 Feb 2026 17:07:05 -0500 Subject: [PATCH 15/76] Update AbilityDash.java --- .../npcs/controllers/data/ability/type/AbilityDash.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 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 79db9dd42..2ea0095eb 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 @@ -168,6 +168,9 @@ public class AbilityDash extends Ability implements IAbilityDash { 0, Math.cos(yawRad) ); + + // Small upward impulse for a skip/hop arc (gravity handles the descent) + caster.motionY = 0.2; } @Override @@ -213,9 +216,8 @@ public class AbilityDash extends Ability implements IAbilityDash { return; } - // Move caster + // Move caster (motionY left to gravity for skip arc) caster.motionX = dashDirection.xCoord * dashSpeed; - caster.motionY = 0; caster.motionZ = dashDirection.zCoord * dashSpeed; if (!isPreview()) { caster.velocityChanged = true; From 2387ece1ff1856e9f049c78b75021f7517dc0d4f Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 8 Feb 2026 01:32:18 -0500 Subject: [PATCH 16/76] Update Abilities to Support Player Casting (Part 1) --- .../controllers/data/ability/Ability.java | 12 ++ .../data/ability/type/AbilityBeam.java | 9 +- .../data/ability/type/AbilityCharge.java | 14 +- .../data/ability/type/AbilityDash.java | 5 +- .../data/ability/type/AbilityDisc.java | 9 +- .../data/ability/type/AbilityHazard.java | 4 +- .../data/ability/type/AbilityLaserShot.java | 5 + .../data/ability/type/AbilityOrb.java | 9 +- .../data/ability/type/AbilityProjectile.java | 195 +++++++++++++----- .../data/ability/type/AbilitySlam.java | 76 ++++--- .../data/ability/type/AbilitySweeper.java | 4 +- .../data/ability/type/AbilityTeleport.java | 24 +-- .../data/ability/type/AbilityTrap.java | 5 +- .../data/ability/type/AbilityVortex.java | 5 +- 14 files changed, 259 insertions(+), 117 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 49ffbf587..b95879c3b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -392,6 +392,18 @@ public abstract class Ability implements IAbility { return 45.0f; } + /** + * Returns true if the caster is a player (not an NPC). + * Use this instead of checking {@code target != null} to make NPC/Player + * code paths explicit and readable. + *

+ * NPCs always have an aggro target passed to ability methods. + * Players never do — they use look direction for aiming instead. + */ + protected final boolean isPlayerCaster(EntityLivingBase caster) { + return caster instanceof EntityPlayer; + } + /** * Returns true if this ability controls NPC movement during ACTIVE phase. * When true, AI pathfinding will be blocked during ability execution. diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 91b0287eb..f99a03528 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -164,6 +164,11 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } + /** + * Create beam entities. + * NPC: target is the aggro target — beams will home toward it. + * Player: target is null — beams fire in caster's look direction. + */ private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) { EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount]; float offsetDist = 1.0f; @@ -294,7 +299,9 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { @Override public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { + // NPC: telegraph on aggro target position + // Player: no telegraph (beam fires in look direction, no fixed position to mark) + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { return null; } 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 8e179dc73..4ae81bfcb 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 @@ -87,11 +87,13 @@ public class AbilityCharge extends Ability implements IAbilityCharge { } /** - * Locks the charge direction based on current target position. - * Called once at windup start - direction won't change even if target moves. + * Locks the charge direction. Called once at windup start — direction won't change even if target moves. + * NPC: charges toward aggro target. + * Player: charges in look direction. */ private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) { - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { + // NPC: charge toward aggro target double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; double len = Math.sqrt(dx * dx + dz * dz); @@ -102,6 +104,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); } } else { + // Player: charge in look direction float yaw = (float) Math.toRadians(caster.rotationYaw); chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); } @@ -258,9 +261,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return null; } - // Calculate direction to target at this moment (locked) + // NPC: telegraph points toward aggro target + // Player: telegraph points in look direction float yaw; - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); 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 2ea0095eb..0f8cbe374 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 @@ -149,9 +149,10 @@ public class AbilityDash extends Ability implements IAbilityDash { : DEFENSIVE_DIRECTIONS; chosenDirection = directions[RANDOM.nextInt(directions.length)]; - // Calculate dash direction relative to target + // NPC: dash direction is relative to aggro target facing + // Player: dash direction is relative to look direction float baseYaw; - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 22832a104..21d4073ed 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -169,6 +169,11 @@ public class AbilityDisc extends Ability implements IAbilityDisc { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } + /** + * Create disc entities. + * NPC: target is the aggro target — discs will home toward it. + * Player: target is null — discs fire in caster's look direction. + */ private EntityAbilityDisc[] createDiscEntities(EntityLivingBase caster, EntityLivingBase target, World world) { EntityAbilityDisc[] entities = new EntityAbilityDisc[projectileCount]; for (int i = 0; i < projectileCount; i++) { @@ -301,7 +306,9 @@ public class AbilityDisc extends Ability implements IAbilityDisc { @Override public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { + // NPC: telegraph on aggro target position + // Player: no telegraph (discs fire in look direction, no fixed position to mark) + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { return null; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 70696eb8f..58c2560a4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; @@ -111,6 +112,7 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.cooldownTicks = 0; this.windUpTicks = 30; this.telegraphType = TelegraphType.CIRCLE; + this.allowedBy = UserType.NPC_ONLY; } @Override @@ -202,14 +204,12 @@ public class AbilityHazard extends Ability implements IAbilityHazard { } break; case AT_TARGET: - // Use telegraph position if available, apply offset if (telegraph != null) { double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), minOffset, maxOffset, randomOffset, RANDOM); zoneX = pos[0]; zoneY = pos[1]; zoneZ = pos[2]; - // Update telegraph to show actual hazard position telegraph.setX(zoneX); telegraph.setY(zoneY); telegraph.setZ(zoneZ); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index 7ddfcc0e7..afffa9c13 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -88,6 +88,11 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { return laserWidth * 2.0f; // Make telegraph slightly wider for visibility } + /** + * Spawn laser entity. + * NPC: target is the aggro target — laser expands toward it. + * Player: target is null — laser expands in caster's look direction. + */ private EntityAbilityLaser spawnLaserEntity(EntityLivingBase caster, EntityLivingBase target, World world) { Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); EntityAbilityLaser entity = new EntityAbilityLaser( diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index e0f6bc19f..17b878305 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -172,6 +172,11 @@ public class AbilityOrb extends Ability implements IAbilityOrb { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } + /** + * Create orb entities. + * NPC: target is the aggro target — orbs will home toward it. + * Player: target is null — orbs fire in caster's look direction. + */ private EntityAbilityOrb[] createOrbEntities(EntityLivingBase caster, EntityLivingBase target, World world) { EntityAbilityOrb[] entities = new EntityAbilityOrb[projectileCount]; for (int i = 0; i < projectileCount; i++) { @@ -302,7 +307,9 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { + // NPC: telegraph on aggro target position + // Player: no telegraph (orbs fire in look direction, no fixed position to mark) + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { return null; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index b6657ac60..8abd5d01e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -9,6 +9,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.entity.EntityNPCInterface; @@ -67,68 +68,131 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if ((world.isRemote && !isPreview()) || target == null) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - if (!isPreview()) { - // Calculate direction to target - double dx = target.posX - caster.posX; - double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); - double dz = target.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (len > 0) { - dx /= len; - dy /= len; - dz /= len; - } - - // Deal instant damage with scripted event support - // TODO: Use custom EntityAbilityProjectile for actual tracking - applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); - - // Play sound - world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); - - // Handle splash damage for explosive projectiles - if (explosive && explosionRadius > 0) { - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity(target, - target.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); - - for (Entity entity : entities) { - if (entity instanceof EntityLivingBase && entity != caster) { - EntityLivingBase living = (EntityLivingBase) entity; - float dist = target.getDistanceToEntity(living); - if (dist < explosionRadius) { - float falloff = 1.0f - (dist / explosionRadius); - // Apply splash damage with scripted event support (no knockback) - applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); - } - } - } - - // Explosion particles - world.playSoundAtEntity(target, "random.explode", 0.5f, 1.0f); - for (int i = 0; i < 10; i++) { - world.spawnParticle("explode", - target.posX + (world.rand.nextDouble() - 0.5) * explosionRadius, - target.posY + world.rand.nextDouble() * target.height, - target.posZ + (world.rand.nextDouble() - 0.5) * explosionRadius, - 0, 0.1, 0); - } - } - - // Spawn projectile particles (visual trail) - spawnProjectileParticles(world, caster, target); + if (isPlayerCaster(caster)) { + // Player: instant hit-scan in look direction + executePlayerProjectile(caster, world); + } else if (target != null) { + // NPC: instant hit-scan on aggro target + executeNpcProjectile(caster, target, world); } - // Projectile is instant signalCompletion(); } + /** + * NPC projectile: instant hit-scan damage on the aggro target. + */ + private void executeNpcProjectile(EntityLivingBase caster, EntityLivingBase target, World world) { + if (isPreview()) return; + + double dx = target.posX - caster.posX; + double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); + double dz = target.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { dx /= len; dy /= len; dz /= len; } + + applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); + + if (explosive && explosionRadius > 0) { + applyExplosionDamage(caster, target, world, target.posX, target.posY, target.posZ); + } + + spawnProjectileParticles(world, caster, target); + } + + /** + * Player projectile: fires instant hit-scan in look direction. + * Raycasts for the first entity in range and applies damage. + */ + private void executePlayerProjectile(EntityLivingBase caster, World world) { + if (isPreview()) return; + + Vec3 look = caster.getLookVec(); + double eyeX = caster.posX; + double eyeY = caster.posY + caster.getEyeHeight(); + double eyeZ = caster.posZ; + + // Raycast: find the closest entity along look direction + EntityLivingBase hitTarget = null; + double closestDist = maxRange; + + @SuppressWarnings("unchecked") + List candidates = world.getEntitiesWithinAABBExcludingEntity(caster, + caster.boundingBox.expand(maxRange, maxRange, maxRange)); + + for (Entity entity : candidates) { + if (!(entity instanceof EntityLivingBase)) continue; + if (entity.isDead) continue; + + // Check if entity is roughly along look direction + double dx = entity.posX - eyeX; + double dy = (entity.posY + entity.height / 2) - eyeY; + double dz = entity.posZ - eyeZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (dist > maxRange || dist < 0.5) continue; + + // Dot product to check alignment with look vector + double dot = (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) / dist; + if (dot < 0.95) continue; // Must be within ~18 degree cone + + if (dist < closestDist) { + closestDist = dist; + hitTarget = (EntityLivingBase) entity; + } + } + + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); + + if (hitTarget != null) { + applyAbilityDamageWithDirection(caster, hitTarget, damage, knockback, look.xCoord, look.zCoord); + + if (explosive && explosionRadius > 0) { + applyExplosionDamage(caster, hitTarget, world, hitTarget.posX, hitTarget.posY, hitTarget.posZ); + } + + spawnProjectileParticles(world, caster, hitTarget); + } else { + // No hit — spawn particles along look direction anyway + spawnProjectileParticlesInDirection(world, caster, look); + } + } + + /** + * Apply explosion splash damage around a point. + */ + private void applyExplosionDamage(EntityLivingBase caster, EntityLivingBase primaryTarget, World world, + double x, double y, double z) { + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity(primaryTarget, + primaryTarget.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + + for (Entity entity : entities) { + if (entity instanceof EntityLivingBase && entity != caster) { + EntityLivingBase living = (EntityLivingBase) entity; + float dist = primaryTarget.getDistanceToEntity(living); + if (dist < explosionRadius) { + float falloff = 1.0f - (dist / explosionRadius); + applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); + } + } + } + + world.playSoundAtEntity(primaryTarget, "random.explode", 0.5f, 1.0f); + for (int i = 0; i < 10; i++) { + world.spawnParticle("explode", + x + (world.rand.nextDouble() - 0.5) * explosionRadius, + y + world.rand.nextDouble() * 2, + z + (world.rand.nextDouble() - 0.5) * explosionRadius, + 0, 0.1, 0); + } + } + private void spawnProjectileParticles(World world, EntityLivingBase caster, EntityLivingBase target) { double startX = caster.posX; double startY = caster.posY + caster.getEyeHeight(); @@ -160,6 +224,31 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } } + /** + * Spawn projectile particles along a direction (player miss — no entity hit). + */ + private void spawnProjectileParticlesInDirection(World world, EntityLivingBase caster, Vec3 look) { + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + + String particle = "flame"; + if (projectileType.equals("arrow")) { + particle = "crit"; + } else if (projectileType.equals("magic")) { + particle = "witchMagic"; + } + + int steps = (int) Math.max(5, maxRange * 2); + for (int i = 0; i < steps; i++) { + double progress = (double) i / steps * maxRange; + double px = startX + look.xCoord * progress; + double py = startY + look.yCoord * progress; + double pz = startZ + look.zCoord * progress; + world.spawnParticle(particle, px, py, pz, 0, 0, 0); + } + } + @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { // Projectile is instant, nothing to do per-tick 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 15b4060b8..a03ecdf6a 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 @@ -85,51 +85,74 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Update target position during windup - if (targetingMode == TargetingMode.AOE_SELF) { - // AOE_SELF: slam at caster's current position + if (isPlayerCaster(caster)) { + // Player: slam will launch from current position, no target tracking needed targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; - } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { - // AOE_TARGET: telegraph follows target via setEntityIdToFollow - targetX = target.posX; - targetY = target.posY; - targetZ = target.posZ; + } else { + // NPC: update target position during windup for telegraph tracking + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { + targetX = target.posX; + targetY = target.posY; + targetZ = target.posZ; + } } } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Lock in the destination at moment of launch + hasLaunched = false; + hasLanded = false; + airTicks = 0; + caster.fallDistance = 0; + + if (isPlayerCaster(caster)) { + executePlayerSlam(caster); + } else { + executeNpcSlam(caster, target); + } + } + + /** + * NPC slam: Lock destination based on targeting mode, then launch in a ballistic arc toward it. + */ + private void executeNpcSlam(EntityLivingBase caster, EntityLivingBase target) { if (targetingMode == TargetingMode.AOE_SELF) { - // AOE_SELF: slam in place (just jump up) targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { - // AOE_TARGET: leap to target's current position targetX = target.posX; targetY = target.posY; targetZ = target.posZ; } else { - // Fallback: slam in place targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; } - - hasLaunched = false; - hasLanded = false; - airTicks = 0; - - // Reset fall distance to prevent fall damage during slam - caster.fallDistance = 0; - - // Calculate and apply leap velocity launchTowardTarget(caster); } + /** + * Player slam: Launch straight up. Player controls horizontal movement via WASD. + * AOE damage triggers wherever the player lands. + */ + private void executePlayerSlam(EntityLivingBase caster) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + + double vy = calculateLaunchVelocity(Math.max(1.0, leapHeight)); + caster.motionY = vy; + hasLaunched = true; + caster.velocityChanged = true; + } + /** * Calculate the initial vertical velocity needed to reach a target height * in Minecraft's physics (gravity=0.08, vertical drag=0.98). @@ -273,8 +296,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { return; } - // While in air, face toward target - if (!isPreview()) { + // NPC: face toward target destination while in air + // Player: free look — player controls their own camera + if (!isPreview() && !isPlayerCaster(caster)) { double dx = targetX - caster.posX; double dz = targetZ - caster.posZ; float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); @@ -441,11 +465,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { TelegraphInstance instance = new TelegraphInstance(telegraph, targetX, groundY, targetZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); - // AOE_TARGET: telegraph follows target during windup - if (targetingMode == TargetingMode.AOE_TARGET && target != null) { + // NPC AOE_TARGET: telegraph follows target during windup + // Player: telegraph stays at caster position (no target to follow) + if (!isPlayerCaster(caster) && targetingMode == TargetingMode.AOE_TARGET && target != null) { instance.setEntityIdToFollow(target.getEntityId()); } - // AOE_SELF: telegraph stays at caster position, no follow return instance; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 9be02101f..8638dd2a4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -83,7 +83,9 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { return; } - // Spawn the entity that handles BOTH visuals AND damage + // Spawn the sweeper entity that handles BOTH visuals AND damage. + // NPC: target is the aggro target — lockOnTarget tracks it during sweep. + // Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect. activeEntity = new EntityAbilitySweeper(world, caster, target, beamLength, beamWidth, beamHeight, colorData, diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index fe847bf3a..8e09c43e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -72,6 +73,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.typeId = "ability.cnpc.teleport"; this.name = "Teleport"; this.targetingMode = TargetingMode.AGGRO_TARGET; + this.allowedBy = UserType.NPC_ONLY; this.maxRange = 30.0f; this.minRange = 5.0f; this.cooldownTicks = 0; @@ -228,26 +230,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } } - // No target (player use) - teleport in caster's look direction - Vec3 look = caster.getLookVec(); - switch (mode) { - case BEHIND: - // Teleport forward in look direction by behindDistance - newX = caster.posX + look.xCoord * behindDistance; - newZ = caster.posZ + look.zCoord * behindDistance; - newY = caster.posY; - return Vec3.createVectorHelper(newX, newY, newZ); - case SINGLE: - case BLINK: - default: - // Teleport forward in look direction within blinkRadius - double dist = Math.min(blinkRadius, maxRange); - double offset = (RANDOM.nextDouble() * 0.5 + 0.5) * dist; // 50-100% of max distance - newX = caster.posX + look.xCoord * offset; - newZ = caster.posZ + look.zCoord * offset; - newY = caster.posY; - return Vec3.createVectorHelper(newX, newY, newZ); - } + // NPC-only ability — should not reach here + return null; } private Vec3 findSafeDestination(World world, double oldX, double oldY, double oldZ, diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 5a540d634..494192e04 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; @@ -83,6 +84,7 @@ public class AbilityTrap extends Ability implements IAbilityTrap { this.cooldownTicks = 0; this.windUpTicks = 20; this.telegraphType = TelegraphType.CIRCLE; + this.allowedBy = UserType.NPC_ONLY; } @Override @@ -128,7 +130,6 @@ public class AbilityTrap extends Ability implements IAbilityTrap { } break; case AT_TARGET: - // Telegraph follows target during windup, locks on execute if (target != null) { instance.setEntityIdToFollow(target.getEntityId()); } @@ -154,14 +155,12 @@ public class AbilityTrap extends Ability implements IAbilityTrap { trapZ = caster.posZ; break; case AT_TARGET: - // Use telegraph position with offset if (telegraph != null) { double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), minOffset, maxOffset, randomOffset, RANDOM); trapX = pos[0]; trapY = pos[1]; trapZ = pos[2]; - // Update telegraph to show actual trap position telegraph.setX(trapX); telegraph.setY(trapY); telegraph.setZ(trapZ); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index 73f9816f7..90aaf054b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -103,8 +103,9 @@ public class AbilityVortex extends Ability implements IAbilityVortex { } } } else { - // Single target mode - still check pullRadius - if (target != null && !target.isDead) { + // NPC single-target mode: pull the aggro target + // Player: single-target mode has no effect (no target to pull — use AOE mode instead) + if (!isPlayerCaster(caster) && target != null && !target.isDead) { double dist = caster.getDistanceToEntity(target); if (dist <= pullRadius) { getPulledEntities().add(target.getUniqueID()); From d76f5d40a4eb8e30c0961086572e1aed90c24df5 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 8 Feb 2026 01:46:13 -0500 Subject: [PATCH 17/76] Prevent Passive Factions from taking Damage --- .../noppes/npcs/client/gui/global/GuiNPCManageFactions.java | 2 ++ src/main/java/noppes/npcs/entity/EntityNPCInterface.java | 3 +++ src/main/resources/assets/customnpcs/lang/en_US.lang | 4 +++- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java index 246e528f3..59adbdd91 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java @@ -85,11 +85,13 @@ public class GuiNPCManageFactions extends GuiNPCInterface2 implements IScrollDat addLabel(new GuiNpcLabel(3, "faction.hidden", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(3, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.hideFaction ? 1 : 0)); + getButton(3).setHoverText("faction.hidden.hover"); y += 23; addLabel(new GuiNpcLabel(4, "faction.attacked", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(4, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.getsAttacked ? 1 : 0)); + getButton(4).setHoverText("faction.attacked.hover"); y += 23; diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index faaa2c9f5..6e4b40884 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -678,6 +678,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti if (entity instanceof EntityLivingBase) attackingEntity = (EntityLivingBase) entity; + if (faction.isPassive) + return false; + if (attackingEntity != null && attackingEntity == getOwner()) return false; else if (attackingEntity instanceof EntityNPCInterface) { diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 3238d2851..3bc0fa119 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -639,6 +639,7 @@ faction.friendly=Friendly faction.points=Points faction.ondeath=On death faction.hidden=Hidden +faction.hidden.hover=Hides this faction from the player's faction standings UI faction.default=Default faction.attackHostile=Attack hostile factions faction.defend=Defence faction members @@ -647,8 +648,9 @@ faction.options=Faction Options faction.increasepoints=Faction %s increased by %s points faction.decreasepoints=Faction %s decreased by %s points faction.attacked=Attacked by mobs +faction.attacked.hover=Whether vanilla mobs will target and attack NPCs in this faction faction.passive=Is Passive -faction.passive.hover=Passive factions will not queue any attacking tasks [Good for Performance] +faction.passive.hover=Passive faction NPCs cannot be damaged and will not queue any attacking tasks [Good for Performance] menu.inventory=Inventory menu.display=Display From 974cfc8c568ccfe685931a6b3291ea2871ffb9e1 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 10:59:42 -0300 Subject: [PATCH 18/76] Changed fire delay for dual disc --- .../data/ability/type/AbilityDisc.java | 2 +- .../animations/Ability_DiscDual_Active.json | 256 +++++------------ .../animations/Ability_DiscDual_Windup.json | 264 +++++++++--------- 3 files changed, 198 insertions(+), 324 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 21d4073ed..f890b7d7b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -138,7 +138,7 @@ public class AbilityDisc extends Ability implements IAbilityDisc { AbilityDisc disc = (AbilityDisc) a; a.setName("Dual Disc"); disc.setProjectileCount(2); - disc.setFireDelay(10); + disc.setFireDelay(5); // Set color override for second disc disc.projectiles[1].colorOverride = true; disc.projectiles[1].innerColor = 0xFFFFFF; diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json index 8fbaa73da..98a3299a2 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json @@ -1,17 +1,17 @@ { - "Loop": 5, + "Loop": -1, "Speed": 1.0f, "Frames": [ { "ColorMarker": 16777215, "Comment": "", - "Speed": 2.0f, + "Speed": 3.0f, "FrameParts": [ { - "Pivot2": -5.0f, - "Part": "BODY", - "Rotation1": -37.0f, - "Rotation0": 37.0f, + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, "Pivot0": 3.0f, "Pivot1": 2.0f, "Rotation2": 0.0f @@ -25,15 +25,6 @@ "Pivot1": 2.0f, "Rotation2": 56.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -37.0f, - "Rotation0": 31.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -25.0f - }, { "Pivot2": 0.0f, "Part": "LEFT_ARM", @@ -43,33 +34,6 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, - { - "Pivot2": -1.0f, - "Part": "RIGHT_LEG", - "Rotation1": -18.0f, - "Rotation0": 12.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 2 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 1.5f, - "FrameParts": [ { "Pivot2": -5.0f, "Part": "BODY", @@ -79,33 +43,6 @@ "Pivot1": 2.0f, "Rotation2": 0.0f }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 56.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -37.0f, - "Rotation0": 31.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -25.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": 120.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, { "Pivot2": -1.0f, "Part": "RIGHT_LEG", @@ -115,42 +52,6 @@ "Pivot1": 0.0f, "Rotation2": 0.0f }, - { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 4 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.5f, - "FrameParts": [ - { - "Pivot2": -5.0f, - "Part": "BODY", - "Rotation1": -37.0f, - "Rotation0": 37.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 56.0f - }, { "Pivot2": 0.0f, "Part": "LEFT_LEG", @@ -159,37 +60,10 @@ "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": -25.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": 120.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "RIGHT_LEG", - "Rotation1": -18.0f, - "Rotation0": 12.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f } ], "Smooth": 0b, - "Duration": 4 + "Duration": 3 }, { "ColorMarker": 16777215, @@ -198,8 +72,8 @@ "FrameParts": [ { "Pivot2": 2.0f, - "Part": "BODY", - "Rotation1": -25.0f, + "Part": "HEAD", + "Rotation1": 0.0f, "Rotation0": -12.0f, "Pivot0": -1.0f, "Pivot1": 1.0f, @@ -214,15 +88,6 @@ "Pivot1": 0.0f, "Rotation2": 75.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -25.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": 2.0f, "Part": "LEFT_ARM", @@ -232,6 +97,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", @@ -242,17 +116,17 @@ "Rotation2": 6.0f }, { - "Pivot2": 2.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f } ], "Smooth": 0b, - "Duration": 2 + "Duration": 3 }, { "ColorMarker": 16777215, @@ -261,8 +135,8 @@ "FrameParts": [ { "Pivot2": 2.0f, - "Part": "BODY", - "Rotation1": -25.0f, + "Part": "HEAD", + "Rotation1": 0.0f, "Rotation0": -12.0f, "Pivot0": -1.0f, "Pivot1": 1.0f, @@ -277,15 +151,6 @@ "Pivot1": 0.0f, "Rotation2": 75.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -25.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": 2.0f, "Part": "LEFT_ARM", @@ -295,6 +160,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", @@ -305,27 +179,27 @@ "Rotation2": 6.0f }, { - "Pivot2": 2.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f } ], "Smooth": 0b, - "Duration": 4 + "Duration": 3 }, { "ColorMarker": 16777215, "Comment": "", - "Speed": 0.5f, + "Speed": 0.25f, "FrameParts": [ { "Pivot2": 2.0f, - "Part": "BODY", - "Rotation1": -25.0f, + "Part": "HEAD", + "Rotation1": 0.0f, "Rotation0": -12.0f, "Pivot0": -1.0f, "Pivot1": 1.0f, @@ -340,15 +214,6 @@ "Pivot1": 0.0f, "Rotation2": 75.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -25.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": 2.0f, "Part": "LEFT_ARM", @@ -358,6 +223,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", @@ -368,17 +242,17 @@ "Rotation2": 6.0f }, { - "Pivot2": 2.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f } ], "Smooth": 0b, - "Duration": 4 + "Duration": 3 } ], "CurrentFrameTime": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json index 080306c95..0dc050b19 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json @@ -7,51 +7,6 @@ "Comment": "", "Speed": 0.5f, "FrameParts": [ - { - "Pivot2": -8.0f, - "Part": "BODY", - "Rotation1": 25.0f, - "Rotation0": 31.0f, - "Pivot0": -2.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -5.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 50.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -2.0f, - "Part": "LEFT_LEG", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -31.0f - }, - { - "Pivot2": -8.0f, - "Part": "LEFT_ARM", - "Rotation1": 31.0f, - "Rotation0": -56.0f, - "Pivot0": -2.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -3.0f, - "Part": "RIGHT_LEG", - "Rotation1": 25.0f, - "Rotation0": 18.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, { "Pivot2": 0.0f, "Part": "FULL_MODEL", @@ -69,6 +24,51 @@ "Pivot0": -2.0f, "Pivot1": 2.0f, "Rotation2": -12.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "LEFT_ARM", + "Rotation1": 31.0f, + "Rotation0": -56.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "BODY", + "Rotation1": 25.0f, + "Rotation0": 31.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_LEG", + "Rotation1": 25.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -31.0f } ], "Smooth": 0b, @@ -79,51 +79,6 @@ "Comment": "", "Speed": 0.35f, "FrameParts": [ - { - "Pivot2": 0.0f, - "Part": "BODY", - "Rotation1": 50.0f, - "Rotation0": -6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 5.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 50.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": 170.0f - }, - { - "Pivot2": -3.0f, - "Part": "LEFT_ARM", - "Rotation1": 75.0f, - "Rotation0": -107.0f, - "Pivot0": -6.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -6.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": 50.0f, - "Rotation0": 18.0f, - "Pivot0": -3.0f, - "Pivot1": -4.0f, - "Rotation2": 0.0f - }, { "Pivot2": 0.0f, "Part": "FULL_MODEL", @@ -141,6 +96,51 @@ "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 170.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -107.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 50.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": -4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f } ], "Smooth": 0b, @@ -153,9 +153,18 @@ "FrameParts": [ { "Pivot2": 0.0f, - "Part": "BODY", - "Rotation1": 50.0f, - "Rotation0": -6.0f, + "Part": "FULL_MODEL", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f @@ -179,10 +188,10 @@ "Rotation2": 0.0f }, { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -6.0f, - "Rotation0": 12.0f, + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -6.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f @@ -197,19 +206,10 @@ "Rotation2": 0.0f }, { - "Pivot2": 0.0f, - "Part": "FULL_MODEL", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 12.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f @@ -221,13 +221,13 @@ { "ColorMarker": 16777215, "Comment": "", - "Speed": 2.0f, + "Speed": 3.0f, "FrameParts": [ { - "Pivot2": -5.0f, - "Part": "BODY", - "Rotation1": -37.0f, - "Rotation0": 37.0f, + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, "Pivot0": 3.0f, "Pivot1": 2.0f, "Rotation2": 0.0f @@ -241,15 +241,6 @@ "Pivot1": 2.0f, "Rotation2": 56.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -37.0f, - "Rotation0": 31.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -25.0f - }, { "Pivot2": 0.0f, "Part": "LEFT_ARM", @@ -259,6 +250,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": -37.0f, + "Rotation0": 37.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, { "Pivot2": -1.0f, "Part": "RIGHT_LEG", @@ -269,13 +269,13 @@ "Rotation2": 0.0f }, { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -37.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -25.0f } ], "Smooth": 0b, @@ -283,7 +283,7 @@ } ], "CurrentFrameTime": 0, - "CurrentFrame": 1, + "CurrentFrame": 3, "Smooth": 0b, "ID": 17, "WhileAttacking": 1b, From 91762bb1bacc13b7a7ee390cff9ab9b28d5eeb84 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 11:28:00 -0300 Subject: [PATCH 19/76] Hazard animation --- .../data/ability/type/AbilityHazard.java | 2 + .../animations/Ability_Hazard_Active.json | 266 ++++++++++++ .../animations/Ability_Hazard_Windup.json | 392 ++++++++++++++++++ 3 files changed, 660 insertions(+) create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 58c2560a4..f1ae7e719 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -113,6 +113,8 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.windUpTicks = 30; this.telegraphType = TelegraphType.CIRCLE; this.allowedBy = UserType.NPC_ONLY; + this.windUpAnimationName = "Ability_Hazard_Windup"; + this.activeAnimationName = "Ability_Hazard_Active"; } @Override diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json new file mode 100644 index 000000000..11cb0ef7a --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json @@ -0,0 +1,266 @@ +{ + "Loop": 3, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -12.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -10.0f, + "Part": "LEFT_ARM", + "Rotation1": 6.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -11.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 101.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -10.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -37.0f, + "Pivot0": -2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -37.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 24, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Hazard_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json new file mode 100644 index 000000000..8a16135a4 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json @@ -0,0 +1,392 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -37.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -37.0f, + "Rotation0": -37.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.75f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -12.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -10.0f, + "Part": "LEFT_ARM", + "Rotation1": 6.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -11.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 101.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -10.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 5, + "Smooth": 0b, + "ID": 23, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Hazard_Windup", + "WhileStanding": 1b +} From eee9b32a5b2a5c32ad44a54a20586b072118c8ce Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 12:14:21 -0300 Subject: [PATCH 20/76] Added eye anchor point using the entity's eye height --- .../kamkeel/npcs/controllers/data/ability/AnchorPoint.java | 4 +++- src/main/java/kamkeel/npcs/util/AnchorPointHelper.java | 7 +++++++ src/main/resources/assets/customnpcs/lang/en_US.lang | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java index 1c308493c..58e54b5aa 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java @@ -10,7 +10,8 @@ public enum AnchorPoint { RIGHT_HAND("Right Hand"), // Right arm/hand position LEFT_HAND("Left Hand"), // Left arm/hand position ABOVE_HEAD("Above Head"), // Above the entity - CHEST("Chest"); // Chest level, centered + CHEST("Chest"), // Chest level, centered + EYE("Eye"); // Eye level, centered private final String displayName; @@ -55,6 +56,7 @@ public enum AnchorPoint { case LEFT_HAND: return "ability.anchor.leftHand"; case ABOVE_HEAD: return "ability.anchor.aboveHead"; case CHEST: return "ability.anchor.chest"; + case EYE: return "ability.anchor.eye"; default: return name(); } } diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index 5ee5936b1..20d557bef 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -37,6 +37,7 @@ public class AnchorPointHelper { private static final float ARM_HEIGHT = 0.75f; private static final float ABOVE_HEAD_HEIGHT = 1.2f; private static final float CHEST_HEIGHT = 0.65f; + private static final float EYE_HEIGHT = 0.85f; // Distance in front for FRONT anchor private static final float DEFAULT_FRONT_DISTANCE = 1.0f; @@ -98,6 +99,10 @@ public class AnchorPointHelper { case CHEST: y += height * CHEST_HEIGHT; break; + + case EYE: + y += entity.getEyeHeight(); + break; } // Rotate offsets relative to entity's body yaw @@ -347,6 +352,8 @@ public class AnchorPointHelper { return ABOVE_HEAD_HEIGHT; case CHEST: return CHEST_HEIGHT; + case EYE: + return EYE_HEIGHT; default: return FRONT_HEIGHT; } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 3bc0fa119..9319f1b36 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1549,6 +1549,7 @@ ability.anchor.rightHand=Right Hand ability.anchor.leftHand=Left Hand ability.anchor.aboveHead=Above Head ability.anchor.chest=Chest +ability.anchor.eye=Eye # Sweep Mode ability.sweep.swipe=Swipe From 0dc6f9aab30fe3b2a4e53f8346cfb64387ece2fc Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 12:38:13 -0300 Subject: [PATCH 21/76] Orb Barrage animation --- .../data/ability/type/AbilityOrb.java | 6 +- .../animations/Ability_OrbBarrage_Active.json | 203 ++++++++++++++++++ .../animations/Ability_OrbBarrage_Windup.json | 201 +++++++++++++++++ 3 files changed, 407 insertions(+), 3 deletions(-) create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 17b878305..c4a4a1ebb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -143,11 +143,11 @@ public class AbilityOrb extends Ability implements IAbilityOrb { a.setMaxRange(75.0f); a.setBurstEnabled(true); a.setBurstAmount(15); - a.setBurstDelay(10); + a.setBurstDelay(5); a.setBurstReplayAnimations(false); a.setBurstOverlap(true); - a.setWindUpAnimationName("Ability_BeamDual_Windup"); - a.setActiveAnimationName("Ability_BeamDual_Active"); + a.setWindUpAnimationName("Ability_OrbBarrage_Windup"); + a.setActiveAnimationName("Ability_OrbBarrage_Active"); }) ); } diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json new file mode 100644 index 000000000..0a0ba828c --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json @@ -0,0 +1,203 @@ +{ + "Loop": 1, + "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 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 26, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbBarrage_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json new file mode 100644 index 000000000..dfe8f601b --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json @@ -0,0 +1,201 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.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 + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + } + ], + "Duration": 8 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.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 + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 19 + }, + { + "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": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 2, + "Smooth": 0b, + "ID": 25, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbBarrage_Windup", + "WhileStanding": 1b +} From 171578ad9b3b8c8f974424d7555ab2c0a8505074 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 12:52:58 -0300 Subject: [PATCH 22/76] Fixed heavy hit animation --- .../animations/Ability_HeavyHit_Windup.json | 1181 +---------------- 1 file changed, 55 insertions(+), 1126 deletions(-) diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json index 15d49bce6..a276742ba 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json @@ -7,24 +7,6 @@ "Comment": "", "Speed": 0.8f, "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 31.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": -1.0f, "Part": "HEAD", @@ -34,15 +16,6 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 6.0f - }, { "Pivot2": -1.0f, "Part": "BODY", @@ -60,24 +33,6 @@ "Pivot0": 0.0f, "Pivot1": 1.0f, "Rotation2": 6.0f - } - ], - "Smooth": 0b, - "Duration": 10 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f }, { "Pivot2": -4.0f, @@ -86,16 +41,16 @@ "Rotation0": 31.0f, "Pivot0": 2.0f, "Pivot1": 0.0f, - "Rotation2": -18.0f + "Rotation2": -12.0f }, { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 31.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, "Pivot1": 1.0f, - "Rotation2": -6.0f + "Rotation2": -37.0f }, { "Pivot2": -2.0f, @@ -104,7 +59,25 @@ "Rotation0": 25.0f, "Pivot0": -2.0f, "Pivot1": -1.0f, - "Rotation2": 0.0f + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 13 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f }, { "Pivot2": -1.0f, @@ -123,24 +96,6 @@ "Pivot0": 0.0f, "Pivot1": 1.0f, "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f }, { "Pivot2": -4.0f, @@ -151,51 +106,6 @@ "Pivot1": 0.0f, "Rotation2": -18.0f }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ { "Pivot2": 3.0f, "Part": "RIGHT_ARM", @@ -205,24 +115,6 @@ "Pivot1": 1.0f, "Rotation2": -37.0f }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, { "Pivot2": -2.0f, "Part": "RIGHT_LEG", @@ -231,997 +123,16 @@ "Pivot0": -2.0f, "Pivot1": -1.0f, "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f } ], "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 + "Duration": 15 }, { "ColorMarker": 16777215, "Comment": "", "Speed": 2.0f, "FrameParts": [ - { - "Pivot2": -5.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 90.0f - }, - { - "Pivot2": 2.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 1.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, { "Pivot2": 0.0f, "Part": "HEAD", @@ -1231,15 +142,6 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 6.0f, - "Rotation0": 12.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, { "Pivot2": 0.0f, "Part": "BODY", @@ -1257,6 +159,33 @@ "Pivot0": -2.0f, "Pivot1": 1.0f, "Rotation2": -6.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f } ], "Smooth": 0b, @@ -1264,7 +193,7 @@ } ], "CurrentFrameTime": 0, - "CurrentFrame": 19, + "CurrentFrame": 1, "Smooth": 0b, "ID": 15, "WhileAttacking": 1b, From cac27535f877d1fd2540419766ab103181e12353 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 13:03:57 -0300 Subject: [PATCH 23/76] Charge animation --- .../data/ability/type/AbilityCharge.java | 2 + .../animations/Ability_Charge_Active.json | 59 +++++++++ .../animations/Ability_Charge_Windup.json | 122 ++++++++++++++++++ 3 files changed, 183 insertions(+) create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json 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 4ae81bfcb..2a0a5ff8c 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 @@ -56,6 +56,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { this.showTelegraph = true; this.windUpSound = "mob.zombie.wood"; this.activeSound = "mob.zombie.attack"; + this.windUpAnimationName = "Ability_Charge_Windup"; + this.activeAnimationName = "Ability_Active_Windup"; } @Override diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json new file mode 100644 index 000000000..82b2294ca --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json @@ -0,0 +1,59 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 45.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 28, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Charge_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json new file mode 100644 index 000000000..c627007e3 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json @@ -0,0 +1,122 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 44.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -10.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -10.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 75.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 18 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 45.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 27, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Charge_Windup", + "WhileStanding": 1b +} From 540903d71fb3a071896e5c8546c43a95c13bb155 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 13:24:28 -0300 Subject: [PATCH 24/76] Changed Abilities register method call --- src/main/java/kamkeel/npcs/util/Register.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index ff6b0f24e..c343a9f03 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -69,7 +69,7 @@ public class Register { public void register() { for (Map.Entry> entry : entries.entrySet()) { - AbilityController.Instance.registerType(entry.getValue().get().getTypeId(), entry.getValue()); + AbilityController.Instance.registerAbility(entry.getKey(), entry.getValue().get()); } } From 8a3b0b98662ecfa25a4d99f1b6c498642abdfbe8 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 13:48:15 -0300 Subject: [PATCH 25/76] why... --- src/main/java/kamkeel/npcs/util/Register.java | 43 +++++-------------- 1 file changed, 11 insertions(+), 32 deletions(-) diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index c343a9f03..af944ed59 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -12,7 +12,7 @@ import java.util.function.Supplier; public class Register { public static final Map> REGISTERED_NAMESPACES = new LinkedHashMap<>(); public static final Map NAMESPACE_DISPLAY_NAMES = new LinkedHashMap<>(); - private final String registryKey; + protected final String registryKey; protected final String namespace; protected final Map> entries = new LinkedHashMap<>(); @@ -35,45 +35,24 @@ public class Register { return false; } - public List catalogue() { - List list = new ArrayList<>(); - for (String regKey : REGISTERED_NAMESPACES.keySet()) { - List nameSp = REGISTERED_NAMESPACES.get(regKey); - for (String name : nameSp) { - List nameSpContent = catalogue(regKey, name); - list.addAll(nameSpContent); - } - } - - return list; - } - - public List catalogue(String namespace) { - return catalogue(registryKey, namespace); - } - - public List catalogue(String registryKey, String namespace) { - List list = new ArrayList<>(); - for (Map.Entry> entry : entries.entrySet()) { - if (entry.getKey().startsWith(registryKey + "." + namespace + ":")) - list.add(entry.getValue().get()); - } - - return list; - } - - public static class Abilities extends Register { + public static class Abilities extends Register { private Abilities(String namespace) { super("ability", namespace); } + @Override + public T register(String factoryName, Supplier factory) { + entries.put(registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"), factory); + return factory.get(); + } + public void register() { - for (Map.Entry> entry : entries.entrySet()) { + for (Map.Entry> entry : entries.entrySet()) { AbilityController.Instance.registerAbility(entry.getKey(), entry.getValue().get()); } } - public static Register.Abilities create(String namespace, String displayName) { + public static Register.Abilities create(String namespace, String displayName) { if (!REGISTERED_NAMESPACES.containsKey("ability")) REGISTERED_NAMESPACES.put("ability", new ArrayList<>()); @@ -84,7 +63,7 @@ public class Register { REGISTERED_NAMESPACES.get("ability").add(namespace); NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); - return new Register.Abilities(namespace); + return new Register.Abilities<>(namespace); } } From c2c571ae7ea9b4d393da62cbed264c474b28ad53 Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 14:02:00 -0300 Subject: [PATCH 26/76] Hotfix --- src/main/java/kamkeel/npcs/util/Register.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index af944ed59..8c27ba57a 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -35,24 +35,24 @@ public class Register { return false; } - public static class Abilities extends Register { + public static class Abilities extends Register { private Abilities(String namespace) { super("ability", namespace); } @Override - public T register(String factoryName, Supplier factory) { + public Ability register(String factoryName, Supplier factory) { entries.put(registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"), factory); return factory.get(); } public void register() { - for (Map.Entry> entry : entries.entrySet()) { + for (Map.Entry> entry : entries.entrySet()) { AbilityController.Instance.registerAbility(entry.getKey(), entry.getValue().get()); } } - public static Register.Abilities create(String namespace, String displayName) { + public static Register.Abilities create(String namespace, String displayName) { if (!REGISTERED_NAMESPACES.containsKey("ability")) REGISTERED_NAMESPACES.put("ability", new ArrayList<>()); @@ -63,7 +63,7 @@ public class Register { REGISTERED_NAMESPACES.get("ability").add(namespace); NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); - return new Register.Abilities<>(namespace); + return new Register.Abilities(namespace); } } From 70ed5a07174bd277f939c807fd9900253c4f08eb Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 14:13:37 -0300 Subject: [PATCH 27/76] =?UTF-8?q?Hotfix=C2=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/kamkeel/npcs/util/Register.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index 8c27ba57a..db6802f34 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -36,19 +36,23 @@ public class Register { } public static class Abilities extends Register { + protected final Map uniqueNames = new LinkedHashMap<>(); + private Abilities(String namespace) { super("ability", namespace); } @Override public Ability register(String factoryName, Supplier factory) { - entries.put(registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"), factory); + String name = registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"); + entries.put(name, factory); + uniqueNames.put(name, factoryName); return factory.get(); } public void register() { for (Map.Entry> entry : entries.entrySet()) { - AbilityController.Instance.registerAbility(entry.getKey(), entry.getValue().get()); + AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get()); } } From 3500b0f55f1a1792c6aa298ea61cdbd5a8269099 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 13:55:56 -0500 Subject: [PATCH 28/76] Ability Trap & Hazard Update --- src/api | 2 +- .../client/renderer/RenderAbilityZone.java | 754 ++++++++++++++ .../lightning/AttachedLightningRenderer.java | 33 + .../data/ability/type/AbilityHazard.java | 599 ++--------- .../data/ability/type/AbilityTrap.java | 487 ++------- .../data/ability/type/AbilityZone.java | 554 +++++++++++ .../npcs/entity/EntityAbilityZone.java | 928 ++++++++++++++++++ src/main/java/noppes/npcs/CustomNpcs.java | 2 + .../java/noppes/npcs/client/ClientProxy.java | 3 + .../java/noppes/npcs/client/fx/CustomFX.java | 4 + .../noppes/npcs/client/fx/ZoneParticleFX.java | 65 ++ .../npcs/client/renderer/ImageData.java | 2 +- .../assets/customnpcs/lang/en_US.lang | 57 +- 13 files changed, 2561 insertions(+), 929 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java create mode 100644 src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java create mode 100644 src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java diff --git a/src/api b/src/api index fd4c77d01..092b18fe9 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit fd4c77d015add1f6f3012a1681561b2774f2f997 +Subproject commit 092b18fe95d57353d16960411e5289ac3bbfa6ef diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java new file mode 100644 index 000000000..6c555aca8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java @@ -0,0 +1,754 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle; +import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneType; +import noppes.npcs.client.fx.CustomFX; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.Render; +import net.minecraft.entity.Entity; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.fx.ZoneParticleFX; +import org.lwjgl.opengl.GL11; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +/** + * Renders zone effects for Trap and Hazard abilities. + * Supports CIRCLE and SQUARE shapes with composable visual layers. + */ +@SideOnly(Side.CLIENT) +public class RenderAbilityZone extends Render { + + private static final int CIRCLE_SEGMENTS = 32; + private static final int ACCENT_LINE_COUNT = 12; + private static final Random RANDOM = new Random(); + + // Track last particle spawn tick per entity to avoid duplicate spawns + private final Map lastParticleTick = new HashMap<>(); + + // Persistent lightning state + private final Map lightningStates = new HashMap<>(); + + // ═══════════════════════════════════════════════════════════════════ + // RENDER CONTEXT + // ═══════════════════════════════════════════════════════════════════ + + private static class Ctx { + EntityAbilityZone zone; + ZoneShape shape; + float radius, height; + float ir, ig, ib; // inner color + float outerR, outerG, outerB; + boolean outerEnabled; + float time, pulse, rotation, brightness; + boolean flash, newTick; + float particleDensity, particleScale, animSpeed, lightningDensity; + // Visual layer fields (always populated) + boolean groundFill, rings, border, accents, lightning, particles; + float groundAlpha, borderSpeed; + int ringCount, accentStyle, particleMotion, particleSize; + boolean particleGlow; + String particleDir; + } + + // ═══════════════════════════════════════════════════════════════════ + // MAIN RENDER + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + EntityAbilityZone zone = (EntityAbilityZone) entity; + + // Build context + Ctx c = new Ctx(); + c.zone = zone; + c.shape = zone.getShape(); + c.radius = zone.getRadius(); + c.height = zone.getZoneHeight(); + + int inner = zone.getInnerColor(); + c.ir = ((inner >> 16) & 0xFF) / 255.0f; + c.ig = ((inner >> 8) & 0xFF) / 255.0f; + c.ib = (inner & 0xFF) / 255.0f; + + int outer = zone.getOuterColor(); + c.outerR = ((outer >> 16) & 0xFF) / 255.0f; + c.outerG = ((outer >> 8) & 0xFF) / 255.0f; + c.outerB = (outer & 0xFF) / 255.0f; + c.outerEnabled = zone.isOuterColorEnabled(); + + c.particleDensity = zone.getParticleDensity(); + c.particleScale = zone.getParticleScale(); + c.animSpeed = zone.getAnimSpeed(); + c.lightningDensity = zone.getLightningDensity(); + + // Visual layer fields — always populated + c.groundFill = zone.isGroundFill(); + c.groundAlpha = zone.getGroundAlpha(); + c.rings = zone.isRings(); + c.ringCount = zone.getRingCount(); + c.border = zone.isBorder(); + c.borderSpeed = zone.getBorderSpeed(); + c.accents = zone.isAccents(); + c.accentStyle = zone.getAccentStyle(); + c.lightning = zone.isLightning(); + c.particles = zone.isParticles(); + c.particleMotion = zone.getParticleMotion(); + c.particleDir = zone.getParticleDir(); + c.particleSize = zone.getParticleSize(); + c.particleGlow = zone.isParticleGlow(); + + c.time = zone.ticksExisted + partialTicks; + c.pulse = c.time * 0.1f * c.animSpeed; + c.rotation = c.time * 1.5f * c.animSpeed; + + c.brightness = 1.0f; + if (zone.getZoneType() == ZoneType.TRAP) { + if (!zone.isArmed()) { + c.brightness = 0.4f; + } else { + c.pulse = c.time * 0.2f; + } + } + + c.flash = zone.getTriggerFlashTick() >= 0 + && zone.ticksExisted - zone.getTriggerFlashTick() < 4; + + c.newTick = isNewTick(zone); + + // Render + setupRenderState(); + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + GL11.glDepthMask(false); + + renderZone(c); + + GL11.glDepthMask(true); + GL11.glPopMatrix(); + restoreRenderState(); + } + + private boolean isNewTick(EntityAbilityZone zone) { + int id = zone.getEntityId(); + int tick = zone.ticksExisted; + Integer last = lastParticleTick.get(id); + if (last == null || last != tick) { + lastParticleTick.put(id, tick); + return true; + } + return false; + } + + private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityZone zone) { + int id = zone.getEntityId(); + AttachedLightningRenderer.LightningState state = lightningStates.get(id); + if (state == null) { + state = new AttachedLightningRenderer.LightningState(); + lightningStates.put(id, state); + } + return state; + } + + // ═══════════════════════════════════════════════════════════════════ + // UNIFIED RENDER — Composable visual layers + // ═══════════════════════════════════════════════════════════════════ + + private void renderZone(Ctx c) { + float rR = ringR(c), rG = ringG(c), rB = ringB(c); + + // 1. Ground fill + if (c.groundFill) { + if (c.flash) { + renderShapeFill(c.shape, c.radius, 1, 1, 1, 0.5f); + } else { + renderShapeFill(c.shape, c.radius, + c.ir, c.ig, c.ib, c.groundAlpha * c.brightness); + } + } + + // 2. Pulse rings + if (c.rings) { + int count = Math.max(1, Math.min(5, c.ringCount)); + for (int i = 0; i < count; i++) { + float frac = (i + 1.0f) / (count + 1); + float ra = (0.4f + 0.3f * sin(c.pulse + i * Math.PI / 3)) * c.brightness; + float yOff = 0.02f + i * 0.01f; + renderRingLine(c.shape, c.radius * frac, + rR, rG, rB, ra, yOff); + } + // Always include outer edge ring + float edgeA = (0.5f + 0.4f * sin(c.pulse + count * Math.PI / 3)) * c.brightness; + renderRingLine(c.shape, c.radius, rR, rG, rB, edgeA, 0.02f + count * 0.01f); + } + + // 3. Rotating border + if (c.border) { + renderRotatingBorder(c.shape, c.radius, rR, rG, rB, + 0.7f * c.brightness, c.rotation * c.borderSpeed, 0.05f); + } + + // 4. Vertical accents + if (c.accents) { + float aa = 0.5f * c.brightness * (0.3f + 0.2f * sin(c.pulse * 0.7f)); + AccentStyle style = AccentStyle.values()[Math.min(c.accentStyle, AccentStyle.values().length - 1)]; + switch (style) { + case SWAYING: + renderSwayingAccents(c, c.ir, c.ig, c.ib, aa, c.height); + break; + case FLICKERING: + renderFlickeringAccents(c, c.ir, c.ig, c.ib, aa, c.height); + break; + default: + renderVerticalAccents(c.shape, c.radius, c.ir, c.ig, c.ib, aa, c.height, c.rotation * 0.3f); + break; + } + } + + // 5. Lightning + if (c.lightning) { + int innerColor = c.zone.getInnerColor(); + int outerColor = c.outerEnabled ? c.zone.getOuterColor() : innerColor; + AttachedLightningRenderer.LightningState state = getLightningState(c.zone); + if (c.newTick) { + state.tick(); + float density = 0.4f * c.brightness * c.lightningDensity; + if (RANDOM.nextFloat() < density) { + double[] p1 = randomPosInZone(c); + double[] p2 = randomPosInZone(c); + double y1 = RANDOM.nextDouble() * c.height * 0.4; + double y2 = RANDOM.nextDouble() * c.height * 0.4; + float disp = c.radius * 0.15f; + state.addArc(AttachedLightningRenderer.createArcBetween( + p1[0], y1, p1[2], p2[0], y2, p2[2], disp, outerColor, innerColor, 6)); + } + if (RANDOM.nextFloat() < density * 0.5f * c.lightningDensity) { + double[] edgePos = randomEdgePos(c); + double ex = edgePos[0]; + double ez = edgePos[1]; + float disp = c.radius * 0.12f; + state.addArc(AttachedLightningRenderer.createArcBetween( + ex, 0, ez, ex + (RANDOM.nextDouble() - 0.5) * 0.5, + c.height * (0.3 + RANDOM.nextDouble() * 0.4), + ez + (RANDOM.nextDouble() - 0.5) * 0.5, + disp, outerColor, innerColor, 5)); + } + } + state.render(); + GL11.glDepthMask(false); // Reset after lightning + } + + // 6. Particles + if (c.particles && c.newTick && c.particleDensity > 0) { + if (c.particleDir != null && !c.particleDir.isEmpty()) { + spawnCustomFXParticle(c); + } else { + spawnDefaultParticles(c); + } + } + } + + /** Spawn CustomFX particles using a texture directory. */ + private void spawnCustomFXParticle(Ctx c) { + int count = Math.round(3 * c.particleDensity); + for (int i = 0; i < count; i++) { + double[] pos = randomPosInZone(c); + double[] motion = getMotionForStyle(c.particleMotion); + CustomFX fx = new CustomFX(c.zone.worldObj, null, c.particleDir, + c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2], + motion[0], motion[1], motion[2]); + fx.setMaxAge(20 + RANDOM.nextInt(20)); + fx.scaleX1 = c.particleScale * 10.0f; + fx.scaleY1 = c.particleScale * 10.0f; + fx.width = c.particleSize; + fx.height = c.particleSize; + fx.HEXColor = c.zone.getInnerColor(); + fx.facePlayer = true; + fx.glows = c.particleGlow; + fx.alpha1 = 0.8f; + fx.alpha2 = 0.0f; + fx.alphaRate = 0.04f; + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + + /** Spawn default ZoneParticleFX with motion style from ParticleMotion enum. */ + private void spawnDefaultParticles(Ctx c) { + int count = Math.round(3 * c.particleDensity); + ParticleMotion motion = ParticleMotion.values()[Math.min(c.particleMotion, ParticleMotion.values().length - 1)]; + for (int i = 0; i < count; i++) { + double[] pos = randomPosInZone(c); + double mx, my, mz; + float gravity; + int age; + switch (motion) { + case DRIFTING: + mx = (RANDOM.nextDouble() - 0.5) * 0.005; + my = 0.005 + RANDOM.nextDouble() * 0.01; + mz = (RANDOM.nextDouble() - 0.5) * 0.005; + gravity = 0; + age = 40 + RANDOM.nextInt(20); + break; + case SPARKS: + mx = (RANDOM.nextDouble() - 0.5) * 0.08; + my = RANDOM.nextDouble() * 0.06; + mz = (RANDOM.nextDouble() - 0.5) * 0.08; + gravity = 0; + age = 4 + RANDOM.nextInt(6); + break; + default: // RISING + mx = (RANDOM.nextDouble() - 0.5) * 0.01; + my = 0.01 + RANDOM.nextDouble() * 0.02; + mz = (RANDOM.nextDouble() - 0.5) * 0.01; + gravity = -0.01f; + age = 30 + RANDOM.nextInt(20); + break; + } + float scale = (1.5f + RANDOM.nextFloat() * 1.0f) * c.particleScale; + spawnParticle(c.zone, pos[0], pos[1], pos[2], mx, my, mz, + c.ir, c.ig, c.ib, 0.7f, scale, age, gravity, c.particleGlow); + } + } + + /** Get motion vector for a CustomFX particle based on ParticleMotion ordinal. */ + private double[] getMotionForStyle(int motionOrdinal) { + ParticleMotion motion = ParticleMotion.values()[Math.min(motionOrdinal, ParticleMotion.values().length - 1)]; + switch (motion) { + case DRIFTING: + return new double[]{ + (RANDOM.nextDouble() - 0.5) * 0.005, + 0.005 + RANDOM.nextDouble() * 0.01, + (RANDOM.nextDouble() - 0.5) * 0.005 + }; + case SPARKS: + return new double[]{ + (RANDOM.nextDouble() - 0.5) * 0.08, + RANDOM.nextDouble() * 0.06, + (RANDOM.nextDouble() - 0.5) * 0.08 + }; + default: // RISING + return new double[]{ + (RANDOM.nextDouble() - 0.5) * 0.01, + 0.01 + RANDOM.nextDouble() * 0.02, + (RANDOM.nextDouble() - 0.5) * 0.01 + }; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // STYLE HELPERS + // ═══════════════════════════════════════════════════════════════════ + + /** Get the ring/outer color (falls back to inner if outer not enabled). */ + private float ringR(Ctx c) { return c.outerEnabled ? c.outerR : c.ir; } + private float ringG(Ctx c) { return c.outerEnabled ? c.outerG : c.ig; } + private float ringB(Ctx c) { return c.outerEnabled ? c.outerB : c.ib; } + + private static float sin(double v) { return (float) Math.sin(v); } + + /** Vertical accents with sinusoidal sway per line. */ + private void renderSwayingAccents(Ctx c, float r, float g, float b, float a, float height) { + if (height <= 0.1f) return; + float rotRad = (float) Math.toRadians(c.rotation * 0.2f); + Tessellator tess = Tessellator.instance; + + if (c.shape == ZoneShape.SQUARE) { + renderSquareSwayingAccents(c, r, g, b, a, height, rotRad, tess); + } else { + for (int i = 0; i < ACCENT_LINE_COUNT; i++) { + float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad; + double lx = Math.cos(baseAngle) * c.radius; + double lz = Math.sin(baseAngle) * c.radius; + + float swayX = 0.15f * sin(c.time * 0.08f + i * 1.7f); + float swayZ = 0.15f * sin(c.time * 0.06f + i * 2.3f); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx + swayX, height, lz + swayZ); + tess.draw(); + } + } + } + + private void renderSquareSwayingAccents(Ctx c, float r, float g, float b, float a, float height, float rotRad, Tessellator tess) { + int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); + int idx = 0; + for (int side = 0; side < 4; side++) { + for (int j = 0; j < perSide; j++) { + float frac = (j + 0.5f) / perSide; + double lx, lz; + switch (side) { + case 0: lx = -c.radius + frac * 2 * c.radius; lz = -c.radius; break; + case 1: lx = c.radius; lz = -c.radius + frac * 2 * c.radius; break; + case 2: lx = c.radius - frac * 2 * c.radius; lz = c.radius; break; + default: lx = -c.radius; lz = c.radius - frac * 2 * c.radius; break; + } + float swayX = 0.15f * sin(c.time * 0.08f + idx * 1.7f); + float swayZ = 0.15f * sin(c.time * 0.06f + idx * 2.3f); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx + swayX, height, lz + swayZ); + tess.draw(); + idx++; + } + } + } + + /** Vertical accents with per-line random alpha flicker. */ + private void renderFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height) { + if (height <= 0.1f) return; + float rotRad = (float) Math.toRadians(c.rotation * 0.4f); + Tessellator tess = Tessellator.instance; + + if (c.shape == ZoneShape.SQUARE) { + renderSquareFlickeringAccents(c, r, g, b, baseAlpha, height, tess); + } else { + for (int i = 0; i < ACCENT_LINE_COUNT; i++) { + float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad; + double lx = Math.cos(baseAngle) * c.radius; + double lz = Math.sin(baseAngle) * c.radius; + + float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + i * 3.14f)); + float lineAlpha = baseAlpha * flicker; + float lineHeight = height * (0.6f + 0.4f * flicker); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, lineAlpha); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, lineHeight, lz); + tess.draw(); + } + } + } + + private void renderSquareFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height, Tessellator tess) { + int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); + int idx = 0; + for (int side = 0; side < 4; side++) { + for (int j = 0; j < perSide; j++) { + float frac = (j + 0.5f) / perSide; + double lx, lz; + switch (side) { + case 0: lx = -c.radius + frac * 2 * c.radius; lz = -c.radius; break; + case 1: lx = c.radius; lz = -c.radius + frac * 2 * c.radius; break; + case 2: lx = c.radius - frac * 2 * c.radius; lz = c.radius; break; + default: lx = -c.radius; lz = c.radius - frac * 2 * c.radius; break; + } + float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + idx * 3.14f)); + float lineAlpha = baseAlpha * flicker; + float lineHeight = height * (0.6f + 0.4f * flicker); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, lineAlpha); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, lineHeight, lz); + tess.draw(); + idx++; + } + } + } + + /** Pick a random position within the zone's area. Returns {x, y, z} offsets from zone center. */ + private double[] randomPosInZone(Ctx c) { + if (c.shape == ZoneShape.SQUARE) { + double px = (RANDOM.nextDouble() * 2 - 1) * c.radius; + double pz = (RANDOM.nextDouble() * 2 - 1) * c.radius; + return new double[]{px, 0, pz}; + } else { + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = Math.sqrt(RANDOM.nextDouble()) * c.radius; + double px = Math.cos(angle) * dist; + double pz = Math.sin(angle) * dist; + return new double[]{px, 0, pz}; + } + } + + /** Pick a random position on the edge of the zone. Returns {x, z}. */ + private double[] randomEdgePos(Ctx c) { + if (c.shape == ZoneShape.SQUARE) { + int side = RANDOM.nextInt(4); + double frac = RANDOM.nextDouble() * 2 - 1; + switch (side) { + case 0: return new double[]{frac * c.radius, -c.radius}; + case 1: return new double[]{frac * c.radius, c.radius}; + case 2: return new double[]{-c.radius, frac * c.radius}; + default: return new double[]{c.radius, frac * c.radius}; + } + } else { + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = c.radius * (0.5 + RANDOM.nextDouble() * 0.5); + return new double[]{Math.cos(angle) * dist, Math.sin(angle) * dist}; + } + } + + /** Spawn a zone particle at world position. */ + private void spawnParticle(EntityAbilityZone zone, double offsetX, double offsetY, double offsetZ, + double mx, double my, double mz, + float r, float g, float b, float alpha, + float scale, int maxAge, float gravity, boolean glow) { + ZoneParticleFX particle = new ZoneParticleFX( + zone.worldObj, + zone.posX + offsetX, zone.posY + offsetY, zone.posZ + offsetZ, + mx, my, mz, r, g, b, alpha, scale, maxAge, gravity, glow); + Minecraft.getMinecraft().effectRenderer.addEffect(particle); + } + + // ═══════════════════════════════════════════════════════════════════ + // GL STATE + // ═══════════════════════════════════════════════════════════════════ + + private void setupRenderState() { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + 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.glDisable(GL11.GL_LIGHTING); + GL11.glShadeModel(GL11.GL_SMOOTH); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f); + } + + private void restoreRenderState() { + GL11.glShadeModel(GL11.GL_FLAT); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glPopAttrib(); + } + + // ═══════════════════════════════════════════════════════════════════ + // SHAPE FILL (Ground plane) + // ═══════════════════════════════════════════════════════════════════ + + private void renderShapeFill(ZoneShape shape, float radius, float r, float g, float b, float a) { + GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + GL11.glPolygonOffset(-1.0f, -1.0f); + switch (shape) { + case CIRCLE: + renderCircleFill(radius, r, g, b, a); + break; + case SQUARE: + renderSquareFill(radius, r, g, b, a); + break; + } + GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + } + + private void renderCircleFill(float radius, float r, float g, float b, float a) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_TRIANGLE_FAN); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(0, 0, 0); + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + tess.addVertex(Math.cos(angle) * radius, 0, Math.sin(angle) * radius); + } + tess.draw(); + } + + private void renderSquareFill(float radius, float r, float g, float b, float a) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_QUADS); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(-radius, 0, -radius); + tess.addVertex(radius, 0, -radius); + tess.addVertex(radius, 0, radius); + tess.addVertex(-radius, 0, radius); + tess.draw(); + } + + // ═══════════════════════════════════════════════════════════════════ + // RING LINES (Concentric pulse rings) + // ═══════════════════════════════════════════════════════════════════ + + private void renderRingLine(ZoneShape shape, float radius, + float r, float g, float b, float a, float yOffset) { + switch (shape) { + case CIRCLE: + renderCircleRingLine(radius, r, g, b, a, yOffset); + break; + case SQUARE: + renderSquareRingLine(radius, r, g, b, a, yOffset); + break; + } + } + + private void renderCircleRingLine(float radius, float r, float g, float b, float a, float yOffset) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_LINE_LOOP); + tess.setColorRGBA_F(r, g, b, a); + for (int i = 0; i < CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + tess.addVertex(Math.cos(angle) * radius, yOffset, Math.sin(angle) * radius); + } + tess.draw(); + } + + private void renderSquareRingLine(float radius, float r, float g, float b, float a, float yOffset) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_LINE_LOOP); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(-radius, yOffset, -radius); + tess.addVertex(radius, yOffset, -radius); + tess.addVertex(radius, yOffset, radius); + tess.addVertex(-radius, yOffset, radius); + tess.draw(); + } + + // ═══════════════════════════════════════════════════════════════════ + // ROTATING BORDER + // ═══════════════════════════════════════════════════════════════════ + + private void renderRotatingBorder(ZoneShape shape, float radius, + float r, float g, float b, float a, + float rotationDeg, float yOffset) { + int dashCount = 16; + + if (shape == ZoneShape.SQUARE) { + // Dashes along 4 rectangle edges with offset + float perimeter = radius * 8; // total perimeter = 4 * (2*radius) + float dashLen = perimeter / dashCount; + float offset = (rotationDeg % 360.0f) / 360.0f * perimeter; + + Tessellator tess = Tessellator.instance; + for (int i = 0; i < dashCount; i += 2) { + float startDist = (i * dashLen + offset) % perimeter; + float endDist = startDist + dashLen; + + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.setColorRGBA_F(r, g, b, a); + int steps = 4; + for (int s = 0; s <= steps; s++) { + float d = startDist + (endDist - startDist) * s / steps; + double[] pos = perimeterPos(d % perimeter, radius); + tess.addVertex(pos[0], yOffset, pos[1]); + } + tess.draw(); + } + } else { + float dashAngle = (float) (Math.PI * 2) / dashCount; + float rotRad = (float) Math.toRadians(rotationDeg); + + Tessellator tess = Tessellator.instance; + for (int i = 0; i < dashCount; i += 2) { + float startAngle = i * dashAngle + rotRad; + float endAngle = startAngle + dashAngle; + + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.setColorRGBA_F(r, g, b, a); + int steps = 4; + for (int s = 0; s <= steps; s++) { + float segAngle = startAngle + (endAngle - startAngle) * s / steps; + tess.addVertex(Math.cos(segAngle) * radius, yOffset, Math.sin(segAngle) * radius); + } + tess.draw(); + } + } + } + + /** Convert a distance along the square perimeter to an x,z position. */ + private double[] perimeterPos(float dist, float radius) { + float sideLen = radius * 2; + if (dist < sideLen) { + // Bottom edge: (-radius, -radius) to (radius, -radius) + return new double[]{-radius + dist, -radius}; + } + dist -= sideLen; + if (dist < sideLen) { + // Right edge: (radius, -radius) to (radius, radius) + return new double[]{radius, -radius + dist}; + } + dist -= sideLen; + if (dist < sideLen) { + // Top edge: (radius, radius) to (-radius, radius) + return new double[]{radius - dist, radius}; + } + dist -= sideLen; + // Left edge: (-radius, radius) to (-radius, -radius) + return new double[]{-radius, radius - dist}; + } + + // ═══════════════════════════════════════════════════════════════════ + // VERTICAL ACCENT LINES + // ═══════════════════════════════════════════════════════════════════ + + private void renderVerticalAccents(ZoneShape shape, float radius, + float r, float g, float b, float a, + float height, float rotationDeg) { + if (height <= 0.1f) return; + + Tessellator tess = Tessellator.instance; + + if (shape == ZoneShape.SQUARE) { + // Lines at corners + distributed along edges + int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); + for (int side = 0; side < 4; side++) { + for (int j = 0; j < perSide; j++) { + float frac = (j + 0.5f) / perSide; + double lx, lz; + switch (side) { + case 0: lx = -radius + frac * 2 * radius; lz = -radius; break; + case 1: lx = radius; lz = -radius + frac * 2 * radius; break; + case 2: lx = radius - frac * 2 * radius; lz = radius; break; + default: lx = -radius; lz = radius - frac * 2 * radius; break; + } + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, height, lz); + tess.draw(); + } + } + // Corner accent lines + float[][] corners = {{-radius, -radius}, {radius, -radius}, {radius, radius}, {-radius, radius}}; + for (float[] corner : corners) { + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(corner[0], 0.01, corner[1]); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(corner[0], height, corner[1]); + tess.draw(); + } + } else { + float rotRad = (float) Math.toRadians(rotationDeg); + for (int i = 0; i < ACCENT_LINE_COUNT; i++) { + float angle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad; + double lx = Math.cos(angle) * radius; + double lz = Math.sin(angle) * radius; + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, height, lz); + tess.draw(); + } + } + } + + @Override + protected ResourceLocation getEntityTexture(Entity entity) { + return null; + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java index d68c4037b..2910a9566 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -85,6 +85,28 @@ public class AttachedLightningRenderer { } } + /** + * Age existing arcs and remove dead ones without spawning new arcs. + * Use with addArc() for custom arc generation. + */ + public void tick() { + Iterator iter = arcs.iterator(); + while (iter.hasNext()) { + LightningArc arc = iter.next(); + arc.tick(); + if (arc.isDead()) { + iter.remove(); + } + } + } + + /** + * Add a custom arc to the state. + */ + public void addArc(LightningArc arc) { + arcs.add(arc); + } + /** * Render all active arcs in local space. * Call this after glTranslated to entity position. @@ -231,6 +253,17 @@ public class AttachedLightningRenderer { } } + /** + * Create a lightning arc between two arbitrary points. + */ + public static LightningArc createArcBetween(double x1, double y1, double z1, + double x2, double y2, double z2, + float displacement, int outerColor, int innerColor, int maxAge) { + int segments = 4 + rand.nextInt(3); + List points = generateLightningPath(x1, y1, z1, x2, y2, z2, segments, displacement); + return new LightningArc(points, maxAge, outerColor, innerColor); + } + // ==================== INSTANT RENDERING (no persistence) ==================== /** diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index f1ae7e719..89dd8b00d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -1,19 +1,11 @@ package kamkeel.npcs.controllers.data.ability.type; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.UserType; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionEffect; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityHazard; @@ -23,93 +15,28 @@ import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; -import java.util.Random; -import java.util.Set; /** - * Hazard ability: Creates persistent ground effect zones. - * Deals damage and/or applies debuffs to entities in the zone over time. + * Hazard ability: Creates persistent ground effect zones around the caster. + * Spawns one or more EntityAbilityZone entities in random positions + * within spawnRadius. Damage and zone logic handled by the entity. */ -public class AbilityHazard extends Ability implements IAbilityHazard { +public class AbilityHazard extends AbilityZone implements IAbilityHazard { - public enum HazardShape { - CIRCLE, - RING, - CONE; - - @Override - public String toString() { - switch (this) { - case CIRCLE: return "ability.shape.circle"; - case RING: return "ability.shape.ring"; - case CONE: return "ability.shape.cone"; - default: return name(); - } - } - } - - public enum PlacementMode { - AT_CASTER, - AT_TARGET, - FOLLOW_CASTER, - FOLLOW_TARGET; - - @Override - public String toString() { - switch (this) { - case AT_CASTER: return "ability.placement.atCaster"; - case AT_TARGET: return "ability.placement.atTarget"; - case FOLLOW_CASTER: return "ability.placement.followCaster"; - case FOLLOW_TARGET: return "ability.placement.followTarget"; - default: return name(); - } - } - } - - private int durationTicks = 100; + // Hazard-specific fields private float radius = 4.0f; - private float innerRadius = 0.0f; - private float coneAngle = 45.0f; - private HazardShape shape = HazardShape.CIRCLE; - private PlacementMode placement = PlacementMode.AT_TARGET; - private float damagePerSecond = 1.0f; private int damageInterval = 20; private boolean ignoreInvulnFrames = false; - - private int slownessLevel = -1; - private int weaknessLevel = -1; - private int poisonLevel = -1; - private int witherLevel = -1; - private int blindnessLevel = -1; - private int debuffDuration = 40; - private boolean affectsCaster = false; - private float heightAbove = 2.0f; - private float heightBelow = 1.0f; - - // Offset parameters - hazard spawns near target, not exactly on them - private float minOffset = 0.0f; // Minimum offset from target - private float maxOffset = 2.0f; // Maximum offset from target - private boolean randomOffset = true; // Random or fixed offset - - // Runtime state - private static final Random RANDOM = new Random(); - private transient double zoneX, zoneY, zoneZ; - private transient boolean positionLocked = false; - private transient int ticksSinceDamage = 0; - private transient Set damagedThisTick = new HashSet<>(); public AbilityHazard() { + super(100, new EnergyDisplayData(0x00CC00, 0x006600, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.hazard"; this.name = "Hazard"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 15.0f; - this.lockMovement = LockMovementType.WINDUP; - this.cooldownTicks = 0; this.windUpTicks = 30; this.telegraphType = TelegraphType.CIRCLE; this.allowedBy = UserType.NPC_ONLY; @@ -117,21 +44,6 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.activeAnimationName = "Ability_Hazard_Active"; } - @Override - public boolean allowBurst() { - return false; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - @Override public float getTelegraphRadius() { return radius; @@ -193,222 +105,71 @@ public class AbilityHazard extends Ability implements IAbilityHazard { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Lock position from telegraph (which was following target) or calculate it now - TelegraphInstance telegraph = getTelegraphInstance(); - - switch (placement) { - case AT_CASTER: - // Already locked during windup - if (!positionLocked) { - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - } - break; - case AT_TARGET: - if (telegraph != null) { - double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), - minOffset, maxOffset, randomOffset, RANDOM); - zoneX = pos[0]; - zoneY = pos[1]; - zoneZ = pos[2]; - telegraph.setX(zoneX); - telegraph.setY(zoneY); - telegraph.setZ(zoneZ); - } else if (target != null) { - double[] pos = Ability.calculateOffsetPosition(target.posX, target.posY, target.posZ, - minOffset, maxOffset, randomOffset, RANDOM); - zoneX = pos[0]; - zoneY = pos[1]; - zoneZ = pos[2]; - } else { - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - } - break; - case FOLLOW_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - break; - case FOLLOW_TARGET: - if (target != null) { - zoneX = target.posX; - zoneY = target.posY; - zoneZ = target.posZ; - } else { - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - } - break; - } - positionLocked = true; - ticksSinceDamage = damageInterval; - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - // Check if hazard duration has ended - if (tick >= durationTicks) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - if (!isPreview()) { - damagedThisTick.clear(); - ticksSinceDamage++; + activeEntities.clear(); - switch (placement) { - case FOLLOW_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - break; - case FOLLOW_TARGET: - if (target != null) { - zoneX = target.posX; - zoneY = target.posY; - zoneZ = target.posZ; - } - break; - default: - break; + List placedPositions = new ArrayList<>(); + float minSeparation = radius * 2.0f; + + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + + EntityAbilityZone entity = EntityAbilityZone.createHazard(world, caster, + pos[0], caster.posY, pos[1], + zoneShape, + radius, + damagePerSecond, damageInterval, + ignoreInvulnFrames, affectsCaster, + durationTicks, + colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, + zoneHeight, + particleDensity, particleScale, animSpeed, lightningDensity, + getEffects()); + + applyVisualToEntity(entity); + + if (isPreview()) { + entity.setupPreview(caster); } - if (ticksSinceDamage >= damageInterval) { - ticksSinceDamage = 0; - - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - zoneX - radius, zoneY - heightBelow, zoneZ - radius, - zoneX + radius, zoneY + heightAbove, zoneZ + radius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); - - for (EntityLivingBase entity : entities) { - if (entity == caster && !affectsCaster) continue; - if (damagedThisTick.contains(entity.getEntityId())) continue; - if (!isInZone(entity, caster)) continue; - - if (damagePerSecond > 0) { - if (ignoreInvulnFrames) { - entity.hurtResistantTime = 0; - } - // Apply damage with scripted event support (no knockback for hazard) - boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0); - if (!wasHit) continue; // Skip debuffs if hit was cancelled - } - - applyDebuffs(entity); - damagedThisTick.add(entity.getEntityId()); - } - } + spawnAbilityEntity(world, entity); + activeEntities.add(entity); } } - private boolean isInZone(EntityLivingBase entity, EntityLivingBase caster) { - double dx = entity.posX - zoneX; - double dz = entity.posZ - zoneZ; - double dist = Math.sqrt(dx * dx + dz * dz); - - switch (shape) { - case CIRCLE: - return dist <= radius; - case RING: - return dist >= innerRadius && dist <= radius; - case CONE: - if (dist > radius) return false; - float casterYaw = caster.rotationYaw; - double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); - double angleDiff = Math.abs(normalizeAngle(angleToEntity - casterYaw)); - return angleDiff <= coneAngle / 2; - default: - return dist <= radius; - } - } - - private double normalizeAngle(double angle) { - while (angle > 180) angle -= 360; - while (angle < -180) angle += 360; - return angle; - } - - private void applyDebuffs(EntityLivingBase target) { - if (slownessLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, debuffDuration, slownessLevel)); - } - if (weaknessLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.weakness.id, debuffDuration, weaknessLevel)); - } - if (poisonLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.poison.id, debuffDuration, poisonLevel)); - } - if (witherLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.wither.id, debuffDuration, witherLevel)); - } - if (blindnessLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.blindness.id, debuffDuration, blindnessLevel)); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - damagedThisTick.clear(); - positionLocked = false; - } - - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - damagedThisTick.clear(); - positionLocked = false; - } + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ @Override public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); + writeZoneNBT(nbt); nbt.setFloat("radius", radius); - nbt.setFloat("innerRadius", innerRadius); - nbt.setFloat("coneAngle", coneAngle); - nbt.setString("shape", shape.name()); - nbt.setString("placement", placement.name()); nbt.setFloat("damagePerSecond", damagePerSecond); nbt.setInteger("damageInterval", damageInterval); nbt.setBoolean("ignoreInvulnFrames", ignoreInvulnFrames); - nbt.setInteger("slownessLevel", slownessLevel); - nbt.setInteger("weaknessLevel", weaknessLevel); - nbt.setInteger("poisonLevel", poisonLevel); - nbt.setInteger("witherLevel", witherLevel); - nbt.setInteger("blindnessLevel", blindnessLevel); - nbt.setInteger("debuffDuration", debuffDuration); nbt.setBoolean("affectsCaster", affectsCaster); - nbt.setFloat("heightAbove", heightAbove); - nbt.setFloat("heightBelow", heightBelow); - nbt.setFloat("minOffset", minOffset); - nbt.setFloat("maxOffset", maxOffset); - nbt.setBoolean("randomOffset", randomOffset); } @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 100; + readZoneNBT(nbt, 100); + + // Backward compat: old "shape" key with RING/CONE → ignore (base defaults to CIRCLE) + // The old HazardShape enum had CIRCLE/RING/CONE — only CIRCLE maps to new ZoneShape + if (nbt.hasKey("shape")) { + String oldShape = nbt.getString("shape"); + if ("RING".equals(oldShape) || "CONE".equals(oldShape)) { + this.zoneShape = ZoneShape.CIRCLE; + } + } + this.radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 4.0f; - this.innerRadius = nbt.hasKey("innerRadius") ? nbt.getFloat("innerRadius") : 0.0f; - this.coneAngle = nbt.hasKey("coneAngle") ? nbt.getFloat("coneAngle") : 45.0f; - try { - this.shape = HazardShape.valueOf(nbt.getString("shape")); - } catch (Exception e) { - this.shape = HazardShape.CIRCLE; - } - try { - this.placement = PlacementMode.valueOf(nbt.getString("placement")); - } catch (Exception e) { - this.placement = PlacementMode.AT_TARGET; - } // Support legacy "damagePerTick" key for backwards compatibility if (nbt.hasKey("damagePerSecond")) { this.damagePerSecond = nbt.getFloat("damagePerSecond"); @@ -419,252 +180,60 @@ public class AbilityHazard extends Ability implements IAbilityHazard { } this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 20; this.ignoreInvulnFrames = nbt.hasKey("ignoreInvulnFrames") && nbt.getBoolean("ignoreInvulnFrames"); - this.slownessLevel = nbt.hasKey("slownessLevel") ? nbt.getInteger("slownessLevel") : -1; - this.weaknessLevel = nbt.hasKey("weaknessLevel") ? nbt.getInteger("weaknessLevel") : -1; - this.poisonLevel = nbt.hasKey("poisonLevel") ? nbt.getInteger("poisonLevel") : -1; - this.witherLevel = nbt.hasKey("witherLevel") ? nbt.getInteger("witherLevel") : -1; - this.blindnessLevel = nbt.hasKey("blindnessLevel") ? nbt.getInteger("blindnessLevel") : -1; - this.debuffDuration = nbt.hasKey("debuffDuration") ? nbt.getInteger("debuffDuration") : 40; this.affectsCaster = nbt.hasKey("affectsCaster") && nbt.getBoolean("affectsCaster"); - this.heightAbove = nbt.hasKey("heightAbove") ? nbt.getFloat("heightAbove") : 2.0f; - this.heightBelow = nbt.hasKey("heightBelow") ? nbt.getFloat("heightBelow") : 1.0f; - this.minOffset = nbt.hasKey("minOffset") ? nbt.getFloat("minOffset") : 0.0f; - this.maxOffset = nbt.hasKey("maxOffset") ? nbt.getFloat("maxOffset") : 2.0f; - this.randomOffset = !nbt.hasKey("randomOffset") || nbt.getBoolean("randomOffset"); } - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } + // ═══════════════════════════════════════════════════════════════════ + // HAZARD-SPECIFIC GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } + public float getRadius() { return radius; } + public void setRadius(float radius) { this.radius = radius; } - public float getRadius() { - return radius; - } + public float getDamagePerSecond() { return damagePerSecond; } + public void setDamagePerSecond(float damagePerSecond) { this.damagePerSecond = damagePerSecond; } - public void setRadius(float radius) { - this.radius = radius; - } + public int getDamageInterval() { return damageInterval; } + public void setDamageInterval(int damageInterval) { this.damageInterval = damageInterval; } - public float getInnerRadius() { - return innerRadius; - } + public boolean isIgnoreInvulnFrames() { return ignoreInvulnFrames; } + public void setIgnoreInvulnFrames(boolean ignoreInvulnFrames) { this.ignoreInvulnFrames = ignoreInvulnFrames; } - public void setInnerRadius(float innerRadius) { - this.innerRadius = innerRadius; - } + public boolean isAffectsCaster() { return affectsCaster; } + public void setAffectsCaster(boolean affectsCaster) { this.affectsCaster = affectsCaster; } - public float getConeAngle() { - return coneAngle; - } - - public void setConeAngle(float coneAngle) { - this.coneAngle = coneAngle; - } - - public HazardShape getShapeEnum() { - return shape; - } - - public void setShapeEnum(HazardShape shape) { - this.shape = shape; - } - - @Override - public int getShape() { - return shape.ordinal(); - } - - @Override - public void setShape(int shape) { - HazardShape[] values = HazardShape.values(); - this.shape = shape >= 0 && shape < values.length ? values[shape] : HazardShape.CIRCLE; - } - - public PlacementMode getPlacementEnum() { - return placement; - } - - public void setPlacementEnum(PlacementMode placement) { - this.placement = placement; - } - - @Override - public int getPlacement() { - return placement.ordinal(); - } - - @Override - public void setPlacement(int placement) { - PlacementMode[] values = PlacementMode.values(); - this.placement = placement >= 0 && placement < values.length ? values[placement] : PlacementMode.AT_CASTER; - } - - public float getDamagePerSecond() { - return damagePerSecond; - } - - public void setDamagePerSecond(float damagePerSecond) { - this.damagePerSecond = damagePerSecond; - } - - public int getDamageInterval() { - return damageInterval; - } - - public void setDamageInterval(int damageInterval) { - this.damageInterval = damageInterval; - } - - public boolean isIgnoreInvulnFrames() { - return ignoreInvulnFrames; - } - - public void setIgnoreInvulnFrames(boolean ignoreInvulnFrames) { - this.ignoreInvulnFrames = ignoreInvulnFrames; - } - - public int getSlownessLevel() { - return slownessLevel; - } - - public void setSlownessLevel(int slownessLevel) { - this.slownessLevel = slownessLevel; - } - - public int getWeaknessLevel() { - return weaknessLevel; - } - - public void setWeaknessLevel(int weaknessLevel) { - this.weaknessLevel = weaknessLevel; - } - - public int getPoisonLevel() { - return poisonLevel; - } - - public void setPoisonLevel(int poisonLevel) { - this.poisonLevel = poisonLevel; - } - - public int getWitherLevel() { - return witherLevel; - } - - public void setWitherLevel(int witherLevel) { - this.witherLevel = witherLevel; - } - - public int getBlindnessLevel() { - return blindnessLevel; - } - - public void setBlindnessLevel(int blindnessLevel) { - this.blindnessLevel = blindnessLevel; - } - - public int getDebuffDuration() { - return debuffDuration; - } - - public void setDebuffDuration(int debuffDuration) { - this.debuffDuration = debuffDuration; - } - - public boolean isAffectsCaster() { - return affectsCaster; - } - - public void setAffectsCaster(boolean affectsCaster) { - this.affectsCaster = affectsCaster; - } - - public float getHeightAbove() { - return heightAbove; - } - - public void setHeightAbove(float heightAbove) { - this.heightAbove = heightAbove; - } - - public float getHeightBelow() { - return heightBelow; - } - - public void setHeightBelow(float heightBelow) { - this.heightBelow = heightBelow; - } - - public float getMinOffset() { - return minOffset; - } - - public void setMinOffset(float minOffset) { - this.minOffset = minOffset; - } - - public float getMaxOffset() { - return maxOffset; - } - - public void setMaxOffset(float maxOffset) { - this.maxOffset = maxOffset; - } - - public boolean isRandomOffset() { - return randomOffset; - } - - public void setRandomOffset(boolean randomOffset) { - this.randomOffset = randomOffset; - } - - // Runtime getters - public double getZoneX() { - return zoneX; - } - - public double getZoneY() { - return zoneY; - } - - public double getZoneZ() { - return zoneZ; - } + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { defs.addAll(Arrays.asList( - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), - FieldDef.enumField("ability.shape", HazardShape.class, this::getShapeEnum, this::setShapeEnum) - .hover("ability.hover.shape"), - FieldDef.enumField("ability.placement", PlacementMode.class, this::getPlacementEnum, this::setPlacementEnum) - .hover("ability.hover.placement"), - FieldDef.section("ability.section.area"), FieldDef.row( - FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), - FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius) + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), + FieldDef.enumField("ability.zoneShape", ZoneShape.class, this::getZoneShapeEnum, this::setZoneShapeEnum) ), + FieldDef.section("ability.section.zone"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getSpawnRadius, this::setSpawnRadius), + FieldDef.intField("gui.count", this::getZoneCount, this::setZoneCount).range(1, 20) + ), + FieldDef.floatField("gui.height", this::getZoneHeight, this::setZoneHeight), + FieldDef.section("ability.section.area"), + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), FieldDef.section("ability.section.damage"), FieldDef.row( - FieldDef.floatField("ability.damagePerSecond", this::getDamagePerSecond, this::setDamagePerSecond), - FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval) + FieldDef.floatField("gui.dps", this::getDamagePerSecond, this::setDamagePerSecond), + FieldDef.intField("gui.interval", this::getDamageInterval, this::setDamageInterval) ), - FieldDef.section("ability.section.debuffs"), - FieldDef.row( - FieldDef.intField("ability.slownessLevel", this::getSlownessLevel, this::setSlownessLevel), - FieldDef.intField("ability.debuffDuration", this::getDebuffDuration, this::setDebuffDuration) - ), - FieldDef.intField("ability.poisonLevel", this::getPoisonLevel, this::setPoisonLevel), + FieldDef.boolField("ability.ignoreInvulnFrames", this::isIgnoreInvulnFrames, this::setIgnoreInvulnFrames), FieldDef.boolField("ability.affectsCaster", this::isAffectsCaster, this::setAffectsCaster) .hover("ability.hover.affectsCaster"), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); + + addVisualFieldDefs(defs); + addTelegraphSizeField(defs); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 494192e04..173efa0de 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -1,17 +1,11 @@ package kamkeel.npcs.controllers.data.ability.type; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.UserType; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityTrap; @@ -21,38 +15,18 @@ import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.UUID; /** - * Trap ability: Places a proximity-triggered trap. - * Features arm time, trigger radius, and various effects on trigger. + * Trap ability: Places proximity-triggered traps around the caster. + * Spawns one or more EntityAbilityZone entities in random positions + * within spawnRadius of the caster. Damage and trigger logic handled by the entity. */ -public class AbilityTrap extends Ability implements IAbilityTrap { +public class AbilityTrap extends AbilityZone implements IAbilityTrap { - public enum TrapPlacement { - AT_CASTER, - AT_TARGET, - AHEAD_OF_CASTER; - - @Override - public String toString() { - switch (this) { - case AT_CASTER: return "ability.trapPlace.atCaster"; - case AT_TARGET: return "ability.trapPlace.atTarget"; - case AHEAD_OF_CASTER: return "ability.trapPlace.aheadOfCaster"; - default: return name(); - } - } - } - - private int durationTicks = 200; - private TrapPlacement placement = TrapPlacement.AT_TARGET; - private float placementDistance = 5.0f; + // Trap-specific fields private float triggerRadius = 2.0f; private int armTime = 20; private int maxTriggers = 1; @@ -62,240 +36,57 @@ public class AbilityTrap extends Ability implements IAbilityTrap { private float knockback = 0.5f; private boolean visible = true; - // Offset parameters - trap spawns near target, not exactly on them - private float minOffset = 0.0f; - private float maxOffset = 1.5f; - private boolean randomOffset = true; - - // Runtime state - private static final Random RANDOM = new Random(); - private transient double trapX, trapY, trapZ; - private transient boolean armed = false; - private transient int triggerCount = 0; - private transient int ticksSinceLastTrigger = 0; - private transient Set triggeredEntities = new HashSet<>(); - public AbilityTrap() { + super(200, new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.trap"; this.name = "Trap"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 15.0f; - this.lockMovement = LockMovementType.WINDUP; - this.cooldownTicks = 0; this.windUpTicks = 20; - this.telegraphType = TelegraphType.CIRCLE; - this.allowedBy = UserType.NPC_ONLY; - } - - @Override - public boolean allowBurst() { - return false; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public float getTelegraphRadius() { - return triggerRadius; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - TelegraphInstance instance = super.createTelegraph(caster, target); - if (instance == null) return null; - - // Control telegraph following based on placement mode - switch (placement) { - case AT_CASTER: - case AHEAD_OF_CASTER: - // Telegraph at caster or ahead, no following - instance.setEntityIdToFollow(-1); - if (placement == TrapPlacement.AHEAD_OF_CASTER) { - double yaw = Math.toRadians(caster.rotationYaw); - instance.setX(caster.posX - Math.sin(yaw) * placementDistance); - instance.setY(caster.posY); - instance.setZ(caster.posZ + Math.cos(yaw) * placementDistance); - } else { - instance.setX(caster.posX); - instance.setY(caster.posY); - instance.setZ(caster.posZ); - } - break; - case AT_TARGET: - if (target != null) { - instance.setEntityIdToFollow(target.getEntityId()); - } - break; - } - return instance; } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - armed = false; - triggerCount = 0; - ticksSinceLastTrigger = armTime; - triggeredEntities.clear(); - - // Use telegraph position if available (for AT_TARGET, it was following target) - TelegraphInstance telegraph = getTelegraphInstance(); - - switch (placement) { - case AT_CASTER: - trapX = caster.posX; - trapY = caster.posY; - trapZ = caster.posZ; - break; - case AT_TARGET: - if (telegraph != null) { - double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), - minOffset, maxOffset, randomOffset, RANDOM); - trapX = pos[0]; - trapY = pos[1]; - trapZ = pos[2]; - telegraph.setX(trapX); - telegraph.setY(trapY); - telegraph.setZ(trapZ); - } else if (target != null) { - double[] pos = Ability.calculateOffsetPosition(target.posX, target.posY, target.posZ, - minOffset, maxOffset, randomOffset, RANDOM); - trapX = pos[0]; - trapY = pos[1]; - trapZ = pos[2]; - } else { - trapX = caster.posX; - trapY = caster.posY; - trapZ = caster.posZ; - } - break; - case AHEAD_OF_CASTER: - double yaw = Math.toRadians(caster.rotationYaw); - trapX = caster.posX - Math.sin(yaw) * placementDistance; - trapY = caster.posY; - trapZ = caster.posZ + Math.cos(yaw) * placementDistance; - break; - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Check if trap duration has ended - if (tick >= durationTicks) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - if (!armed) { - if (tick >= armTime) { - armed = true; + activeEntities.clear(); + + List placedPositions = new ArrayList<>(); + float minSeparation = triggerRadius * 2.0f; + + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + + EntityAbilityZone entity = EntityAbilityZone.createTrap(world, caster, + pos[0], caster.posY, pos[1], + zoneShape, + triggerRadius, armTime, maxTriggers, triggerCooldown, + damage, damageRadius, knockback, durationTicks, + colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, + zoneHeight, + particleDensity, particleScale, animSpeed, lightningDensity, + getEffects()); + + applyVisualToEntity(entity); + + if (isPreview()) { + entity.setupPreview(caster); } - return; - } - ticksSinceLastTrigger++; - - if (maxTriggers > 0 && triggerCount >= maxTriggers) { - signalCompletion(); // All triggers used, trap is done - return; - } - - if (ticksSinceLastTrigger < triggerCooldown) { - return; - } - - if (!isPreview()) { - AxisAlignedBB box = AxisAlignedBB.getBoundingBox( - trapX - triggerRadius, trapY - 1, trapZ - triggerRadius, - trapX + triggerRadius, trapY + 2, trapZ + triggerRadius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; - if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; - - double dx = entity.posX - trapX; - double dz = entity.posZ - trapZ; - double dist = Math.sqrt(dx * dx + dz * dz); - - if (dist <= triggerRadius) { - triggerTrap(caster, entity, world); - return; - } - } + spawnAbilityEntity(world, entity); + activeEntities.add(entity); } } - private void triggerTrap(EntityLivingBase caster, EntityLivingBase triggerer, World world) { - triggerCount++; - ticksSinceLastTrigger = 0; - triggeredEntities.add(triggerer.getUniqueID()); - - Set affected = new HashSet<>(); - - if (damageRadius > 0) { - AxisAlignedBB box = AxisAlignedBB.getBoundingBox( - trapX - damageRadius, trapY - 1, trapZ - damageRadius, - trapX + damageRadius, trapY + 3, trapZ + damageRadius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - double dx = entity.posX - trapX; - double dz = entity.posZ - trapZ; - double dist = Math.sqrt(dx * dx + dz * dz); - if (dist <= damageRadius) { - affected.add(entity); - } - } - } else { - affected.add(triggerer); - } - - for (EntityLivingBase entity : affected) { - // Apply damage with scripted event support - boolean wasHit = applyAbilityDamage(caster, entity, damage, knockback); - - // Apply effects if the hit wasn't cancelled - if (wasHit) { - applyEffects(entity); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - armed = false; - triggerCount = 0; - triggeredEntities.clear(); - } - - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - armed = false; - triggerCount = 0; - triggeredEntities.clear(); - } + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ @Override public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); - nbt.setString("placement", placement.name()); - nbt.setFloat("placementDistance", placementDistance); + writeZoneNBT(nbt); nbt.setFloat("triggerRadius", triggerRadius); nbt.setInteger("armTime", armTime); nbt.setInteger("maxTriggers", maxTriggers); @@ -304,20 +95,11 @@ public class AbilityTrap extends Ability implements IAbilityTrap { nbt.setFloat("damageRadius", damageRadius); nbt.setFloat("knockback", knockback); nbt.setBoolean("visible", visible); - nbt.setFloat("minOffset", minOffset); - nbt.setFloat("maxOffset", maxOffset); - nbt.setBoolean("randomOffset", randomOffset); } @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 200; - try { - this.placement = TrapPlacement.valueOf(nbt.getString("placement")); - } catch (Exception e) { - this.placement = TrapPlacement.AT_TARGET; - } - this.placementDistance = nbt.hasKey("placementDistance") ? nbt.getFloat("placementDistance") : 5.0f; + readZoneNBT(nbt, 200); this.triggerRadius = nbt.hasKey("triggerRadius") ? nbt.getFloat("triggerRadius") : 2.0f; this.armTime = nbt.hasKey("armTime") ? nbt.getInteger("armTime") : 20; this.maxTriggers = nbt.hasKey("maxTriggers") ? nbt.getInteger("maxTriggers") : 1; @@ -326,168 +108,58 @@ public class AbilityTrap extends Ability implements IAbilityTrap { this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 0.0f; this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; this.visible = !nbt.hasKey("visible") || nbt.getBoolean("visible"); - this.minOffset = nbt.hasKey("minOffset") ? nbt.getFloat("minOffset") : 0.0f; - this.maxOffset = nbt.hasKey("maxOffset") ? nbt.getFloat("maxOffset") : 1.5f; - this.randomOffset = !nbt.hasKey("randomOffset") || nbt.getBoolean("randomOffset"); } - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } + // ═══════════════════════════════════════════════════════════════════ + // TRAP-SPECIFIC GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } + public float getTriggerRadius() { return triggerRadius; } + public void setTriggerRadius(float triggerRadius) { this.triggerRadius = triggerRadius; } + public int getArmTime() { return armTime; } + public void setArmTime(int armTime) { this.armTime = armTime; } + public int getMaxTriggers() { return maxTriggers; } + public void setMaxTriggers(int maxTriggers) { this.maxTriggers = maxTriggers; } + public int getTriggerCooldown() { return triggerCooldown; } + public void setTriggerCooldown(int triggerCooldown) { this.triggerCooldown = triggerCooldown; } + public float getDamage() { return damage; } + public void setDamage(float damage) { this.damage = damage; } + public float getDamageRadius() { return damageRadius; } + public void setDamageRadius(float damageRadius) { this.damageRadius = damageRadius; } + public float getKnockback() { return knockback; } + public void setKnockback(float knockback) { this.knockback = knockback; } + public boolean isVisible() { return visible; } + public void setVisible(boolean visible) { this.visible = visible; } - public TrapPlacement getPlacementEnum() { - return placement; - } - - public void setPlacementEnum(TrapPlacement placement) { - this.placement = placement; - } - - @Override - public int getPlacement() { - return placement.ordinal(); - } - - @Override - public void setPlacement(int placement) { - TrapPlacement[] values = TrapPlacement.values(); - this.placement = placement >= 0 && placement < values.length ? values[placement] : TrapPlacement.AT_TARGET; - } - - public float getPlacementDistance() { - return placementDistance; - } - - public void setPlacementDistance(float placementDistance) { - this.placementDistance = placementDistance; - } - - public float getTriggerRadius() { - return triggerRadius; - } - - public void setTriggerRadius(float triggerRadius) { - this.triggerRadius = triggerRadius; - } - - public int getArmTime() { - return armTime; - } - - public void setArmTime(int armTime) { - this.armTime = armTime; - } - - public int getMaxTriggers() { - return maxTriggers; - } - - public void setMaxTriggers(int maxTriggers) { - this.maxTriggers = maxTriggers; - } - - public int getTriggerCooldown() { - return triggerCooldown; - } - - public void setTriggerCooldown(int triggerCooldown) { - this.triggerCooldown = triggerCooldown; - } - - public float getDamage() { - return damage; - } - - public void setDamage(float damage) { - this.damage = damage; - } - - public float getDamageRadius() { - return damageRadius; - } - - public void setDamageRadius(float damageRadius) { - this.damageRadius = damageRadius; - } - - public float getKnockback() { - return knockback; - } - - public void setKnockback(float knockback) { - this.knockback = knockback; - } - - public boolean isVisible() { - return visible; - } - - public void setVisible(boolean visible) { - this.visible = visible; - } - - public float getMinOffset() { - return minOffset; - } - - public void setMinOffset(float minOffset) { - this.minOffset = minOffset; - } - - public float getMaxOffset() { - return maxOffset; - } - - public void setMaxOffset(float maxOffset) { - this.maxOffset = maxOffset; - } - - public boolean isRandomOffset() { - return randomOffset; - } - - public void setRandomOffset(boolean randomOffset) { - this.randomOffset = randomOffset; - } - - // Runtime getters - public double getTrapX() { - return trapX; - } - - public double getTrapY() { - return trapY; - } - - public double getTrapZ() { - return trapZ; - } - - public boolean isArmed() { - return armed; - } + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { defs.addAll(Arrays.asList( - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) - .range(1, 2000), - FieldDef.enumField("ability.placement", TrapPlacement.class, this::getPlacementEnum, this::setPlacementEnum) - .hover("ability.hover.placement"), + FieldDef.row( + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), + FieldDef.enumField("ability.zoneShape", ZoneShape.class, this::getZoneShapeEnum, this::setZoneShapeEnum) + ), + FieldDef.section("ability.section.zone"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getSpawnRadius, this::setSpawnRadius), + FieldDef.intField("gui.count", this::getZoneCount, this::setZoneCount).range(1, 20) + ), + FieldDef.row( + FieldDef.floatField("gui.height", this::getZoneHeight, this::setZoneHeight), + FieldDef.boolField("ability.visible", this::isVisible, this::setVisible) + ), FieldDef.section("ability.section.trigger"), FieldDef.row( FieldDef.floatField("gui.radius", this::getTriggerRadius, this::setTriggerRadius), FieldDef.intField("ability.armTime", this::getArmTime, this::setArmTime) ), FieldDef.row( - FieldDef.intField("ability.maxTriggers", this::getMaxTriggers, this::setMaxTriggers), - FieldDef.intField("ability.triggerCooldown", this::getTriggerCooldown, this::setTriggerCooldown) + FieldDef.intField("gui.max", this::getMaxTriggers, this::setMaxTriggers), + FieldDef.intField("gui.cooldown", this::getTriggerCooldown, this::setTriggerCooldown) ), FieldDef.section("ability.section.damage"), FieldDef.row( @@ -497,5 +169,8 @@ public class AbilityTrap extends Ability implements IAbilityTrap { FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); + + addVisualFieldDefs(defs); + addTelegraphSizeField(defs); } } 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 new file mode 100644 index 000000000..94ceea56d --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -0,0 +1,554 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle; +import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import net.minecraft.world.World; + +import noppes.npcs.client.gui.builder.FieldDef; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +/** + * Abstract base class for zone-based abilities (Trap, Hazard). + * Extracts shared fields: duration, shape, spawn, visual, lifecycle, and FieldDefs. + */ +public abstract class AbilityZone extends Ability { + + // Zone properties + protected int durationTicks; + protected ZoneShape zoneShape = ZoneShape.CIRCLE; + protected float spawnRadius = 5.0f; + protected float telegraphSize = 5.0f; + protected int zoneCount = 1; + protected float zoneHeight = 2.0f; + + // Visual parameters + protected float particleDensity = 1.0f; + protected float particleScale = 1.0f; + protected float animSpeed = 1.0f; + protected float lightningDensity = 1.0f; + protected EnergyDisplayData colorData; + + // Visual layer fields (always active) + protected boolean groundFill = true; + protected float groundAlpha = 0.25f; + protected boolean rings = true; + protected int ringCount = 3; + protected boolean border = true; + protected float borderSpeed = 1.0f; + protected boolean accents = true; + protected int accentStyle = 0; + protected boolean lightning = false; + protected boolean particles = true; + protected int particleMotion = 0; + protected String particleDir = ""; + protected int particleSize = 32; + protected boolean particleGlow = true; + + // Runtime state + protected static final Random RANDOM = new Random(); + protected transient List activeEntities = new ArrayList<>(); + + protected AbilityZone(int defaultDuration, EnergyDisplayData defaultColors) { + this.durationTicks = defaultDuration; + this.colorData = defaultColors; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 15.0f; + this.lockMovement = LockMovementType.WINDUP; + this.cooldownTicks = 0; + this.telegraphType = TelegraphType.CIRCLE; + this.allowedBy = UserType.NPC_ONLY; + } + + // ═════════════════════════════════════════════════════════════════ + // SHARED OVERRIDES + // ═════════════════════════════════════════════════════════════════ + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + public float getTelegraphRadius() { + return telegraphSize; + } + + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + TelegraphInstance instance = super.createTelegraph(caster, target); + if (instance == null) return null; + + // Always show telegraph at caster position + instance.setEntityIdToFollow(-1); + instance.setX(caster.posX); + instance.setY(caster.posY); + instance.setZ(caster.posZ); + return instance; + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + // Remove dead entities + Iterator it = activeEntities.iterator(); + while (it.hasNext()) { + EntityAbilityZone entity = it.next(); + if (entity == null || entity.isDead) { + it.remove(); + } + } + + if (activeEntities.isEmpty()) { + signalCompletion(); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + cleanup(); + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + for (EntityAbilityZone entity : activeEntities) { + if (entity != null && !entity.isDead) { + killAbilityEntity(entity); + } + } + activeEntities.clear(); + } + + @Override + public int getMaxPreviewDuration() { + return durationTicks + 10; + } + + // ═════════════════════════════════════════════════════════════════ + // SHARED SPAWN HELPER + // ═════════════════════════════════════════════════════════════════ + + /** + * Find a non-overlapping spawn position within spawnRadius of the caster. + */ + protected double[] findSpawnPosition(EntityLivingBase caster, List placedPositions, float minSeparation) { + double spawnX = caster.posX; + double spawnZ = caster.posZ; + + for (int attempt = 0; attempt < 15; attempt++) { + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = Math.sqrt(RANDOM.nextDouble()) * spawnRadius; + double candidateX = caster.posX + Math.cos(angle) * dist; + double candidateZ = caster.posZ + Math.sin(angle) * dist; + + boolean overlaps = false; + for (double[] placed : placedPositions) { + double dx = candidateX - placed[0]; + double dz = candidateZ - placed[1]; + if (Math.sqrt(dx * dx + dz * dz) < minSeparation) { + overlaps = true; + break; + } + } + + spawnX = candidateX; + spawnZ = candidateZ; + if (!overlaps) break; + } + + return new double[]{spawnX, spawnZ}; + } + + /** + * Apply visual settings to a zone entity. + */ + protected void applyVisualToEntity(EntityAbilityZone entity) { + entity.applyVisual(groundFill, groundAlpha, + rings, ringCount, border, borderSpeed, + accents, accentStyle, lightning, + particles, particleMotion, particleDir, + particleSize, particleGlow); + } + + // ═════════════════════════════════════════════════════════════════ + // PRESET SUPPORT + // ═════════════════════════════════════════════════════════════════ + + /** + * Apply preset defaults by old style name (for backward compatibility). + */ + private void applyPresetDefaults(String styleName) { + switch (styleName) { + case "TOXIC": + groundFill = true; groundAlpha = 0.30f; rings = true; ringCount = 3; + border = false; borderSpeed = 1.0f; accents = true; accentStyle = 1; + lightning = false; particles = true; particleMotion = 0; particleGlow = true; + break; + case "INFERNO": + groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; + border = true; borderSpeed = 2.0f; accents = true; accentStyle = 2; + lightning = false; particles = true; particleMotion = 0; particleGlow = true; + break; + case "ARCANE": + groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; + border = true; borderSpeed = 0.8f; accents = true; accentStyle = 0; + lightning = false; particles = true; particleMotion = 1; particleGlow = true; + break; + case "ELECTRIC": + groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; + border = false; borderSpeed = 1.0f; accents = false; accentStyle = 0; + lightning = true; particles = true; particleMotion = 2; particleGlow = true; + break; + case "FROST": + groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; + border = true; borderSpeed = 0.3f; accents = true; accentStyle = 0; + lightning = false; particles = true; particleMotion = 1; particleGlow = true; + break; + case "DEFAULT": + groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; + border = true; borderSpeed = 1.0f; accents = true; accentStyle = 0; + lightning = false; particles = false; particleMotion = 0; particleGlow = true; + break; + default: + break; + } + } + + /** + * Client-only preset enum for the GUI dropdown. + * Not persisted — presets simply set field values. + */ + @SideOnly(Side.CLIENT) + public enum ZonePreset { + CUSTOM, DEFAULT, TOXIC, INFERNO, ARCANE, ELECTRIC, FROST; + + @Override + public String toString() { + return "ability.preset." + name().toLowerCase(); + } + } + + /** + * Check current field values against each preset, return matching preset or CUSTOM. + */ + @SideOnly(Side.CLIENT) + public ZonePreset getCurrentPreset() { + if (matchesPreset(true, 0.25f, true, 3, true, 1.0f, true, 0, false, false, 0, true)) + return ZonePreset.DEFAULT; + if (matchesPreset(true, 0.30f, true, 3, false, 1.0f, true, 1, false, true, 0, true)) + return ZonePreset.TOXIC; + if (matchesPreset(true, 0.35f, true, 3, true, 2.0f, true, 2, false, true, 0, true)) + return ZonePreset.INFERNO; + if (matchesPreset(true, 0.20f, true, 1, true, 0.8f, true, 0, false, true, 1, true)) + return ZonePreset.ARCANE; + if (matchesPreset(true, 0.15f, false, 1, false, 1.0f, false, 0, true, true, 2, true)) + return ZonePreset.ELECTRIC; + if (matchesPreset(true, 0.25f, true, 3, true, 0.3f, true, 0, false, true, 1, true)) + return ZonePreset.FROST; + return ZonePreset.CUSTOM; + } + + @SideOnly(Side.CLIENT) + private boolean matchesPreset(boolean gf, float ga, boolean r, int rc, boolean b, float bs, + boolean a, int as, boolean l, boolean p, int pm, boolean pg) { + return groundFill == gf && Math.abs(groundAlpha - ga) < 0.001f + && rings == r && ringCount == rc && border == b && Math.abs(borderSpeed - bs) < 0.001f + && accents == a && accentStyle == as && lightning == l + && particles == p && particleMotion == pm && particleGlow == pg; + } + + /** + * Apply a preset's field values. CUSTOM does nothing (user configures manually). + */ + @SideOnly(Side.CLIENT) + public void applyPreset(ZonePreset preset) { + if (preset == ZonePreset.CUSTOM) return; + applyPresetDefaults(preset.name()); + } + + // ═════════════════════════════════════════════════════════════════ + // SHARED NBT + // ═════════════════════════════════════════════════════════════════ + + protected void writeZoneNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setString("zoneShape", zoneShape.name()); + nbt.setFloat("spawnRadius", spawnRadius); + nbt.setFloat("telegraphSize", telegraphSize); + nbt.setInteger("zoneCount", zoneCount); + nbt.setFloat("zoneHeight", zoneHeight); + nbt.setFloat("particleDensity", particleDensity); + nbt.setFloat("particleScale", particleScale); + nbt.setFloat("animSpeed", animSpeed); + nbt.setFloat("lightningDensity", lightningDensity); + colorData.writeNBT(nbt); + + // Visual layer fields — always written as top-level keys + 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); + } + + protected void readZoneNBT(NBTTagCompound nbt, int defaultDuration) { + this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : defaultDuration; + if (nbt.hasKey("zoneShape")) { + try { this.zoneShape = ZoneShape.valueOf(nbt.getString("zoneShape")); } + catch (Exception e) { this.zoneShape = ZoneShape.CIRCLE; } + } else { + this.zoneShape = ZoneShape.CIRCLE; + } + this.spawnRadius = nbt.hasKey("spawnRadius") ? nbt.getFloat("spawnRadius") : 5.0f; + this.telegraphSize = nbt.hasKey("telegraphSize") ? nbt.getFloat("telegraphSize") : spawnRadius; + this.zoneCount = nbt.hasKey("zoneCount") ? nbt.getInteger("zoneCount") : 1; + 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; + colorData.readNBT(nbt); + + // Visual fields — backward compat with old zoneStyle format + if (nbt.hasKey("zoneStyle")) { + // OLD FORMAT: apply preset defaults, then overlay CustomVisual + applyPresetDefaults(nbt.getString("zoneStyle")); + if (nbt.hasKey("CustomVisual")) { + NBTTagCompound custom = nbt.getCompoundTag("CustomVisual"); + this.groundFill = !custom.hasKey("groundFill") || custom.getBoolean("groundFill"); + this.groundAlpha = custom.hasKey("groundAlpha") ? custom.getFloat("groundAlpha") : 0.25f; + this.rings = !custom.hasKey("rings") || custom.getBoolean("rings"); + this.ringCount = custom.hasKey("ringCount") ? custom.getInteger("ringCount") : 3; + this.border = !custom.hasKey("border") || custom.getBoolean("border"); + this.borderSpeed = custom.hasKey("borderSpeed") ? custom.getFloat("borderSpeed") : 1.0f; + this.accents = !custom.hasKey("accents") || custom.getBoolean("accents"); + this.accentStyle = custom.hasKey("accentStyle") ? custom.getInteger("accentStyle") : 0; + this.lightning = custom.hasKey("lightning") && custom.getBoolean("lightning"); + this.particles = !custom.hasKey("particles") || custom.getBoolean("particles"); + this.particleMotion = custom.hasKey("particleMotion") ? custom.getInteger("particleMotion") : 0; + this.particleDir = custom.hasKey("particleDir") ? custom.getString("particleDir") : ""; + this.particleSize = custom.hasKey("particleSize") ? custom.getInteger("particleSize") : 32; + this.particleGlow = !custom.hasKey("particleGlow") || custom.getBoolean("particleGlow"); + } + } else { + // NEW FORMAT: read individual top-level keys + this.groundFill = !nbt.hasKey("groundFill") || nbt.getBoolean("groundFill"); + this.groundAlpha = nbt.hasKey("groundAlpha") ? nbt.getFloat("groundAlpha") : 0.25f; + this.rings = !nbt.hasKey("rings") || nbt.getBoolean("rings"); + this.ringCount = nbt.hasKey("ringCount") ? nbt.getInteger("ringCount") : 3; + this.border = !nbt.hasKey("border") || nbt.getBoolean("border"); + this.borderSpeed = nbt.hasKey("borderSpeed") ? nbt.getFloat("borderSpeed") : 1.0f; + this.accents = !nbt.hasKey("accents") || nbt.getBoolean("accents"); + this.accentStyle = nbt.hasKey("accentStyle") ? nbt.getInteger("accentStyle") : 0; + this.lightning = nbt.hasKey("lightning") && nbt.getBoolean("lightning"); + this.particles = !nbt.hasKey("particles") || nbt.getBoolean("particles"); + this.particleMotion = nbt.hasKey("particleMotion") ? nbt.getInteger("particleMotion") : 0; + this.particleDir = nbt.hasKey("particleDir") ? nbt.getString("particleDir") : ""; + this.particleSize = nbt.hasKey("particleSize") ? nbt.getInteger("particleSize") : 32; + this.particleGlow = !nbt.hasKey("particleGlow") || nbt.getBoolean("particleGlow"); + } + } + + // ═════════════════════════════════════════════════════════════════ + // SHARED GETTERS & SETTERS + // ═════════════════════════════════════════════════════════════════ + + public int getDurationTicks() { return durationTicks; } + public void setDurationTicks(int durationTicks) { this.durationTicks = Math.max(1, durationTicks); } + + public ZoneShape getZoneShapeEnum() { return zoneShape; } + public void setZoneShapeEnum(ZoneShape shape) { this.zoneShape = shape; } + + public int getZoneShapeOrdinal() { return zoneShape.ordinal(); } + public void setZoneShapeOrdinal(int shape) { + ZoneShape[] values = ZoneShape.values(); + this.zoneShape = shape >= 0 && shape < values.length ? values[shape] : ZoneShape.CIRCLE; + } + + public float getSpawnRadius() { return spawnRadius; } + public void setSpawnRadius(float spawnRadius) { this.spawnRadius = Math.max(0, spawnRadius); } + public float getTelegraphSize() { return telegraphSize; } + public void setTelegraphSize(float telegraphSize) { this.telegraphSize = Math.max(0, telegraphSize); } + public int getZoneCount() { return zoneCount; } + public void setZoneCount(int zoneCount) { this.zoneCount = Math.max(1, zoneCount); } + public float getZoneHeight() { return zoneHeight; } + public void setZoneHeight(float zoneHeight) { this.zoneHeight = Math.max(0.5f, zoneHeight); } + + public float getParticleDensity() { return particleDensity; } + public void setParticleDensity(float v) { this.particleDensity = Math.max(0, Math.min(5, v)); } + public float getParticleScale() { return particleScale; } + public void setParticleScale(float v) { this.particleScale = Math.max(0.1f, Math.min(5, v)); } + public float getAnimSpeed() { return animSpeed; } + public void setAnimSpeed(float v) { this.animSpeed = Math.max(0.1f, Math.min(5, v)); } + public float getLightningDensity() { return lightningDensity; } + public void setLightningDensity(float v) { this.lightningDensity = Math.max(0, Math.min(3, v)); } + + // Color getters/setters + public int getInnerColor() { return colorData.innerColor; } + public void setInnerColor(int color) { colorData.innerColor = color; } + public int getOuterColor() { return colorData.outerColor; } + public void setOuterColor(int color) { colorData.outerColor = color; } + public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } + public void setOuterColorEnabled(boolean enabled) { colorData.outerColorEnabled = enabled; } + + // Visual layer getters/setters + public boolean isGroundFill() { return groundFill; } + public void setGroundFill(boolean v) { this.groundFill = v; } + public float getGroundAlpha() { return groundAlpha; } + public void setGroundAlpha(float v) { this.groundAlpha = Math.max(0, Math.min(1, v)); } + public boolean isRings() { return rings; } + public void setRings(boolean v) { this.rings = v; } + public int getRingCount() { return ringCount; } + public void setRingCount(int v) { this.ringCount = Math.max(1, Math.min(5, v)); } + public boolean isBorder() { return border; } + public void setBorder(boolean v) { this.border = v; } + public float getBorderSpeed() { return borderSpeed; } + public void setBorderSpeed(float v) { this.borderSpeed = Math.max(0.1f, Math.min(5, v)); } + public boolean isAccents() { return accents; } + public void setAccents(boolean v) { this.accents = v; } + public int getAccentStyle() { return accentStyle; } + public void setAccentStyle(int v) { this.accentStyle = Math.max(0, Math.min(AccentStyle.values().length - 1, v)); } + public AccentStyle getAccentStyleEnum() { return AccentStyle.values()[Math.max(0, Math.min(accentStyle, AccentStyle.values().length - 1))]; } + public void setAccentStyleEnum(AccentStyle s) { this.accentStyle = s.ordinal(); } + public boolean isLightning() { return lightning; } + public void setLightning(boolean v) { this.lightning = v; } + public boolean isParticles() { return particles; } + public void setParticles(boolean v) { this.particles = v; } + public int getParticleMotion() { return particleMotion; } + public void setParticleMotion(int v) { this.particleMotion = Math.max(0, Math.min(ParticleMotion.values().length - 1, v)); } + public ParticleMotion getParticleMotionEnum() { return ParticleMotion.values()[Math.max(0, Math.min(particleMotion, ParticleMotion.values().length - 1))]; } + public void setParticleMotionEnum(ParticleMotion m) { this.particleMotion = m.ordinal(); } + public String getParticleDir() { return particleDir; } + public void setParticleDir(String v) { this.particleDir = v != null ? v : ""; } + public int getParticleSize() { return particleSize; } + public void setParticleSize(int v) { this.particleSize = Math.max(1, Math.min(256, v)); } + public boolean isParticleGlow() { return particleGlow; } + public void setParticleGlow(boolean v) { this.particleGlow = v; } + + // ═════════════════════════════════════════════════════════════════ + // SHARED FIELD DEFINITIONS (client-only) + // ═════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + protected void addVisualFieldDefs(List defs) { + defs.addAll(Arrays.asList( + // Preset dropdown + FieldDef.enumField("gui.preset", ZonePreset.class, this::getCurrentPreset, this::applyPreset) + .tab("ability.tab.visual"), + + // Ground Fill + FieldDef.section("ability.section.ground").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isGroundFill, this::setGroundFill), + FieldDef.floatField("gui.alpha", this::getGroundAlpha, this::setGroundAlpha) + ).tab("ability.tab.visual"), + + // Rings + FieldDef.section("ability.section.rings").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isRings, this::setRings), + FieldDef.intField("gui.count", this::getRingCount, this::setRingCount).range(1, 5) + ).tab("ability.tab.visual"), + + // Border + FieldDef.section("ability.section.border").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isBorder, this::setBorder), + FieldDef.floatField("gui.speed", this::getBorderSpeed, this::setBorderSpeed) + ).tab("ability.tab.visual"), + + // Accents + FieldDef.section("ability.section.accents").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isAccents, this::setAccents), + FieldDef.enumField("gui.style", AccentStyle.class, this::getAccentStyleEnum, this::setAccentStyleEnum) + ).tab("ability.tab.visual"), + + // Lightning + FieldDef.section("ability.section.lightning").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isLightning, this::setLightning), + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + ).tab("ability.tab.visual"), + + // Particles + FieldDef.section("ability.section.particles").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isParticles, this::setParticles), + FieldDef.floatField("gui.density", this::getParticleDensity, this::setParticleDensity) + ).tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("gui.scale", this::getParticleScale, this::setParticleScale), + FieldDef.enumField("gui.motion", ParticleMotion.class, this::getParticleMotionEnum, this::setParticleMotionEnum) + ).tab("ability.tab.visual"), + FieldDef.boolField("gui.glow", this::isParticleGlow, this::setParticleGlow) + .tab("ability.tab.visual"), + FieldDef.stringField("gui.texture", this::getParticleDir, this::setParticleDir) + .tab("ability.tab.visual").visibleWhen(this::isParticles), + FieldDef.intField("gui.size", this::getParticleSize, this::setParticleSize).range(1, 256) + .tab("ability.tab.visual").visibleWhen(this::isParticles), + + // Animation + FieldDef.section("ability.section.animation").tab("ability.tab.visual"), + FieldDef.floatField("gui.speed", this::getAnimSpeed, this::setAnimSpeed) + .tab("ability.tab.visual"), + + // Colors + FieldDef.section("ability.section.colors").tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual"), + FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled) + )); + } + + @SideOnly(Side.CLIENT) + protected void addTelegraphSizeField(List defs) { + defs.add(FieldDef.floatField("gui.size", this::getTelegraphSize, this::setTelegraphSize) + .tab("ability.tab.effects")); + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java new file mode 100644 index 000000000..2f2bc00e9 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -0,0 +1,928 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.common.network.ByteBufUtils; +import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.world.World; +import noppes.npcs.NpcDamageSource; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +/** + * Shared zone entity for Trap and Hazard abilities. + * Handles rendering, positioning, and damage logic. + */ +public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnData { + + // ═══════════════════════════════════════════════════════════════════ + // ENUMS + // ═══════════════════════════════════════════════════════════════════ + + public enum ZoneType { TRAP, HAZARD } + public enum ZoneShape { + CIRCLE, SQUARE; + + @Override + public String toString() { + switch (this) { + case CIRCLE: return "ability.shape.circle"; + case SQUARE: return "ability.shape.square"; + default: return name(); + } + } + } + + public enum AccentStyle { + STATIC, SWAYING, FLICKERING; + + @Override + public String toString() { + switch (this) { + case STATIC: return "ability.accentStyle.static"; + case SWAYING: return "ability.accentStyle.swaying"; + case FLICKERING: return "ability.accentStyle.flickering"; + default: return name(); + } + } + } + + public enum ParticleMotion { + RISING, DRIFTING, SPARKS; + + @Override + public String toString() { + switch (this) { + case RISING: return "ability.particleMotion.rising"; + case DRIFTING: return "ability.particleMotion.drifting"; + case SPARKS: return "ability.particleMotion.sparks"; + default: return name(); + } + } + } + + /** Tiny Y offset above ground to prevent z-clipping */ + private static final double GROUND_OFFSET = 0.005; + + // ═══════════════════════════════════════════════════════════════════ + // COMMON PROPERTIES (synced via ByteBuf) + // ═══════════════════════════════════════════════════════════════════ + + private ZoneType zoneType = ZoneType.TRAP; + private ZoneShape shape = ZoneShape.CIRCLE; + + private int ownerEntityId = -1; + + private float radius = 4.0f; + + private int durationTicks = 200; + private int maxTicks = 200; + + private int innerColor = 0xFF6600; + private int outerColor = 0xFF0000; + private boolean outerColorEnabled = true; + + private float zoneHeight = 2.0f; + + // Visual parameters (synced for renderer) + private float particleDensity = 1.0f; + private float particleScale = 1.0f; + private float animSpeed = 1.0f; + private float lightningDensity = 1.0f; + + // Visual layer parameters (always active) + private boolean groundFill = true; + private float groundAlpha = 0.25f; + private boolean rings = true; + private int ringCount = 3; + private boolean border = true; + private float borderSpeed = 1.0f; + private boolean accents = true; + private int accentStyle = 0; // AccentStyle ordinal + private boolean lightning = false; + private boolean particles = true; + private int particleMotion = 0; // ParticleMotion ordinal + private String particleDir = ""; + private int particleSize = 32; + private boolean particleGlow = true; + + // Lifetime + private long deathWorldTime = -1; + + // Effects + private List effects = new ArrayList<>(); + + // ═══════════════════════════════════════════════════════════════════ + // TRAP-SPECIFIC PROPERTIES + // ═══════════════════════════════════════════════════════════════════ + + private int armTime = 20; + private float triggerRadius = 2.0f; + private int maxTriggers = 1; + private int triggerCooldown = 20; + private float damage = 6.0f; + private float damageRadius = 0.0f; + private float knockback = 0.5f; + + // ═══════════════════════════════════════════════════════════════════ + // HAZARD-SPECIFIC PROPERTIES + // ═══════════════════════════════════════════════════════════════════ + + private float damagePerSecond = 1.0f; + private int damageInterval = 20; + private boolean ignoreInvulnFrames = false; + private boolean affectsCaster = false; + + // ═══════════════════════════════════════════════════════════════════ + // RUNTIME STATE (transient) + // ═══════════════════════════════════════════════════════════════════ + + // Trap runtime + private transient boolean armed = false; + private transient int triggerCount = 0; + private transient int ticksSinceLastTrigger = 0; + private transient Set triggeredEntities = new HashSet<>(); + private transient int triggerFlashTick = -1; // For visual flash on trigger + + // Hazard runtime + private transient int ticksSinceDamage = 0; + private transient Set damagedThisTick = new HashSet<>(); + + // Preview mode + private boolean previewMode = false; + private EntityLivingBase previewOwner = null; + + // ═══════════════════════════════════════════════════════════════════ + // CONSTRUCTORS + // ═══════════════════════════════════════════════════════════════════ + + public EntityAbilityZone(World world) { + super(world); + this.setSize(0.1f, 0.1f); + this.noClip = true; + this.isImmuneToFire = true; + this.ignoreFrustumCheck = true; + } + + /** + * Full constructor for creating a zone entity. + * Use the static factory methods for cleaner creation. + * Position is snapped to ground level with a tiny offset to avoid z-clipping. + */ + private EntityAbilityZone(World world, ZoneType type, EntityLivingBase owner, + double x, double y, double z) { + this(world); + this.zoneType = type; + this.ownerEntityId = owner.getEntityId(); + // Snap to ground with tiny offset to prevent z-clipping + double groundY = Ability.findGroundLevel(world, x, y, z) + GROUND_OFFSET; + this.setPosition(x, groundY, z); + } + + /** + * Create a Trap zone entity. + */ + public static EntityAbilityZone createTrap(World world, EntityLivingBase owner, + double x, double y, double z, + ZoneShape shape, + float triggerRadius, int armTime, int maxTriggers, + int triggerCooldown, float damage, float damageRadius, + float knockback, int durationTicks, + int innerColor, int outerColor, boolean outerColorEnabled, + float zoneHeight, + float particleDensity, float particleScale, + float animSpeed, float lightningDensity, + List effects) { + EntityAbilityZone zone = new EntityAbilityZone(world, ZoneType.TRAP, owner, x, y, z); + zone.shape = shape; + zone.radius = triggerRadius; + zone.triggerRadius = triggerRadius; + zone.armTime = armTime; + zone.maxTriggers = maxTriggers; + zone.triggerCooldown = triggerCooldown; + zone.damage = damage; + zone.damageRadius = damageRadius; + zone.knockback = knockback; + zone.durationTicks = durationTicks; + zone.maxTicks = durationTicks; + zone.innerColor = innerColor; + zone.outerColor = outerColor; + zone.outerColorEnabled = outerColorEnabled; + zone.zoneHeight = zoneHeight; + zone.particleDensity = particleDensity; + zone.particleScale = particleScale; + zone.animSpeed = animSpeed; + zone.lightningDensity = lightningDensity; + if (effects != null) { + for (AbilityEffect e : effects) { + zone.effects.add(e.copy()); + } + } + // Ready to trigger immediately after arm time + zone.ticksSinceLastTrigger = triggerCooldown; + return zone; + } + + /** + * Create a Hazard zone entity. + */ + public static EntityAbilityZone createHazard(World world, EntityLivingBase owner, + double x, double y, double z, + ZoneShape shape, + float radius, + float damagePerSecond, int damageInterval, + boolean ignoreInvulnFrames, boolean affectsCaster, + int durationTicks, + int innerColor, int outerColor, boolean outerColorEnabled, + float zoneHeight, + float particleDensity, float particleScale, + float animSpeed, float lightningDensity, + List effects) { + EntityAbilityZone zone = new EntityAbilityZone(world, ZoneType.HAZARD, owner, x, y, z); + zone.shape = shape; + zone.radius = radius; + zone.damagePerSecond = damagePerSecond; + zone.damageInterval = damageInterval; + zone.ignoreInvulnFrames = ignoreInvulnFrames; + zone.affectsCaster = affectsCaster; + zone.durationTicks = durationTicks; + zone.maxTicks = durationTicks; + zone.innerColor = innerColor; + zone.outerColor = outerColor; + zone.outerColorEnabled = outerColorEnabled; + zone.zoneHeight = zoneHeight; + zone.particleDensity = particleDensity; + zone.particleScale = particleScale; + zone.animSpeed = animSpeed; + zone.lightningDensity = lightningDensity; + if (effects != null) { + for (AbilityEffect e : effects) { + zone.effects.add(e.copy()); + } + } + // Ready to deal damage immediately + zone.ticksSinceDamage = damageInterval; + return zone; + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTITY LIFECYCLE + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void entityInit() { + // No DataWatcher needed + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + super.onUpdate(); + + // Set death time on first tick + if (deathWorldTime < 0 && worldObj != null) { + deathWorldTime = worldObj.getTotalWorldTime() + maxTicks; + } + + // Check lifetime + if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { + this.setDead(); + return; + } + + // Server handles damage + if (!worldObj.isRemote && !previewMode) { + switch (zoneType) { + case TRAP: + tickTrap(); + break; + case HAZARD: + tickHazard(); + break; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // TRAP LOGIC (server-only) + // ═══════════════════════════════════════════════════════════════════ + + private void tickTrap() { + // Arm time countdown + if (!armed) { + if (ticksExisted >= armTime) { + armed = true; + } + return; + } + + ticksSinceLastTrigger++; + + // All triggers used + if (maxTriggers > 0 && triggerCount >= maxTriggers) { + this.setDead(); + return; + } + + // Cooldown between triggers + if (ticksSinceLastTrigger < triggerCooldown) { + return; + } + + // Proximity detection + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + posX - triggerRadius, posY - 0.5, posZ - triggerRadius, + posX + triggerRadius, posY + zoneHeight, posZ + triggerRadius + ); + + Entity owner = getOwner(); + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); + + for (EntityLivingBase entity : entities) { + if (owner != null && entity == owner) continue; + if (entity.isDead) continue; + if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; + + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + + boolean inRange; + if (shape == ZoneShape.SQUARE) { + inRange = Math.abs(dx) <= triggerRadius && Math.abs(dz) <= triggerRadius; + } else { + double dist = Math.sqrt(dx * dx + dz * dz); + inRange = dist <= triggerRadius; + } + + if (inRange) { + triggerTrap(entity); + return; + } + } + } + + private void triggerTrap(EntityLivingBase triggerer) { + Entity owner = getOwner(); + Set affected = new HashSet<>(); + + if (damageRadius > 0) { + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + posX - damageRadius, posY - 0.5, posZ - damageRadius, + posX + damageRadius, posY + zoneHeight, posZ + damageRadius + ); + + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); + + for (EntityLivingBase entity : entities) { + if (owner != null && entity == owner) continue; + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + if (shape == ZoneShape.SQUARE) { + if (Math.abs(dx) <= damageRadius && Math.abs(dz) <= damageRadius) { + affected.add(entity); + } + } else { + double dist = Math.sqrt(dx * dx + dz * dz); + if (dist <= damageRadius) { + affected.add(entity); + } + } + } + } else { + affected.add(triggerer); + } + + boolean anyDamaged = false; + for (EntityLivingBase entity : affected) { + boolean hit = applyDamage(entity, owner, damage); + if (hit) { + anyDamaged = true; + } + + // Apply knockback only if damage landed + if (hit && knockback > 0) { + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + double len = Math.sqrt(dx * dx + dz * dz); + if (len > 0) { + entity.addVelocity((dx / len) * knockback * 0.5, 0.1, (dz / len) * knockback * 0.5); + entity.velocityChanged = true; + } + } + + // Apply effects only if damage landed + if (hit) { + applyEffects(entity); + } + } + + // Only count the trigger if at least one entity was actually damaged + if (anyDamaged) { + triggerCount++; + ticksSinceLastTrigger = 0; + triggeredEntities.add(triggerer.getUniqueID()); + triggerFlashTick = ticksExisted; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // HAZARD LOGIC (server-only) + // ═══════════════════════════════════════════════════════════════════ + + private void tickHazard() { + damagedThisTick.clear(); + ticksSinceDamage++; + + if (ticksSinceDamage < damageInterval) { + return; + } + ticksSinceDamage = 0; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - radius, posY - 0.5, posZ - radius, + posX + radius, posY + zoneHeight, posZ + radius + ); + + Entity owner = getOwner(); + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + + for (EntityLivingBase entity : entities) { + if (owner != null && entity == owner && !affectsCaster) continue; + if (damagedThisTick.contains(entity.getEntityId())) continue; + if (!isInZone(entity)) continue; + + if (damagePerSecond > 0) { + if (ignoreInvulnFrames) { + entity.hurtResistantTime = 0; + } + applyDamage(entity, owner, damagePerSecond); + } + + applyEffects(entity); + damagedThisTick.add(entity.getEntityId()); + } + } + + private boolean isInZone(EntityLivingBase entity) { + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + + switch (shape) { + case CIRCLE: + return Math.sqrt(dx * dx + dz * dz) <= radius; + case SQUARE: + return Math.abs(dx) <= radius && Math.abs(dz) <= radius; + default: + return Math.sqrt(dx * dx + dz * dz) <= radius; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // DAMAGE + // ═══════════════════════════════════════════════════════════════════ + + private boolean applyDamage(EntityLivingBase target, Entity owner, float dmg) { + if (dmg <= 0) return false; + + if (owner instanceof EntityNPCInterface) { + return target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg); + } else if (owner instanceof EntityPlayer) { + return target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg); + } else if (owner instanceof EntityLivingBase) { + return target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg); + } else { + return target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg); + } + } + + private void applyEffects(EntityLivingBase entity) { + if (entity == null || effects.isEmpty()) return; + for (AbilityEffect effect : effects) { + effect.apply(entity); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTITY HELPERS + // ═══════════════════════════════════════════════════════════════════ + + private Entity getOwner() { + if (previewMode && previewOwner != null) return previewOwner; + if (ownerEntityId == -1) return null; + return worldObj.getEntityByID(ownerEntityId); + } + + public void setupPreview(EntityLivingBase owner) { + this.previewMode = true; + this.previewOwner = owner; + } + + // ═══════════════════════════════════════════════════════════════════ + // RENDERING SUPPORT + // ═══════════════════════════════════════════════════════════════════ + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + return distance < 16384.0D; // 128 blocks + } + + @Override + public boolean shouldRenderInPass(int pass) { + return pass == 1; // Translucent pass + } + + @Override + public float getBrightness(float partialTicks) { + return 1.0f; + } + + @Override + @SideOnly(Side.CLIENT) + public int getBrightnessForRender(float partialTicks) { + return 0xF000F0; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS FOR RENDERER + // ═══════════════════════════════════════════════════════════════════ + + public ZoneType getZoneType() { return zoneType; } + public ZoneShape getShape() { return shape; } + public float getRadius() { return radius; } + public int getInnerColor() { return innerColor; } + public int getOuterColor() { return outerColor; } + public boolean isOuterColorEnabled() { return outerColorEnabled; } + public float getZoneHeight() { return zoneHeight; } + public boolean isArmed() { return armed || ticksExisted >= armTime; } + public int getTriggerFlashTick() { return triggerFlashTick; } + public int getDurationTicks() { return durationTicks; } + public int getMaxTicks() { return maxTicks; } + public float getParticleDensity() { return particleDensity; } + public float getParticleScale() { return particleScale; } + public float getAnimSpeed() { return animSpeed; } + public float getLightningDensity() { return lightningDensity; } + + // Visual layer getters + public boolean isGroundFill() { return groundFill; } + public float getGroundAlpha() { return groundAlpha; } + public boolean isRings() { return rings; } + public int getRingCount() { return ringCount; } + public boolean isBorder() { return border; } + public float getBorderSpeed() { return borderSpeed; } + public boolean isAccents() { return accents; } + public int getAccentStyle() { return accentStyle; } + public boolean isLightning() { return lightning; } + public boolean isParticles() { return particles; } + public int getParticleMotion() { return particleMotion; } + public String getParticleDir() { return particleDir; } + public int getParticleSize() { return particleSize; } + public boolean isParticleGlow() { return particleGlow; } + + /** + * Apply visual settings from ability data. + */ + public void applyVisual(boolean groundFill, float groundAlpha, + boolean rings, int ringCount, + boolean border, float borderSpeed, + boolean accents, int accentStyle, + boolean lightning, + boolean particles, int particleMotion, + String particleDir, int particleSize, boolean particleGlow) { + this.groundFill = groundFill; + this.groundAlpha = groundAlpha; + this.rings = rings; + this.ringCount = ringCount; + this.border = border; + this.borderSpeed = borderSpeed; + this.accents = accents; + this.accentStyle = accentStyle; + this.lightning = lightning; + this.particles = particles; + this.particleMotion = particleMotion; + this.particleDir = particleDir != null ? particleDir : ""; + this.particleSize = particleSize; + this.particleGlow = particleGlow; + } + + /** + * Apply preset defaults by old style name (for backward compatibility). + */ + private void applyPresetDefaults(String styleName) { + switch (styleName) { + case "TOXIC": + groundFill = true; groundAlpha = 0.30f; rings = true; ringCount = 3; + border = false; borderSpeed = 1.0f; accents = true; accentStyle = 1; + lightning = false; particles = true; particleMotion = 0; particleGlow = true; + break; + case "INFERNO": + groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; + border = true; borderSpeed = 2.0f; accents = true; accentStyle = 2; + lightning = false; particles = true; particleMotion = 0; particleGlow = true; + break; + case "ARCANE": + groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; + border = true; borderSpeed = 0.8f; accents = true; accentStyle = 0; + lightning = false; particles = true; particleMotion = 1; particleGlow = true; + break; + case "ELECTRIC": + groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; + border = false; borderSpeed = 1.0f; accents = false; accentStyle = 0; + lightning = true; particles = true; particleMotion = 2; particleGlow = true; + break; + case "FROST": + groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; + border = true; borderSpeed = 0.3f; accents = true; accentStyle = 0; + lightning = false; particles = true; particleMotion = 1; particleGlow = true; + break; + default: // DEFAULT + groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; + border = true; borderSpeed = 1.0f; accents = true; accentStyle = 0; + lightning = false; particles = false; particleMotion = 0; particleGlow = true; + break; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void readEntityFromNBT(NBTTagCompound nbt) { + this.zoneType = ZoneType.values()[nbt.getInteger("ZoneType")]; + + // Shape: read new string key first, fall back to old ordinal (always CIRCLE for old RING/CONE) + if (nbt.hasKey("ShapeName")) { + try { + this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); + } catch (Exception e) { + this.shape = ZoneShape.CIRCLE; + } + } else { + // Legacy: old ordinal data — RING(1) and CONE(2) map to CIRCLE + this.shape = ZoneShape.CIRCLE; + } + + this.ownerEntityId = nbt.getInteger("OwnerId"); + this.radius = nbt.getFloat("Radius"); + this.durationTicks = nbt.getInteger("Duration"); + this.maxTicks = nbt.getInteger("MaxTicks"); + this.innerColor = nbt.getInteger("InnerColor"); + this.outerColor = nbt.getInteger("OuterColor"); + this.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.hasKey("DeathWorldTime") ? nbt.getLong("DeathWorldTime") : -1; + + // Visual fields — backward compat with old ZoneStyle format + if (nbt.hasKey("ZoneStyle")) { + // OLD FORMAT: apply preset defaults, then overlay CustomVisual + applyPresetDefaults(nbt.getString("ZoneStyle")); + if (nbt.hasKey("CustomVisual")) { + NBTTagCompound cv = nbt.getCompoundTag("CustomVisual"); + this.groundFill = !cv.hasKey("GroundFill") || cv.getBoolean("GroundFill"); + this.groundAlpha = cv.hasKey("GroundAlpha") ? cv.getFloat("GroundAlpha") : 0.25f; + this.rings = !cv.hasKey("Rings") || cv.getBoolean("Rings"); + this.ringCount = cv.hasKey("RingCount") ? cv.getInteger("RingCount") : 3; + this.border = !cv.hasKey("Border") || cv.getBoolean("Border"); + this.borderSpeed = cv.hasKey("BorderSpeed") ? cv.getFloat("BorderSpeed") : 1.0f; + this.accents = !cv.hasKey("Accents") || cv.getBoolean("Accents"); + this.accentStyle = cv.hasKey("AccentStyle") ? cv.getInteger("AccentStyle") : 0; + this.lightning = cv.hasKey("Lightning") && cv.getBoolean("Lightning"); + this.particles = !cv.hasKey("Particles") || cv.getBoolean("Particles"); + this.particleMotion = cv.hasKey("ParticleMotion") ? cv.getInteger("ParticleMotion") : 0; + this.particleDir = cv.hasKey("ParticleDir") ? cv.getString("ParticleDir") : ""; + this.particleSize = cv.hasKey("ParticleSize") ? cv.getInteger("ParticleSize") : 32; + this.particleGlow = !cv.hasKey("ParticleGlow") || cv.getBoolean("ParticleGlow"); + } + } else { + // NEW FORMAT: read individual top-level keys + this.groundFill = !nbt.hasKey("GroundFill") || nbt.getBoolean("GroundFill"); + this.groundAlpha = nbt.hasKey("GroundAlpha") ? nbt.getFloat("GroundAlpha") : 0.25f; + this.rings = !nbt.hasKey("Rings") || nbt.getBoolean("Rings"); + this.ringCount = nbt.hasKey("RingCount") ? nbt.getInteger("RingCount") : 3; + this.border = !nbt.hasKey("Border") || nbt.getBoolean("Border"); + this.borderSpeed = nbt.hasKey("BorderSpeed") ? nbt.getFloat("BorderSpeed") : 1.0f; + this.accents = !nbt.hasKey("Accents") || nbt.getBoolean("Accents"); + this.accentStyle = nbt.hasKey("AccentStyle") ? nbt.getInteger("AccentStyle") : 0; + this.lightning = nbt.hasKey("Lightning") && nbt.getBoolean("Lightning"); + this.particles = !nbt.hasKey("Particles") || nbt.getBoolean("Particles"); + this.particleMotion = nbt.hasKey("ParticleMotion") ? nbt.getInteger("ParticleMotion") : 0; + this.particleDir = nbt.hasKey("ParticleDir") ? nbt.getString("ParticleDir") : ""; + this.particleSize = nbt.hasKey("ParticleSize") ? nbt.getInteger("ParticleSize") : 32; + this.particleGlow = !nbt.hasKey("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"); + + // Hazard + this.damagePerSecond = nbt.getFloat("DamagePerSecond"); + this.damageInterval = nbt.getInteger("DamageInterval"); + 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++) { + AbilityEffect effect = AbilityEffect.fromNBT(effectList.getCompoundTagAt(i)); + if (effect != null && effect.isValid()) { + effects.add(effect); + } + } + } + } + + @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 fields — always written as top-level keys + 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); + + // Hazard + nbt.setFloat("DamagePerSecond", damagePerSecond); + nbt.setInteger("DamageInterval", damageInterval); + nbt.setBoolean("IgnoreInvuln", ignoreInvulnFrames); + nbt.setBoolean("AffectsCaster", affectsCaster); + + // Effects + NBTTagList effectList = new NBTTagList(); + for (AbilityEffect effect : effects) { + effectList.appendTag(effect.writeNBT()); + } + nbt.setTag("Effects", effectList); + } + + // ═══════════════════════════════════════════════════════════════════ + // SPAWN DATA (ByteBuf for client sync) + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void writeSpawnData(ByteBuf buffer) { + buffer.writeInt(zoneType.ordinal()); + ByteBufUtils.writeUTF8String(buffer, shape.name()); + buffer.writeInt(ownerEntityId); + buffer.writeFloat(radius); + buffer.writeInt(durationTicks); + buffer.writeInt(maxTicks); + buffer.writeInt(innerColor); + buffer.writeInt(outerColor); + buffer.writeBoolean(outerColorEnabled); + buffer.writeFloat(zoneHeight); + buffer.writeFloat(particleDensity); + buffer.writeFloat(particleScale); + buffer.writeFloat(animSpeed); + buffer.writeFloat(lightningDensity); + + // Visual fields — always written individually + buffer.writeBoolean(groundFill); + buffer.writeFloat(groundAlpha); + buffer.writeBoolean(rings); + buffer.writeInt(ringCount); + buffer.writeBoolean(border); + buffer.writeFloat(borderSpeed); + buffer.writeBoolean(accents); + buffer.writeInt(accentStyle); + buffer.writeBoolean(lightning); + buffer.writeBoolean(particles); + buffer.writeInt(particleMotion); + ByteBufUtils.writeUTF8String(buffer, particleDir); + buffer.writeInt(particleSize); + buffer.writeBoolean(particleGlow); + + // Trap-specific (client needs armTime for visual state) + buffer.writeInt(armTime); + + // Effects via NBT in buffer + NBTTagCompound effectsNbt = new NBTTagCompound(); + NBTTagList effectList = new NBTTagList(); + for (AbilityEffect effect : effects) { + effectList.appendTag(effect.writeNBT()); + } + effectsNbt.setTag("Effects", effectList); + ByteBufUtils.writeTag(buffer, effectsNbt); + } + + @Override + public void readSpawnData(ByteBuf buffer) { + this.zoneType = ZoneType.values()[buffer.readInt()]; + String shapeName = ByteBufUtils.readUTF8String(buffer); + try { + this.shape = ZoneShape.valueOf(shapeName); + } catch (Exception e) { + this.shape = ZoneShape.CIRCLE; + } + this.ownerEntityId = buffer.readInt(); + this.radius = buffer.readFloat(); + this.durationTicks = buffer.readInt(); + this.maxTicks = buffer.readInt(); + this.innerColor = buffer.readInt(); + this.outerColor = buffer.readInt(); + this.outerColorEnabled = buffer.readBoolean(); + this.zoneHeight = buffer.readFloat(); + this.particleDensity = buffer.readFloat(); + this.particleScale = buffer.readFloat(); + this.animSpeed = buffer.readFloat(); + this.lightningDensity = buffer.readFloat(); + + // Visual fields — always read individually + this.groundFill = buffer.readBoolean(); + this.groundAlpha = buffer.readFloat(); + this.rings = buffer.readBoolean(); + this.ringCount = buffer.readInt(); + this.border = buffer.readBoolean(); + this.borderSpeed = buffer.readFloat(); + this.accents = buffer.readBoolean(); + this.accentStyle = buffer.readInt(); + this.lightning = buffer.readBoolean(); + this.particles = buffer.readBoolean(); + this.particleMotion = buffer.readInt(); + this.particleDir = ByteBufUtils.readUTF8String(buffer); + this.particleSize = buffer.readInt(); + this.particleGlow = buffer.readBoolean(); + + this.armTime = buffer.readInt(); + + // Effects via NBT + NBTTagCompound effectsNbt = ByteBufUtils.readTag(buffer); + effects.clear(); + if (effectsNbt != null && effectsNbt.hasKey("Effects")) { + NBTTagList effectList = effectsNbt.getTagList("Effects", 10); + for (int i = 0; i < effectList.tagCount(); i++) { + AbilityEffect effect = AbilityEffect.fromNBT(effectList.getCompoundTagAt(i)); + if (effect != null && effect.isValid()) { + effects.add(effect); + } + } + } + } +} diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 0bc081429..933450557 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -91,6 +91,7 @@ import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityAbilityZone; import noppes.npcs.entity.old.EntityNPCDwarfFemale; import noppes.npcs.entity.old.EntityNPCDwarfMale; import noppes.npcs.entity.old.EntityNPCElfFemale; @@ -292,6 +293,7 @@ public class CustomNpcs { registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 3, true); registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 3, true); registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true); + registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true); new RecipeController(); diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index 4331ab0ea..2970d835a 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -151,12 +151,14 @@ import kamkeel.npcs.client.renderer.RenderAbilityDisc; import kamkeel.npcs.client.renderer.RenderAbilityLaser; import kamkeel.npcs.client.renderer.RenderAbilityBeam; import kamkeel.npcs.client.renderer.RenderAbilitySweeper; +import kamkeel.npcs.client.renderer.RenderAbilityZone; import kamkeel.npcs.client.renderer.lightning.LightningHandler; import kamkeel.npcs.entity.EntityAbilityOrb; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityAbilityZone; import noppes.npcs.client.renderer.blocks.BlockBannerRenderer; import noppes.npcs.client.renderer.blocks.BlockBarrelRenderer; import noppes.npcs.client.renderer.blocks.BlockBeamRenderer; @@ -270,6 +272,7 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone()); RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc()); diff --git a/src/main/java/noppes/npcs/client/fx/CustomFX.java b/src/main/java/noppes/npcs/client/fx/CustomFX.java index 7a296d8e8..79d5f452c 100644 --- a/src/main/java/noppes/npcs/client/fx/CustomFX.java +++ b/src/main/java/noppes/npcs/client/fx/CustomFX.java @@ -84,6 +84,10 @@ public class CustomFX extends EntityFX { this.imageData = ClientCacheHandler.getImageData(this.directory); } + public void setMaxAge(int age) { + this.particleMaxAge = age; + } + public static CustomFX fromScriptedParticle(ScriptParticle particle, World worldObj, Entity entity) { EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; if (entity == player) { diff --git a/src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java b/src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java new file mode 100644 index 000000000..80f6f687b --- /dev/null +++ b/src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java @@ -0,0 +1,65 @@ +package noppes.npcs.client.fx; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.world.World; + +/** + * Simple particle for zone visual effects (Trap/Hazard styles). + * Uses vanilla particle atlas with color tinting. Fades out over lifetime. + */ +@SideOnly(Side.CLIENT) +public class ZoneParticleFX extends EntityFX { + + private final float startAlpha; + private final boolean glow; + + public ZoneParticleFX(World world, double x, double y, double z, + double motionX, double motionY, double motionZ, + float r, float g, float b, float alpha, + float scale, int maxAge, float gravity, boolean glow) { + super(world, x, y, z, 0, 0, 0); + this.motionX = motionX; + this.motionY = motionY; + this.motionZ = motionZ; + this.particleRed = r; + this.particleGreen = g; + this.particleBlue = b; + this.particleAlpha = alpha; + this.startAlpha = alpha; + this.particleScale = scale; + this.particleMaxAge = maxAge; + this.particleGravity = gravity; + this.glow = glow; + this.noClip = true; + this.setParticleTextureIndex(0); + } + + @Override + public int getBrightnessForRender(float partialTick) { + return glow ? 0xF000F0 : super.getBrightnessForRender(partialTick); + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + if (this.particleAge++ >= this.particleMaxAge) { + this.setDead(); + return; + } + + // Linear fade out + float lifeRatio = (float) this.particleAge / (float) this.particleMaxAge; + this.particleAlpha = this.startAlpha * (1.0f - lifeRatio); + + // Movement + this.motionY -= 0.04D * (double) this.particleGravity; + this.posX += this.motionX; + this.posY += this.motionY; + this.posZ += this.motionZ; + } +} diff --git a/src/main/java/noppes/npcs/client/renderer/ImageData.java b/src/main/java/noppes/npcs/client/renderer/ImageData.java index 15c383e40..8e6f651c5 100644 --- a/src/main/java/noppes/npcs/client/renderer/ImageData.java +++ b/src/main/java/noppes/npcs/client/renderer/ImageData.java @@ -25,7 +25,7 @@ public class ImageData { public ImageData(String directory) { this.location = new ResourceLocation(directory); - if (directory.startsWith("https://")) { + if (directory.startsWith("https://") || directory.startsWith("http://")) { this.isUrl = true; TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); this.imageDownloadAlt = new ImageDownloadAlt(null, directory, new ResourceLocation("customnpcs:textures/gui/invisible.png"), new ImageBufferDownloadAlt(true, false)); diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 9319f1b36..408136c34 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1563,10 +1563,46 @@ ability.dash.defensive=Defensive ability.counter.flat=Flat ability.counter.percent=Percent -# Hazard Shape +# Zone Shape ability.shape.circle=Circle +ability.shape.square=Square ability.shape.ring=Ring ability.shape.cone=Cone +ability.zoneShape=Shape + +# Zone Presets +ability.preset.custom=Custom +ability.preset.default=Default +ability.preset.toxic=Toxic +ability.preset.inferno=Inferno +ability.preset.arcane=Arcane +ability.preset.electric=Electric +ability.preset.frost=Frost + +# Accent Styles +ability.accentStyle.static=Static +ability.accentStyle.swaying=Swaying +ability.accentStyle.flickering=Flickering + +# Particle Motion Styles +ability.particleMotion.rising=Rising +ability.particleMotion.drifting=Drifting +ability.particleMotion.sparks=Sparks + +# Zone Settings +ability.section.zone=Zone Placement +ability.telegraphSize=Telegraph Size +ability.coneAngle=Cone Angle +ability.ignoreInvulnFrames=Ignore Invuln Frames +ability.visible=Visible + +# Visual Layer Section Headers +ability.section.ground=Ground Fill +ability.section.rings=Rings +ability.section.border=Border +ability.section.accents=Accents +ability.section.lightning=Lightning +ability.section.particles=Particles # Placement Mode ability.placement.atCaster=At Caster @@ -1662,6 +1698,7 @@ ability.section.timing=Timing ability.section.movement=Movement ability.section.sounds=Sounds ability.section.animations=Animations +ability.section.animation=Animation ability.section.telegraph=Telegraph ability.section.beam=Beam ability.section.sweep=Sweep @@ -1711,6 +1748,19 @@ gui.animation=Animation gui.duration=Duration gui.amp=Amp gui.speed=Speed +gui.size=Size +gui.alpha=Alpha +gui.count=Count +gui.style=Style +gui.scale=Scale +gui.motion=Motion +gui.glow=Glow +gui.texture=Texture +gui.dps=DPS +gui.interval=Interval +gui.cooldown=Cooldown +gui.max=Max +gui.preset=Preset # Common Type Settings ability.radius=Radius @@ -1793,7 +1843,6 @@ ability.healAllies=Heal Allies # Hazard ability.shape=Shape ability.placement=Placement -ability.damagePerSecond=Damage/Sec ability.damageInterval=Damage Interval ability.slownessLevel=Slowness Level ability.debuffDuration=Debuff Duration @@ -1802,8 +1851,6 @@ ability.affectsCaster=Affects Caster # Trap ability.armTime=Arm Time -ability.maxTriggers=Max Triggers -ability.triggerCooldown=Trigger Cooldown # Sweeper ability.sweepSpeed=Sweep Speed @@ -1826,7 +1873,6 @@ ability.outerEnabled=Outer Glow ability.outerWidth=Outer Width ability.outerAlpha=Outer Alpha ability.lightning=Lightning -ability.lightningDensity=Density ability.lightningRadius=Radius # Projectile Count / Settings @@ -1930,7 +1976,6 @@ ability.hover.placement=Where the ability effect is placed (Caster, Target, etc. ability.hover.lockTarget=Sweeper beam tracks the target's position ability.hover.canCounter=Enable counterattack when blocking damage ability.hover.counterType=Flat = fixed damage, Percent = % of blocked damage -ability.hover.shape=Shape of the hazard zone (Circle, Ring, Cone) ability.hover.affectsCaster=Hazard can damage the NPC that created it ability.hover.sweepMode=Swipe = single arc attack, Spin = continuous rotation From 64ba087cc5d2d9281e5228b6fc0d17c5d927adf1 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 14:07:03 -0500 Subject: [PATCH 29/76] Merge Conflict Compile Issues --- .../data/ability/type/AbilityHazard.java | 56 ------------------- 1 file changed, 56 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 89dd8b00d..35397371b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -38,8 +38,6 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { this.typeId = "ability.cnpc.hazard"; this.name = "Hazard"; this.windUpTicks = 30; - this.telegraphType = TelegraphType.CIRCLE; - this.allowedBy = UserType.NPC_ONLY; this.windUpAnimationName = "Ability_Hazard_Windup"; this.activeAnimationName = "Ability_Hazard_Active"; } @@ -49,60 +47,6 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { return radius; } - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - TelegraphInstance instance = super.createTelegraph(caster, target); - if (instance == null) return null; - - // Control telegraph following based on placement mode - switch (placement) { - case AT_CASTER: - case FOLLOW_CASTER: - // Telegraph stays at caster position, no following - instance.setEntityIdToFollow(-1); - instance.setX(caster.posX); - instance.setY(caster.posY); - instance.setZ(caster.posZ); - break; - case AT_TARGET: - // Telegraph follows target during windup, locks on execute - if (target != null) { - instance.setEntityIdToFollow(target.getEntityId()); - } - break; - case FOLLOW_TARGET: - // Telegraph follows target during windup AND active phase - if (target != null) { - instance.setEntityIdToFollow(target.getEntityId()); - } - break; - } - return instance; - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // AT_CASTER locks immediately, AT_TARGET follows during windup and locks on execute - if (tick == 0) { - switch (placement) { - case AT_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - positionLocked = true; - break; - case AT_TARGET: - // Position will be set from telegraph on execute - // Telegraph follows target during windup - positionLocked = false; - break; - default: - positionLocked = false; - break; - } - } - } - @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { if (world.isRemote && !isPreview()) { From 2d3106a2562b2e389499915abb342236433a1dab Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 15:01:19 -0500 Subject: [PATCH 30/76] Fix Zone Defaults --- src/api | 2 +- .../client/renderer/TelegraphRenderer.java | 30 ++++ .../controllers/data/ability/Ability.java | 32 +++-- .../data/ability/type/AbilityBeam.java | 62 +++----- .../data/ability/type/AbilityDisc.java | 67 +++------ .../data/ability/type/AbilityHazard.java | 50 +++---- .../data/ability/type/AbilityOrb.java | 74 +++------- .../data/ability/type/AbilityTeleport.java | 9 -- .../data/ability/type/AbilityTrap.java | 30 +++- .../data/ability/type/AbilityZone.java | 136 +++++++++--------- .../controllers/data/telegraph/Telegraph.java | 6 + .../data/telegraph/TelegraphType.java | 5 + src/main/java/noppes/npcs/DataAbilities.java | 26 ++-- .../controllers/data/PlayerAbilityData.java | 21 +-- 14 files changed, 253 insertions(+), 297 deletions(-) diff --git a/src/api b/src/api index 092b18fe9..456bb2cbf 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 092b18fe95d57353d16960411e5289ac3bbfa6ef +Subproject commit 456bb2cbfa7456d114bfc22caf49020353282e07 diff --git a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java index 3b5e49e2d..78ba58aed 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java @@ -110,6 +110,9 @@ public class TelegraphRenderer { case POINT: renderPoint(red, green, blue, alpha); break; + case SQUARE: + renderSquare(telegraph.getRadius(), red, green, blue, alpha); + break; default: break; } @@ -258,6 +261,30 @@ public class TelegraphRenderer { tessellator.draw(); } + private void renderSquare(float radius, float r, float g, float b, float a) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(r, g, b, a); + + tessellator.addVertex(-radius, 0, -radius); + tessellator.addVertex(radius, 0, -radius); + tessellator.addVertex(radius, 0, radius); + tessellator.addVertex(-radius, 0, radius); + + tessellator.draw(); + + // Draw border + tessellator.startDrawing(GL11.GL_LINE_LOOP); + tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2)); + + tessellator.addVertex(-radius, 0.01, -radius); + tessellator.addVertex(radius, 0.01, -radius); + tessellator.addVertex(radius, 0.01, radius); + tessellator.addVertex(-radius, 0.01, radius); + + tessellator.draw(); + } + // ==================== GUI PREVIEW RENDERING ==================== /** @@ -322,6 +349,9 @@ public class TelegraphRenderer { case POINT: renderPoint(red, green, blue, alpha); break; + case SQUARE: + renderSquare(telegraph.getRadius(), red, green, blue, alpha); + break; default: break; } 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 b95879c3b..2dd86a4b4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -117,7 +117,7 @@ public abstract class Ability implements IAbility { protected transient int currentTick = 0; protected transient EntityLivingBase currentTarget; protected transient long executionStartTime; - protected transient TelegraphInstance telegraphInstance; + protected transient List telegraphInstances = new ArrayList<>(); // Burst execution state protected transient int burstIndex = 0; @@ -682,6 +682,9 @@ public abstract class Ability implements IAbility { case POINT: telegraph = new Telegraph("", TelegraphType.POINT); break; + case SQUARE: + telegraph = Telegraph.square(getTelegraphRadius()); + break; default: return null; } @@ -716,6 +719,17 @@ public abstract class Ability implements IAbility { return instance; } + /** + * Create all telegraph instances for this ability. + * Override for abilities that need multiple telegraphs (e.g., zone abilities). + * Default wraps createTelegraph() in a singleton list. + */ + public List createTelegraphs(EntityLivingBase caster, EntityLivingBase target) { + TelegraphInstance instance = createTelegraph(caster, target); + if (instance == null) return new ArrayList<>(); + return new ArrayList<>(Collections.singletonList(instance)); + } + /** * Find the ground level at a given position. * Searches downward from the given Y to find a solid block. @@ -784,17 +798,17 @@ public abstract class Ability implements IAbility { } /** - * Get the current telegraph instance. + * Get the current telegraph instances. */ - public TelegraphInstance getTelegraphInstance() { - return telegraphInstance; + public List getTelegraphInstances() { + return telegraphInstances; } /** - * Set the telegraph instance (called by DataAbilities). + * Set the telegraph instances (called by DataAbilities). */ - public void setTelegraphInstance(TelegraphInstance instance) { - this.telegraphInstance = instance; + public void setTelegraphInstances(List instances) { + this.telegraphInstances = instances != null ? instances : new ArrayList<>(); } // ═══════════════════════════════════════════════════════════════════ @@ -918,7 +932,7 @@ public abstract class Ability implements IAbility { } burstIndex = 0; currentTarget = null; - telegraphInstance = null; + telegraphInstances.clear(); } /** @@ -970,7 +984,7 @@ public abstract class Ability implements IAbility { currentTick = 0; burstIndex = 0; currentTarget = null; - telegraphInstance = null; + telegraphInstances.clear(); previewMode = false; previewEntityHandler = null; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index f99a03528..8bf2341f5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -118,8 +118,9 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { this.fireDelay = Math.max(0, delay); } - // Legacy compat + /** @deprecated Use {@link #getFireDelay()} */ public int getDualFireDelay() { return fireDelay; } + /** @deprecated Use {@link #setFireDelay(int)} */ public void setDualFireDelay(int delay) { setFireDelay(delay); } @Override @@ -225,8 +226,13 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { for (EntityAbilityBeam beam : beamEntities) { spawnAbilityEntity(world, beam); } - for (EntityAbilityBeam beam : beamEntities) { - fireBeamEntity(beam, target); + + // Fire first projectile immediately, let onActiveTick handle the rest with fireDelay + fireBeamEntity(beamEntities[0], target); + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireBeamEntity(beamEntities[i], target); + } } } @@ -356,55 +362,21 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; initProjectiles(count); - if (nbt.hasKey("fireDelay")) { - this.fireDelay = nbt.getInteger("fireDelay"); - } else if (nbt.hasKey("dualFireDelay")) { - this.fireDelay = nbt.getInteger("dualFireDelay"); - } else { - this.fireDelay = 0; - } + this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; combatData.readNBT(nbt); homingData.readNBT(nbt); lifespanData.readNBT(nbt); - if (nbt.hasKey("Projectile_0")) { - NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); - if (proj0.hasKey("colorOverride")) { - // NEW format - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } - } else { - // OLD per-projectile format - displayData.readNBT(proj0); - lightningData.readNBT(proj0); - projectiles[0].anchor.readNBT(proj0); + // Shared visual data + displayData.readNBT(nbt); + lightningData.readNBT(nbt); - for (int i = 1; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); - projectiles[i].anchor.readNBT(projNbt); - - EnergyDisplayData tempDisplay = new EnergyDisplayData(); - tempDisplay.readNBT(projNbt); - if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { - projectiles[i].colorOverride = true; - projectiles[i].innerColor = tempDisplay.innerColor; - projectiles[i].outerColor = tempDisplay.outerColor; - } - } - } + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); } - } else { - // LEGACY flat format - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - projectiles[0].anchor.readNBT(nbt); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index f890b7d7b..886a269e2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -124,8 +124,9 @@ public class AbilityDisc extends Ability implements IAbilityDisc { this.fireDelay = Math.max(0, delay); } - // Legacy compat + /** @deprecated Use {@link #getFireDelay()} */ public int getDualFireDelay() { return fireDelay; } + /** @deprecated Use {@link #setFireDelay(int)} */ public void setDualFireDelay(int delay) { setFireDelay(delay); } @Override @@ -228,8 +229,13 @@ public class AbilityDisc extends Ability implements IAbilityDisc { for (EntityAbilityDisc disc : discEntities) { spawnAbilityEntity(world, disc); } - for (EntityAbilityDisc disc : discEntities) { - fireDiscEntity(disc, target); + + // Fire first projectile immediately, let onActiveTick handle the rest with fireDelay + fireDiscEntity(discEntities[0], target); + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireDiscEntity(discEntities[i], target); + } } } @@ -371,61 +377,22 @@ public class AbilityDisc extends Ability implements IAbilityDisc { int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; initProjectiles(count); - // Read fireDelay with fallback to old dualFireDelay key - if (nbt.hasKey("fireDelay")) { - this.fireDelay = nbt.getInteger("fireDelay"); - } else if (nbt.hasKey("dualFireDelay")) { - this.fireDelay = nbt.getInteger("dualFireDelay"); - } else { - this.fireDelay = 0; - } + this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; // Shared combat/movement data combatData.readNBT(nbt); homingData.readNBT(nbt); lifespanData.readNBT(nbt); - // Determine format and read accordingly - if (nbt.hasKey("Projectile_0")) { - NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); - if (proj0.hasKey("colorOverride")) { - // NEW format: shared visuals at root + ProjectileData per projectile - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } - } else { - // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) - // Read primary visuals from Projectile_0 - displayData.readNBT(proj0); - lightningData.readNBT(proj0); - projectiles[0].anchor.readNBT(proj0); + // Shared visual data + displayData.readNBT(nbt); + lightningData.readNBT(nbt); - // Read remaining projectiles, set color override if colors differ - for (int i = 1; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); - projectiles[i].anchor.readNBT(projNbt); - - // Check if this projectile had different colors - EnergyDisplayData tempDisplay = new EnergyDisplayData(); - tempDisplay.readNBT(projNbt); - if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { - projectiles[i].colorOverride = true; - projectiles[i].innerColor = tempDisplay.innerColor; - projectiles[i].outerColor = tempDisplay.outerColor; - } - } - } + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); } - } else { - // LEGACY flat format: all data at root level - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - projectiles[0].anchor.readNBT(nbt); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 35397371b..551fbe9cc 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -27,14 +27,14 @@ import java.util.List; public class AbilityHazard extends AbilityZone implements IAbilityHazard { // Hazard-specific fields - private float radius = 4.0f; + private float radius = 2.0f; private float damagePerSecond = 1.0f; private int damageInterval = 20; private boolean ignoreInvulnFrames = false; private boolean affectsCaster = false; public AbilityHazard() { - super(100, new EnergyDisplayData(0x00CC00, 0x006600, true, 1.0f, 0.5f, 1.5f)); + super(300, new EnergyDisplayData(0x00CC00, 0x006600, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.hazard"; this.name = "Hazard"; this.windUpTicks = 30; @@ -43,7 +43,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { } @Override - public float getTelegraphRadius() { + public float getZoneRadius() { return radius; } @@ -56,12 +56,24 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { activeEntities.clear(); - List placedPositions = new ArrayList<>(); - float minSeparation = radius * 2.0f; + // Use pre-calculated positions from telegraph phase, or generate new ones + List positions; + if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { + positions = new ArrayList<>(preCalculatedPositions); + preCalculatedPositions.clear(); + } else { + positions = new ArrayList<>(); + List placedPositions = new ArrayList<>(); + float minSeparation = radius * 2.0f; + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + positions.add(pos); + } + } for (int i = 0; i < zoneCount; i++) { - double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); - placedPositions.add(pos); + double[] pos = positions.get(i); EntityAbilityZone entity = EntityAbilityZone.createHazard(world, caster, pos[0], caster.posY, pos[1], @@ -102,26 +114,9 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { @Override public void readTypeNBT(NBTTagCompound nbt) { - readZoneNBT(nbt, 100); - - // Backward compat: old "shape" key with RING/CONE → ignore (base defaults to CIRCLE) - // The old HazardShape enum had CIRCLE/RING/CONE — only CIRCLE maps to new ZoneShape - if (nbt.hasKey("shape")) { - String oldShape = nbt.getString("shape"); - if ("RING".equals(oldShape) || "CONE".equals(oldShape)) { - this.zoneShape = ZoneShape.CIRCLE; - } - } - - this.radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 4.0f; - // Support legacy "damagePerTick" key for backwards compatibility - if (nbt.hasKey("damagePerSecond")) { - this.damagePerSecond = nbt.getFloat("damagePerSecond"); - } else if (nbt.hasKey("damagePerTick")) { - this.damagePerSecond = nbt.getFloat("damagePerTick"); - } else { - this.damagePerSecond = 1.0f; - } + readZoneNBT(nbt, 300); + this.radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 2.0f; + this.damagePerSecond = nbt.hasKey("damagePerSecond") ? nbt.getFloat("damagePerSecond") : 1.0f; this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 20; this.ignoreInvulnFrames = nbt.hasKey("ignoreInvulnFrames") && nbt.getBoolean("ignoreInvulnFrames"); this.affectsCaster = nbt.hasKey("affectsCaster") && nbt.getBoolean("affectsCaster"); @@ -178,6 +173,5 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { )); addVisualFieldDefs(defs); - addTelegraphSizeField(defs); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index c4a4a1ebb..8b4783f7c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -115,8 +115,9 @@ public class AbilityOrb extends Ability implements IAbilityOrb { this.fireDelay = Math.max(0, delay); } - // Legacy compat + /** @deprecated Use {@link #getFireDelay()} */ public int getDualFireDelay() { return fireDelay; } + /** @deprecated Use {@link #setFireDelay(int)} */ public void setDualFireDelay(int delay) { setFireDelay(delay); } @Override @@ -229,8 +230,13 @@ public class AbilityOrb extends Ability implements IAbilityOrb { for (EntityAbilityOrb orb : orbEntities) { spawnAbilityEntity(world, orb); } - for (EntityAbilityOrb orb : orbEntities) { - fireOrbEntity(orb, target); + + // Fire first projectile immediately, let onActiveTick handle the rest with fireDelay + fireOrbEntity(orbEntities[0], target); + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireOrbEntity(orbEntities[i], target); + } } } @@ -354,8 +360,6 @@ public class AbilityOrb extends Ability implements IAbilityOrb { nbt.setTag("Projectile_" + i, projNbt); } - // Backward compat write - nbt.setFloat("orbSpeed", homingData.speed); } @Override @@ -365,66 +369,22 @@ public class AbilityOrb extends Ability implements IAbilityOrb { int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; initProjectiles(count); - // Read fireDelay with fallback to old dualFireDelay key - if (nbt.hasKey("fireDelay")) { - this.fireDelay = nbt.getInteger("fireDelay"); - } else if (nbt.hasKey("dualFireDelay")) { - this.fireDelay = nbt.getInteger("dualFireDelay"); - } else { - this.fireDelay = 0; - } + this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; // Shared combat/movement data combatData.readNBT(nbt); homingData.readNBT(nbt); lifespanData.readNBT(nbt); - // Determine format and read accordingly - if (nbt.hasKey("Projectile_0")) { - NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); - if (proj0.hasKey("colorOverride")) { - // NEW format: shared visuals at root + ProjectileData per projectile - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } - } else { - // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) - // Read primary visuals from Projectile_0 - displayData.readNBT(proj0); - lightningData.readNBT(proj0); - projectiles[0].anchor.readNBT(proj0); + // Shared visual data + displayData.readNBT(nbt); + lightningData.readNBT(nbt); - // Read remaining projectiles, set color override if colors differ - for (int i = 1; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); - projectiles[i].anchor.readNBT(projNbt); - - // Check if this projectile had different colors - EnergyDisplayData tempDisplay = new EnergyDisplayData(); - tempDisplay.readNBT(projNbt); - if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { - projectiles[i].colorOverride = true; - projectiles[i].innerColor = tempDisplay.innerColor; - projectiles[i].outerColor = tempDisplay.outerColor; - } - } - } + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); } - } else { - // LEGACY flat format: all data at root level - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - projectiles[0].anchor.readNBT(nbt); - } - - // Backward compat - if (nbt.hasKey("orbSpeed")) { - homingData.speed = nbt.getFloat("orbSpeed"); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index 8e09c43e7..4b19bc91d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -441,15 +441,6 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } catch (Exception e) { this.mode = TeleportMode.BLINK; } - } else if (nbt.hasKey("pattern")) { - String legacy = nbt.getString("pattern"); - if ("BEHIND_TARGET".equals(legacy)) { - this.mode = TeleportMode.BEHIND; - } else if ("RANDOM".equals(legacy)) { - this.mode = TeleportMode.BLINK; - } else { - this.mode = TeleportMode.SINGLE; - } } else { this.mode = TeleportMode.BLINK; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 173efa0de..b296fa8bc 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -37,12 +37,17 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { private boolean visible = true; public AbilityTrap() { - super(200, new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.0f, 0.5f, 1.5f)); + super(300, new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.trap"; this.name = "Trap"; this.windUpTicks = 20; } + @Override + public float getZoneRadius() { + return triggerRadius; + } + @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { if (world.isRemote && !isPreview()) { @@ -52,12 +57,24 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { activeEntities.clear(); - List placedPositions = new ArrayList<>(); - float minSeparation = triggerRadius * 2.0f; + // Use pre-calculated positions from telegraph phase, or generate new ones + List positions; + if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { + positions = new ArrayList<>(preCalculatedPositions); + preCalculatedPositions.clear(); + } else { + positions = new ArrayList<>(); + List placedPositions = new ArrayList<>(); + float minSeparation = triggerRadius * 2.0f; + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + positions.add(pos); + } + } for (int i = 0; i < zoneCount; i++) { - double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); - placedPositions.add(pos); + double[] pos = positions.get(i); EntityAbilityZone entity = EntityAbilityZone.createTrap(world, caster, pos[0], caster.posY, pos[1], @@ -99,7 +116,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { @Override public void readTypeNBT(NBTTagCompound nbt) { - readZoneNBT(nbt, 200); + readZoneNBT(nbt, 300); this.triggerRadius = nbt.hasKey("triggerRadius") ? nbt.getFloat("triggerRadius") : 2.0f; this.armTime = nbt.hasKey("armTime") ? nbt.getInteger("armTime") : 20; this.maxTriggers = nbt.hasKey("maxTriggers") ? nbt.getInteger("maxTriggers") : 1; @@ -171,6 +188,5 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { )); addVisualFieldDefs(defs); - addTelegraphSizeField(defs); } } 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 94ceea56d..5f8c33499 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 @@ -5,6 +5,7 @@ import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +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.EntityAbilityZone; @@ -36,9 +37,8 @@ public abstract class AbilityZone extends Ability { // Zone properties protected int durationTicks; protected ZoneShape zoneShape = ZoneShape.CIRCLE; - protected float spawnRadius = 5.0f; - protected float telegraphSize = 5.0f; - protected int zoneCount = 1; + protected float spawnRadius = 10.0f; + protected int zoneCount = 3; protected float zoneHeight = 2.0f; // Visual parameters @@ -67,15 +67,15 @@ public abstract class AbilityZone extends Ability { // Runtime state protected static final Random RANDOM = new Random(); protected transient List activeEntities = new ArrayList<>(); + protected transient List preCalculatedPositions = new ArrayList<>(); protected AbilityZone(int defaultDuration, EnergyDisplayData defaultColors) { this.durationTicks = defaultDuration; this.colorData = defaultColors; this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 15.0f; + this.maxRange = 20.0f; this.lockMovement = LockMovementType.WINDUP; this.cooldownTicks = 0; - this.telegraphType = TelegraphType.CIRCLE; this.allowedBy = UserType.NPC_ONLY; } @@ -98,22 +98,53 @@ public abstract class AbilityZone extends Ability { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public float getTelegraphRadius() { - return telegraphSize; - } + /** + * Returns the actual zone effect radius for telegraph sizing. + * AbilityHazard returns its damage radius, AbilityTrap returns triggerRadius. + */ + public abstract float getZoneRadius(); @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - TelegraphInstance instance = super.createTelegraph(caster, target); - if (instance == null) return null; + public List createTelegraphs(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || windUpTicks <= 0) return new ArrayList<>(); - // Always show telegraph at caster position - instance.setEntityIdToFollow(-1); - instance.setX(caster.posX); - instance.setY(caster.posY); - instance.setZ(caster.posZ); - return instance; + // Pre-calculate zone positions + preCalculatedPositions.clear(); + List placedPositions = new ArrayList<>(); + float minSeparation = getZoneRadius() * 2.0f; + + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + preCalculatedPositions.add(pos); + } + + // Create a telegraph for each zone position + List telegraphs = new ArrayList<>(); + float zoneRadius = getZoneRadius(); + + for (double[] pos : preCalculatedPositions) { + Telegraph telegraph; + if (zoneShape == ZoneShape.SQUARE) { + telegraph = Telegraph.square(zoneRadius); + } else { + telegraph = Telegraph.circle(zoneRadius); + } + + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + double groundY = findGroundLevel(caster.worldObj, pos[0], caster.posY, pos[1]); + TelegraphInstance instance = new TelegraphInstance(telegraph, pos[0], groundY, pos[1], 0); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(-1); + telegraphs.add(instance); + } + + return telegraphs; } @Override @@ -150,6 +181,7 @@ public abstract class AbilityZone extends Ability { } } activeEntities.clear(); + preCalculatedPositions.clear(); } @Override @@ -208,7 +240,7 @@ public abstract class AbilityZone extends Ability { // ═════════════════════════════════════════════════════════════════ /** - * Apply preset defaults by old style name (for backward compatibility). + * Apply preset defaults by style name. */ private void applyPresetDefaults(String styleName) { switch (styleName) { @@ -307,7 +339,6 @@ public abstract class AbilityZone extends Ability { nbt.setInteger("durationTicks", durationTicks); nbt.setString("zoneShape", zoneShape.name()); nbt.setFloat("spawnRadius", spawnRadius); - nbt.setFloat("telegraphSize", telegraphSize); nbt.setInteger("zoneCount", zoneCount); nbt.setFloat("zoneHeight", zoneHeight); nbt.setFloat("particleDensity", particleDensity); @@ -341,9 +372,8 @@ public abstract class AbilityZone extends Ability { } else { this.zoneShape = ZoneShape.CIRCLE; } - this.spawnRadius = nbt.hasKey("spawnRadius") ? nbt.getFloat("spawnRadius") : 5.0f; - this.telegraphSize = nbt.hasKey("telegraphSize") ? nbt.getFloat("telegraphSize") : spawnRadius; - this.zoneCount = nbt.hasKey("zoneCount") ? nbt.getInteger("zoneCount") : 1; + this.spawnRadius = nbt.hasKey("spawnRadius") ? nbt.getFloat("spawnRadius") : 10.0f; + this.zoneCount = nbt.hasKey("zoneCount") ? nbt.getInteger("zoneCount") : 3; 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; @@ -351,44 +381,21 @@ public abstract class AbilityZone extends Ability { this.lightningDensity = nbt.hasKey("lightningDensity") ? nbt.getFloat("lightningDensity") : 1.0f; colorData.readNBT(nbt); - // Visual fields — backward compat with old zoneStyle format - if (nbt.hasKey("zoneStyle")) { - // OLD FORMAT: apply preset defaults, then overlay CustomVisual - applyPresetDefaults(nbt.getString("zoneStyle")); - if (nbt.hasKey("CustomVisual")) { - NBTTagCompound custom = nbt.getCompoundTag("CustomVisual"); - this.groundFill = !custom.hasKey("groundFill") || custom.getBoolean("groundFill"); - this.groundAlpha = custom.hasKey("groundAlpha") ? custom.getFloat("groundAlpha") : 0.25f; - this.rings = !custom.hasKey("rings") || custom.getBoolean("rings"); - this.ringCount = custom.hasKey("ringCount") ? custom.getInteger("ringCount") : 3; - this.border = !custom.hasKey("border") || custom.getBoolean("border"); - this.borderSpeed = custom.hasKey("borderSpeed") ? custom.getFloat("borderSpeed") : 1.0f; - this.accents = !custom.hasKey("accents") || custom.getBoolean("accents"); - this.accentStyle = custom.hasKey("accentStyle") ? custom.getInteger("accentStyle") : 0; - this.lightning = custom.hasKey("lightning") && custom.getBoolean("lightning"); - this.particles = !custom.hasKey("particles") || custom.getBoolean("particles"); - this.particleMotion = custom.hasKey("particleMotion") ? custom.getInteger("particleMotion") : 0; - this.particleDir = custom.hasKey("particleDir") ? custom.getString("particleDir") : ""; - this.particleSize = custom.hasKey("particleSize") ? custom.getInteger("particleSize") : 32; - this.particleGlow = !custom.hasKey("particleGlow") || custom.getBoolean("particleGlow"); - } - } else { - // NEW FORMAT: read individual top-level keys - this.groundFill = !nbt.hasKey("groundFill") || nbt.getBoolean("groundFill"); - this.groundAlpha = nbt.hasKey("groundAlpha") ? nbt.getFloat("groundAlpha") : 0.25f; - this.rings = !nbt.hasKey("rings") || nbt.getBoolean("rings"); - this.ringCount = nbt.hasKey("ringCount") ? nbt.getInteger("ringCount") : 3; - this.border = !nbt.hasKey("border") || nbt.getBoolean("border"); - this.borderSpeed = nbt.hasKey("borderSpeed") ? nbt.getFloat("borderSpeed") : 1.0f; - this.accents = !nbt.hasKey("accents") || nbt.getBoolean("accents"); - this.accentStyle = nbt.hasKey("accentStyle") ? nbt.getInteger("accentStyle") : 0; - this.lightning = nbt.hasKey("lightning") && nbt.getBoolean("lightning"); - this.particles = !nbt.hasKey("particles") || nbt.getBoolean("particles"); - this.particleMotion = nbt.hasKey("particleMotion") ? nbt.getInteger("particleMotion") : 0; - this.particleDir = nbt.hasKey("particleDir") ? nbt.getString("particleDir") : ""; - this.particleSize = nbt.hasKey("particleSize") ? nbt.getInteger("particleSize") : 32; - this.particleGlow = !nbt.hasKey("particleGlow") || nbt.getBoolean("particleGlow"); - } + // Visual layer fields + this.groundFill = !nbt.hasKey("groundFill") || nbt.getBoolean("groundFill"); + this.groundAlpha = nbt.hasKey("groundAlpha") ? nbt.getFloat("groundAlpha") : 0.25f; + this.rings = !nbt.hasKey("rings") || nbt.getBoolean("rings"); + this.ringCount = nbt.hasKey("ringCount") ? nbt.getInteger("ringCount") : 3; + this.border = !nbt.hasKey("border") || nbt.getBoolean("border"); + this.borderSpeed = nbt.hasKey("borderSpeed") ? nbt.getFloat("borderSpeed") : 1.0f; + this.accents = !nbt.hasKey("accents") || nbt.getBoolean("accents"); + this.accentStyle = nbt.hasKey("accentStyle") ? nbt.getInteger("accentStyle") : 0; + this.lightning = nbt.hasKey("lightning") && nbt.getBoolean("lightning"); + this.particles = !nbt.hasKey("particles") || nbt.getBoolean("particles"); + this.particleMotion = nbt.hasKey("particleMotion") ? nbt.getInteger("particleMotion") : 0; + this.particleDir = nbt.hasKey("particleDir") ? nbt.getString("particleDir") : ""; + this.particleSize = nbt.hasKey("particleSize") ? nbt.getInteger("particleSize") : 32; + this.particleGlow = !nbt.hasKey("particleGlow") || nbt.getBoolean("particleGlow"); } // ═════════════════════════════════════════════════════════════════ @@ -409,8 +416,6 @@ public abstract class AbilityZone extends Ability { public float getSpawnRadius() { return spawnRadius; } public void setSpawnRadius(float spawnRadius) { this.spawnRadius = Math.max(0, spawnRadius); } - public float getTelegraphSize() { return telegraphSize; } - public void setTelegraphSize(float telegraphSize) { this.telegraphSize = Math.max(0, telegraphSize); } public int getZoneCount() { return zoneCount; } public void setZoneCount(int zoneCount) { this.zoneCount = Math.max(1, zoneCount); } public float getZoneHeight() { return zoneHeight; } @@ -546,9 +551,4 @@ public abstract class AbilityZone extends Ability { )); } - @SideOnly(Side.CLIENT) - protected void addTelegraphSizeField(List defs) { - defs.add(FieldDef.floatField("gui.size", this::getTelegraphSize, this::setTelegraphSize) - .tab("ability.tab.effects")); - } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java index 3ba858acc..bcb7a7958 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java @@ -150,6 +150,12 @@ public class Telegraph { return new Telegraph("", TelegraphType.POINT); } + public static Telegraph square(float radius) { + Telegraph t = new Telegraph("", TelegraphType.SQUARE); + t.radius = radius; + return t; + } + // ═══════════════════════════════════════════════════════════════════ // GETTERS & SETTERS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java index 4a2fe4b12..dd080f093 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java @@ -29,6 +29,11 @@ public enum TelegraphType { */ POINT, + /** + * Filled square (uses radius as half-size) + */ + SQUARE, + /** * No telegraph */ diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 5e1ff694f..b5c23c756 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -191,10 +191,9 @@ public class DataAbilities { case ACTIVE: if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { - // Just entered ACTIVE phase - lock telegraph position if it was following + // Just entered ACTIVE phase - lock telegraph positions if they were following // This commits the ability to its current target position - TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); - if (telegraph != null) { + for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } @@ -603,26 +602,27 @@ public class DataAbilities { } /** - * Spawn and send telegraph for an ability. + * Spawn and send telegraphs for an ability. */ private void spawnTelegraph(Ability ability, EntityLivingBase target) { - TelegraphInstance telegraph = ability.createTelegraph(npc, target); - if (telegraph != null) { - ability.setTelegraphInstance(telegraph); - // Send to all nearby players - TelegraphSpawnPacket.sendToTracking(telegraph, npc); + List telegraphs = ability.createTelegraphs(npc, target); + if (!telegraphs.isEmpty()) { + ability.setTelegraphInstances(telegraphs); + for (TelegraphInstance telegraph : telegraphs) { + TelegraphSpawnPacket.sendToTracking(telegraph, npc); + } } } /** - * Remove telegraph when ability ends or is interrupted. + * Remove telegraphs when ability ends or is interrupted. */ private void removeTelegraph(Ability ability) { - TelegraphInstance telegraph = ability.getTelegraphInstance(); - if (telegraph != null) { + List telegraphs = ability.getTelegraphInstances(); + for (TelegraphInstance telegraph : telegraphs) { TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), npc); - ability.setTelegraphInstance(null); } + ability.setTelegraphInstances(null); } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 6d265de27..a653e2a94 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -118,9 +118,8 @@ public class PlayerAbilityData implements IPlayerAbilityData { case ACTIVE: if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { - // Just entered ACTIVE phase - TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); - if (telegraph != null) { + // Just entered ACTIVE phase - lock all telegraph positions + for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } removeTelegraph(currentAbility, player); @@ -451,23 +450,25 @@ public class PlayerAbilityData implements IPlayerAbilityData { // ═══════════════════════════════════════════════════════════════════ private void spawnTelegraph(Ability ability, EntityPlayer player, EntityLivingBase target) { - TelegraphInstance telegraph = ability.createTelegraph(player, target); - if (telegraph != null) { - ability.setTelegraphInstance(telegraph); + List telegraphs = ability.createTelegraphs(player, target); + if (!telegraphs.isEmpty()) { + ability.setTelegraphInstances(telegraphs); if (player instanceof EntityPlayerMP) { - TelegraphSpawnPacket.sendToTracking(telegraph, player); + for (TelegraphInstance telegraph : telegraphs) { + TelegraphSpawnPacket.sendToTracking(telegraph, player); + } } } } private void removeTelegraph(Ability ability, EntityPlayer player) { - TelegraphInstance telegraph = ability.getTelegraphInstance(); - if (telegraph != null) { + List telegraphs = ability.getTelegraphInstances(); + for (TelegraphInstance telegraph : telegraphs) { if (player instanceof EntityPlayerMP) { TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), player); } - ability.setTelegraphInstance(null); } + ability.setTelegraphInstances(null); } // ═══════════════════════════════════════════════════════════════════ From bf3391a1a8e6984e3ec6b14b91910e5d35c2114e Mon Sep 17 00:00:00 2001 From: Vidal Date: Thu, 12 Feb 2026 18:46:11 -0300 Subject: [PATCH 31/76] Made trap windup a bit slower to match the animation Made the previously only hazard animation play on both hazard and trap --- .../npcs/controllers/data/ability/type/AbilityHazard.java | 4 ++-- .../npcs/controllers/data/ability/type/AbilityTrap.java | 4 +++- .../{Ability_Hazard_Active.json => Ability_Zone_Active.json} | 2 +- .../{Ability_Hazard_Windup.json => Ability_Zone_Windup.json} | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) rename src/main/resources/assets/customnpcs/animations/{Ability_Hazard_Active.json => Ability_Zone_Active.json} (99%) rename src/main/resources/assets/customnpcs/animations/{Ability_Hazard_Windup.json => Ability_Zone_Windup.json} (99%) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 551fbe9cc..51538da55 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -38,8 +38,8 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { this.typeId = "ability.cnpc.hazard"; this.name = "Hazard"; this.windUpTicks = 30; - this.windUpAnimationName = "Ability_Hazard_Windup"; - this.activeAnimationName = "Ability_Hazard_Active"; + this.windUpAnimationName = "Ability_Zone_Windup"; + this.activeAnimationName = "Ability_Zone_Active"; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index b296fa8bc..d55a4060c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -40,7 +40,9 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { super(300, new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.trap"; this.name = "Trap"; - this.windUpTicks = 20; + this.windUpTicks = 30; + this.windUpAnimationName = "Ability_Zone_Windup"; + this.activeAnimationName = "Ability_Zone_Active"; } @Override diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json similarity index 99% rename from src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json rename to src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json index 11cb0ef7a..747f73860 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json @@ -261,6 +261,6 @@ "ID": 24, "WhileAttacking": 1b, "WhileWalking": 1b, - "Name": "Ability_Hazard_Active", + "Name": "Ability_Zone_Active", "WhileStanding": 1b } diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json similarity index 99% rename from src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json rename to src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json index 8a16135a4..40a6abef7 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Hazard_Windup.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json @@ -387,6 +387,6 @@ "ID": 23, "WhileAttacking": 1b, "WhileWalking": 1b, - "Name": "Ability_Hazard_Windup", + "Name": "Ability_Zone_Windup", "WhileStanding": 1b } From 6f9cafa1414accff7d56947c676685c15f75c78f Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 18:15:41 -0500 Subject: [PATCH 32/76] Add Custom Particle Handling and Preset Handling to Trap and Hazards --- .../client/renderer/RenderAbilityZone.java | 35 +++++- .../controllers/data/ability/Ability.java | 10 ++ .../data/ability/AbilityEffect.java | 8 +- .../data/ability/type/AbilityCharge.java | 39 +++++- .../data/ability/type/AbilityCutter.java | 91 +++++++++++++- .../data/ability/type/AbilityHazard.java | 2 + .../data/ability/type/AbilityShockwave.java | 2 +- .../data/ability/type/AbilityTrap.java | 2 + .../data/ability/type/AbilityZone.java | 115 +++++++++--------- src/main/java/noppes/npcs/DataAbilities.java | 15 ++- .../client/gui/SubGuiZonePresetSelector.java | 72 +++++++++++ .../npcs/client/gui/builder/FieldDef.java | 4 +- .../assets/customnpcs/lang/en_US.lang | 2 + 13 files changed, 318 insertions(+), 79 deletions(-) create mode 100644 src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java index 6c555aca8..9fae0e982 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java @@ -252,13 +252,30 @@ public class RenderAbilityZone extends Render { // 6. Particles if (c.particles && c.newTick && c.particleDensity > 0) { if (c.particleDir != null && !c.particleDir.isEmpty()) { - spawnCustomFXParticle(c); + if (c.particleDir.startsWith("mc:")) { + spawnVanillaParticle(c); + } else { + spawnCustomFXParticle(c); + } } else { spawnDefaultParticles(c); } } } + /** Spawn vanilla Minecraft particles using mc: prefix (e.g. "mc:flame"). */ + private void spawnVanillaParticle(Ctx c) { + String particleName = c.particleDir.substring(3); + int count = Math.round(3 * c.particleDensity); + for (int i = 0; i < count; i++) { + double[] pos = randomPosInZone(c); + double[] motion = getMotionForStyle(c.particleMotion); + c.zone.worldObj.spawnParticle(particleName, + c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2], + motion[0], motion[1], motion[2]); + } + } + /** Spawn CustomFX particles using a texture directory. */ private void spawnCustomFXParticle(Ctx c) { int count = Math.round(3 * c.particleDensity); @@ -267,18 +284,26 @@ public class RenderAbilityZone extends Render { double[] motion = getMotionForStyle(c.particleMotion); CustomFX fx = new CustomFX(c.zone.worldObj, null, c.particleDir, c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2], - motion[0], motion[1], motion[2]); + 0, 0, 0); + fx.motionX = motion[0]; + fx.motionY = motion[1]; + fx.motionZ = motion[2]; fx.setMaxAge(20 + RANDOM.nextInt(20)); + fx.width = -1; + fx.height = -1; fx.scaleX1 = c.particleScale * 10.0f; fx.scaleY1 = c.particleScale * 10.0f; - fx.width = c.particleSize; - fx.height = c.particleSize; + fx.scaleX2 = fx.scaleX1; + fx.scaleY2 = fx.scaleY1; + fx.scaleXRate = 0; + fx.scaleYRate = 0; fx.HEXColor = c.zone.getInnerColor(); fx.facePlayer = true; fx.glows = c.particleGlow; + fx.noClip = true; fx.alpha1 = 0.8f; fx.alpha2 = 0.0f; - fx.alphaRate = 0.04f; + fx.alphaRate = -0.04f; Minecraft.getMinecraft().effectRenderer.addEffect(fx); } } 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 2dd86a4b4..44bb6beb2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -404,6 +404,16 @@ public abstract class Ability implements IAbility { return caster instanceof EntityPlayer; } + /** + * Whether the telegraph should remain visible during the ACTIVE phase. + * Default: false (telegraph removed at WINDUP→ACTIVE transition). + * Override for abilities where the active phase IS the attack (e.g., sweeping/spinning attacks) + * so the telegraph stays visible while damage is being dealt. + */ + public boolean keepTelegraphDuringActive() { + return false; + } + /** * Returns true if this ability controls NPC movement during ACTIVE phase. * When true, AI pathfinding will be blocked during ability execution. diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java index 57f0cbf17..73f465049 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java @@ -20,7 +20,8 @@ public class AbilityEffect { BLINDNESS("potion.blindness", Potion.blindness.id), NAUSEA("potion.confusion", Potion.confusion.id), HUNGER("potion.hunger", Potion.hunger.id), - MINING_FATIGUE("potion.digSlowDown", Potion.digSlowdown.id); + MINING_FATIGUE("potion.digSlowDown", Potion.digSlowdown.id), + BURN("ability.effect.burn", -1); private final String langKey; private final int potionId; @@ -83,6 +84,11 @@ public class AbilityEffect { return; } + if (type == EffectType.BURN) { + entity.setFire(Math.max(1, durationTicks / 20)); + return; + } + int potionId = type.getPotionId(); if (potionId >= 0) { entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier)); 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 2a0a5ff8c..a7430ce20 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 @@ -38,9 +38,11 @@ public class AbilityCharge extends Ability implements IAbilityCharge { // Runtime state (transient) private transient double startX, startY, startZ; + private transient double prevTickX, prevTickZ; private transient Vec3 chargeDirection; private transient Set hitEntities = new HashSet<>(); private transient float lockedYaw; + private transient int maxActiveTicks; public AbilityCharge() { this.typeId = "ability.cnpc.charge"; @@ -119,8 +121,13 @@ public class AbilityCharge extends Ability implements IAbilityCharge { startX = caster.posX; startY = caster.posY; startZ = caster.posZ; + prevTickX = caster.posX; + prevTickZ = caster.posZ; hitEntities.clear(); + // Safety timeout: expected ticks + buffer to prevent infinite charge + maxActiveTicks = chargeSpeed > 0 ? (int)(maxRange / chargeSpeed) + 10 : 10; + // If direction wasn't set during windup (shouldn't happen), set it now if (chargeDirection == null) { lockChargeDirection(caster, target); @@ -140,13 +147,36 @@ public class AbilityCharge extends Ability implements IAbilityCharge { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (chargeDirection == null) return; + // Safety timeout or missing state: force-complete to prevent stuck NPC + if (!isPreview() && (chargeDirection == null || tick > maxActiveTicks)) { + stopMomentum(caster); + signalCompletion(); + return; + } + + if (chargeDirection == null) { + signalCompletion(); + return; + } // Enforce rotation every tick if (!isPreview()) { enforceLockedRotation(caster); } + // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall + if (!isPreview() && tick > 1) { + double dx = caster.posX - prevTickX; + double dz = caster.posZ - prevTickZ; + if (dx * dx + dz * dz < 0.0001) { + stopMomentum(caster); + signalCompletion(); + return; + } + } + prevTickX = caster.posX; + prevTickZ = caster.posZ; + // Calculate distance traveled double distanceTraveled = Math.sqrt( Math.pow(caster.posX - startX, 2) + @@ -155,11 +185,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { // Check if reached max distance if (distanceTraveled >= maxRange) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; - } + stopMomentum(caster); signalCompletion(); return; } @@ -240,6 +266,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { super.reset(); chargeDirection = null; hitEntities.clear(); + maxActiveTicks = 0; } @Override 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 22831f4ff..900ae6080 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 @@ -3,6 +3,8 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -60,6 +62,8 @@ public class AbilityCutter extends Ability implements IAbilityCutter { // Runtime state private transient Set hitEntities = new HashSet<>(); private transient float currentRotation = 0.0f; + private transient boolean activeSoundPlayed = false; + private transient float sweepBaseYaw = 0.0f; public AbilityCutter() { this.typeId = "ability.cnpc.cutter"; @@ -86,6 +90,54 @@ public class AbilityCutter extends Ability implements IAbilityCutter { return new TargetingMode[]{TargetingMode.AOE_SELF}; } + /** + * Calculate how many ticks the active sweep phase takes. + * SWIPE: arcAngle / sweepSpeed ticks + * SPIN: spinDurationTicks + */ + private int getActiveDurationTicks() { + if (sweepMode == SweepMode.SPIN) { + return spinDurationTicks; + } + return sweepSpeed > 0 ? (int) Math.ceil(arcAngle / sweepSpeed) : 1; + } + + @Override + public boolean keepTelegraphDuringActive() { + return true; + } + + /** + * Creates a CONE telegraph that lasts through both windup and active sweep phases. + * Warning color transitions when the sweep actually begins (at windUpTicks). + */ + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) { + return null; + } + + Telegraph telegraph = Telegraph.cone(getTelegraphLength(), getTelegraphAngle()); + int totalDuration = windUpTicks + getActiveDurationTicks(); + telegraph.setDurationTicks(totalDuration); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + // Warning transition starts when the sweep begins (active phase) + telegraph.setWarningStartTick(windUpTicks); + telegraph.setHeightOffset(telegraphHeightOffset); + + double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ); + TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, groundY, caster.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(caster.getEntityId()); + + if (target != null && !isRotationLockedDuringWindup()) { + instance.setTargetEntityId(target.getEntityId()); + } + + return instance; + } + @Override public float getTelegraphRadius() { return range; @@ -105,6 +157,21 @@ public class AbilityCutter extends Ability implements IAbilityCutter { public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { hitEntities.clear(); 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) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + if (dx * dx + dz * dz > 0.0001) { + sweepBaseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + } else { + sweepBaseYaw = caster.rotationYaw; + } + } else { + sweepBaseYaw = caster.rotationYaw; + } } @Override @@ -115,6 +182,12 @@ public class AbilityCutter extends Ability implements IAbilityCutter { case SWIPE: float prevRotation = currentRotation; currentRotation += sweepSpeed; + + // Play active sound when sweep reaches center (where target typically stands) + if (!activeSoundPlayed && currentRotation >= 0) { + playActiveSound(caster, world); + } + if (currentRotation > arcAngle / 2.0f) { if (!isPreview()) { performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); @@ -128,6 +201,11 @@ public class AbilityCutter extends Ability implements IAbilityCutter { break; case SPIN: + // Play active sound at spin start + if (!activeSoundPlayed) { + playActiveSound(caster, world); + } + if (tick >= spinDurationTicks) { signalCompletion(); return; @@ -142,6 +220,13 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } } + private void playActiveSound(EntityLivingBase caster, World world) { + activeSoundPlayed = true; + if (activeSound != null && !activeSound.isEmpty()) { + world.playSoundAtEntity(caster, activeSound, 1.0f, 1.0f); + } + } + /** * Check for entities between two sweep angles, ensuring no gaps between ticks. * For SWIPE mode, this covers the continuous arc from startAngle to endAngle. @@ -171,7 +256,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { double dist = Math.sqrt(dx * dx + dz * dz); if (dist < minDist || dist > maxDist) continue; - if (!isInSweepRange(dx, dz, caster.rotationYaw, minAngle, maxAngle)) continue; + if (!isInSweepRange(dx, dz, sweepBaseYaw, minAngle, maxAngle)) continue; hitEntities.add(entity.getEntityId()); @@ -214,12 +299,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter { public void onComplete(EntityLivingBase caster, EntityLivingBase target) { hitEntities.clear(); currentRotation = 0.0f; + activeSoundPlayed = false; + sweepBaseYaw = 0.0f; } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { hitEntities.clear(); currentRotation = 0.0f; + activeSoundPlayed = false; + sweepBaseYaw = 0.0f; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 51538da55..a8bbafc1a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -148,6 +148,8 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { + addPresetFieldDef(defs); + defs.addAll(Arrays.asList( FieldDef.row( FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 6788a3ea3..0ef0dc50f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -35,7 +35,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.typeId = "ability.cnpc.shockwave"; this.name = "Shockwave"; this.targetingMode = TargetingMode.AOE_SELF; - this.maxRange = 15.0f; + this.maxRange = 8.0f; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; this.cooldownTicks = 0; this.windUpTicks = 25; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index d55a4060c..b35891d9a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -157,6 +157,8 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { + addPresetFieldDef(defs); + defs.addAll(Arrays.asList( FieldDef.row( FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), 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 5f8c33499..8a15c2ce5 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 @@ -1,6 +1,7 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.UserType; @@ -17,6 +18,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.world.World; +import noppes.npcs.client.gui.SubGuiZonePresetSelector; import noppes.npcs.client.gui.builder.FieldDef; import cpw.mods.fml.relauncher.Side; @@ -243,36 +245,61 @@ public abstract class AbilityZone extends Ability { * Apply preset defaults by style name. */ private void applyPresetDefaults(String styleName) { + effects.clear(); + particleDir = ""; switch (styleName) { case "TOXIC": groundFill = true; groundAlpha = 0.30f; rings = true; ringCount = 3; border = false; borderSpeed = 1.0f; accents = true; accentStyle = 1; - lightning = false; particles = true; particleMotion = 0; particleGlow = true; + lightning = false; particles = true; particleDensity = 1.5f; particleScale = 0.8f; + particleMotion = 1; particleGlow = true; particleDir = "mc:mobSpell"; + colorData.innerColor = 0x44DD44; colorData.outerColor = 0x116611; + windUpColor = 0x6044DD44; activeColor = 0xC044FF44; + effects.add(new AbilityEffect(AbilityEffect.EffectType.POISON, 100, 0)); break; case "INFERNO": groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; border = true; borderSpeed = 2.0f; accents = true; accentStyle = 2; - lightning = false; particles = true; particleMotion = 0; particleGlow = true; + lightning = false; particles = true; particleDensity = 2.0f; particleScale = 1.2f; + particleMotion = 0; particleGlow = true; particleDir = "mc:flame"; + colorData.innerColor = 0xFF6611; colorData.outerColor = 0xCC2200; + windUpColor = 0x60FF6611; activeColor = 0xC0FF4400; + effects.add(new AbilityEffect(AbilityEffect.EffectType.BURN, 60, 0)); break; case "ARCANE": groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; border = true; borderSpeed = 0.8f; accents = true; accentStyle = 0; - lightning = false; particles = true; particleMotion = 1; particleGlow = true; + lightning = false; particles = true; particleDensity = 1.0f; particleScale = 1.0f; + particleMotion = 1; particleGlow = true; particleDir = "mc:portal"; + colorData.innerColor = 0xAA44FF; colorData.outerColor = 0x6622BB; + windUpColor = 0x60AA44FF; activeColor = 0xC0CC66FF; + effects.add(new AbilityEffect(AbilityEffect.EffectType.WEAKNESS, 100, 0)); break; case "ELECTRIC": groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; border = false; borderSpeed = 1.0f; accents = false; accentStyle = 0; - lightning = true; particles = true; particleMotion = 2; particleGlow = true; + lightning = true; particles = true; particleDensity = 0.8f; particleScale = 0.6f; + particleMotion = 2; particleGlow = true; particleDir = "mc:enchantmenttable"; + colorData.innerColor = 0x4488FF; colorData.outerColor = 0x2244BB; + windUpColor = 0x604488FF; activeColor = 0xC066AAFF; + effects.add(new AbilityEffect(AbilityEffect.EffectType.MINING_FATIGUE, 80, 1)); break; case "FROST": groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; border = true; borderSpeed = 0.3f; accents = true; accentStyle = 0; - lightning = false; particles = true; particleMotion = 1; particleGlow = true; + lightning = false; particles = true; particleDensity = 1.5f; particleScale = 1.0f; + particleMotion = 1; particleGlow = true; particleDir = "mc:snowshovel"; + colorData.innerColor = 0x88CCFF; colorData.outerColor = 0x4488CC; + windUpColor = 0x6088CCFF; activeColor = 0xC0AADDFF; + effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 100, 1)); break; case "DEFAULT": groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; border = true; borderSpeed = 1.0f; accents = true; accentStyle = 0; - lightning = false; particles = false; particleMotion = 0; particleGlow = true; + lightning = false; particles = false; particleDensity = 1.0f; particleScale = 1.0f; + particleMotion = 0; particleGlow = true; + colorData.innerColor = 0xCCCCCC; colorData.outerColor = 0x666666; + windUpColor = 0x60CCCCCC; activeColor = 0xC0FFFFFF; break; default: break; @@ -285,7 +312,7 @@ public abstract class AbilityZone extends Ability { */ @SideOnly(Side.CLIENT) public enum ZonePreset { - CUSTOM, DEFAULT, TOXIC, INFERNO, ARCANE, ELECTRIC, FROST; + DEFAULT, TOXIC, INFERNO, ARCANE, ELECTRIC, FROST; @Override public String toString() { @@ -293,44 +320,6 @@ public abstract class AbilityZone extends Ability { } } - /** - * Check current field values against each preset, return matching preset or CUSTOM. - */ - @SideOnly(Side.CLIENT) - public ZonePreset getCurrentPreset() { - if (matchesPreset(true, 0.25f, true, 3, true, 1.0f, true, 0, false, false, 0, true)) - return ZonePreset.DEFAULT; - if (matchesPreset(true, 0.30f, true, 3, false, 1.0f, true, 1, false, true, 0, true)) - return ZonePreset.TOXIC; - if (matchesPreset(true, 0.35f, true, 3, true, 2.0f, true, 2, false, true, 0, true)) - return ZonePreset.INFERNO; - if (matchesPreset(true, 0.20f, true, 1, true, 0.8f, true, 0, false, true, 1, true)) - return ZonePreset.ARCANE; - if (matchesPreset(true, 0.15f, false, 1, false, 1.0f, false, 0, true, true, 2, true)) - return ZonePreset.ELECTRIC; - if (matchesPreset(true, 0.25f, true, 3, true, 0.3f, true, 0, false, true, 1, true)) - return ZonePreset.FROST; - return ZonePreset.CUSTOM; - } - - @SideOnly(Side.CLIENT) - private boolean matchesPreset(boolean gf, float ga, boolean r, int rc, boolean b, float bs, - boolean a, int as, boolean l, boolean p, int pm, boolean pg) { - return groundFill == gf && Math.abs(groundAlpha - ga) < 0.001f - && rings == r && ringCount == rc && border == b && Math.abs(borderSpeed - bs) < 0.001f - && accents == a && accentStyle == as && lightning == l - && particles == p && particleMotion == pm && particleGlow == pg; - } - - /** - * Apply a preset's field values. CUSTOM does nothing (user configures manually). - */ - @SideOnly(Side.CLIENT) - public void applyPreset(ZonePreset preset) { - if (preset == ZonePreset.CUSTOM) return; - applyPresetDefaults(preset.name()); - } - // ═════════════════════════════════════════════════════════════════ // SHARED NBT // ═════════════════════════════════════════════════════════════════ @@ -476,13 +465,21 @@ public abstract class AbilityZone extends Ability { // SHARED FIELD DEFINITIONS (client-only) // ═════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) + protected void addPresetFieldDef(List defs) { + defs.add(FieldDef.subGuiField("gui.applyPreset", + SubGuiZonePresetSelector::new, + gui -> { + SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui; + if (selector.selectedPreset != null) { + applyPresetDefaults(selector.selectedPreset); + } + })); + } + @SideOnly(Side.CLIENT) protected void addVisualFieldDefs(List defs) { defs.addAll(Arrays.asList( - // Preset dropdown - FieldDef.enumField("gui.preset", ZonePreset.class, this::getCurrentPreset, this::applyPreset) - .tab("ability.tab.visual"), - // Ground Fill FieldDef.section("ability.section.ground").tab("ability.tab.visual"), FieldDef.row( @@ -520,20 +517,18 @@ public abstract class AbilityZone extends Ability { // Particles FieldDef.section("ability.section.particles").tab("ability.tab.visual"), - FieldDef.row( - FieldDef.boolField("gui.enabled", this::isParticles, this::setParticles), - FieldDef.floatField("gui.density", this::getParticleDensity, this::setParticleDensity) - ).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.scale", this::getParticleScale, this::setParticleScale), - FieldDef.enumField("gui.motion", ParticleMotion.class, this::getParticleMotionEnum, this::setParticleMotionEnum) - ).tab("ability.tab.visual"), - FieldDef.boolField("gui.glow", this::isParticleGlow, this::setParticleGlow) + FieldDef.boolField("gui.enabled", this::isParticles, this::setParticles) .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("gui.density", this::getParticleDensity, this::setParticleDensity), + FieldDef.floatField("gui.scale", this::getParticleScale, this::setParticleScale) + ).tab("ability.tab.visual").visibleWhen(this::isParticles), + FieldDef.row( + FieldDef.enumField("gui.motion", ParticleMotion.class, this::getParticleMotionEnum, this::setParticleMotionEnum), + FieldDef.boolField("gui.glow", this::isParticleGlow, this::setParticleGlow) + ).tab("ability.tab.visual").visibleWhen(this::isParticles), FieldDef.stringField("gui.texture", this::getParticleDir, this::setParticleDir) .tab("ability.tab.visual").visibleWhen(this::isParticles), - FieldDef.intField("gui.size", this::getParticleSize, this::setParticleSize).range(1, 256) - .tab("ability.tab.visual").visibleWhen(this::isParticles), // Animation FieldDef.section("ability.section.animation").tab("ability.tab.visual"), diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index b5c23c756..9020b0ba8 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -197,8 +197,11 @@ public class DataAbilities { telegraph.lockPosition(); } - // Remove telegraph - it has served its purpose - removeTelegraph(currentAbility); + // Remove telegraph unless the ability keeps it during active phase + // (e.g., sweeping attacks where the telegraph shows the ongoing danger zone) + if (!currentAbility.keepTelegraphDuringActive()) { + removeTelegraph(currentAbility); + } // Handle rotation control transition from WINDUP to ACTIVE if (currentAbility.isRotationLockedDuringActive()) { @@ -224,7 +227,10 @@ public class DataAbilities { } // Play active sound and animation - playAbilitySound(currentAbility.getActiveSound()); + // Abilities that keep telegraph during active manage their own sound timing + if (!currentAbility.keepTelegraphDuringActive()) { + playAbilitySound(currentAbility.getActiveSound()); + } playAbilityAnimation(currentAbility.getActiveAnimation()); // Snap NPC to face target before execute so startMoving() reads correct rotation @@ -338,6 +344,9 @@ public class DataAbilities { private void handleAbilityCompletion(EntityLivingBase target) { if (currentAbility == null) return; + // Remove any remaining telegraphs (for abilities that keep telegraph during active) + removeTelegraph(currentAbility); + // Call onComplete callback currentAbility.onComplete(npc, target); diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java new file mode 100644 index 000000000..f67ef3db1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; + +@SideOnly(Side.CLIENT) +public class SubGuiZonePresetSelector extends SubGuiInterface { + + public String selectedPreset = null; + + private static final String[] PRESET_NAMES = {"DEFAULT", "TOXIC", "INFERNO", "ARCANE", "ELECTRIC", "FROST"}; + private static final String[] PRESET_LABELS = { + "ability.preset.default", "ability.preset.toxic", "ability.preset.inferno", + "ability.preset.arcane", "ability.preset.electric", "ability.preset.frost" + }; + private static final int[] PRESET_COLORS = {0xCCCCCC, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF}; + + public SubGuiZonePresetSelector() { + xSize = 170; + ySize = 135; + setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + int btnW = 72; + int btnH = 20; + int gapY = 4; + int col1 = guiLeft + 7; + int col2 = col1 + btnW + 6; + int startY = guiTop + 22; + + for (int i = 0; i < 6; i++) { + int x = (i % 2 == 0) ? col1 : col2; + int y = startY + (i / 2) * (btnH + gapY); + addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i])); + } + + int cancelY = startY + 3 * (btnH + gapY) + 4; + addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton btn) { + super.actionPerformed(btn); + if (btn.id >= 0 && btn.id < 6) { + selectedPreset = PRESET_NAMES[btn.id]; + close(); + } else if (btn.id == 10) { + close(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + super.drawScreen(mouseX, mouseY, f); + drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF); + for (int i = 0; i < 6; i++) { + GuiNpcButton btn = getButton(i); + if (btn != null && btn.visible) { + int x = btn.xPosition + 4; + int y = btn.yPosition + 5; + drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]); + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java index 9263cc880..5319d16e4 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -154,8 +154,8 @@ public class FieldDef { public static FieldDef colorSubGui(String label, Supplier getter, Consumer setter) { return subGuiField(label, - () -> new SubGuiColorSelector(getter.get()), - gui -> setter.accept(((SubGuiColorSelector) gui).color & 0x00FFFFFF)) + () -> new SubGuiColorSelector(getter.get() & 0xFFFFFF), + gui -> setter.accept((((SubGuiColorSelector) gui).color & 0x00FFFFFF) | (getter.get() & 0xFF000000))) .buttonLabel(() -> String.format("%06X", getter.get() & 0xFFFFFF)) .buttonTextColor(() -> getter.get() & 0xFFFFFF); } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 408136c34..3e8fa323a 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1761,6 +1761,7 @@ gui.interval=Interval gui.cooldown=Cooldown gui.max=Max gui.preset=Preset +gui.applyPreset=Apply Preset # Common Type Settings ability.radius=Radius @@ -1773,6 +1774,7 @@ ability.stunTicks=Stun Ticks ability.hitWidth=Hit Width ability.hitLength=Hit Length ability.effects=Effects +ability.effect.burn=Burn ability.mode=Mode ability.duration=Duration ability.anchorPoint=Anchor Point From 9dae4bae55f846912561530827a3e0b09560f204 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 18:53:40 -0500 Subject: [PATCH 33/76] feat: enhance damage handling for abilities and implement guard counter mechanics --- .../data/ability/type/AbilityGuard.java | 33 +++++++------ .../data/ability/type/AbilityTeleport.java | 5 -- .../noppes/npcs/ScriptPlayerEventHandler.java | 6 +++ .../controllers/data/PlayerAbilityData.java | 48 +++++++++++++++++++ 4 files changed, 73 insertions(+), 19 deletions(-) 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 477be2cc4..461fef2bd 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 @@ -65,11 +65,6 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.counterAnimationName = "Ability_Guard_Counter"; } - @Override - public boolean hasDamage() { - return false; - } - @Override public boolean allowBurst() { return false; @@ -133,16 +128,22 @@ public class AbilityGuard extends Ability implements IAbilityGuard { lastAttacker = attacker; lastDamageTaken = damage; - float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage); - float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth()); - - caster.setHealth(newHealth); - - if (!canCounter || !counterEligible || counterTriggered || !isDirectHit(source)) { - caster.setHealth(newHealth); + // Players: damage reduction handled via LivingHurtEvent (event.ammount modification) + // NPCs: called AFTER damageEntity() so health was already reduced — heal back here + if (caster instanceof EntityPlayer) { + if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) { + counterTriggered = true; + } } else { - caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); - counterTriggered = true; + float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage); + float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth()); + + if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) { + caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); + counterTriggered = true; + } else { + caster.setHealth(newHealth); + } } } @@ -342,6 +343,10 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.counterAnimationId = counterAnimationId; } + public boolean isCounterTriggered() { + return counterTriggered; + } + public String getCounterAnimationName() { return counterAnimationName; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index 4b19bc91d..29eb73832 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -86,11 +86,6 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.activeSound = "mob.endermen.portal"; } - @Override - public boolean hasDamage() { - return false; - } - @Override public boolean isTargetingModeLocked() { return true; diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 0541f64c4..c77083fa1 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -596,6 +596,12 @@ public class ScriptPlayerEventHandler { } if (event.entityLiving instanceof EntityPlayerMP) { + // Handle ability damage interactions (Guard counter, damage reduction) + PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving); + if (pData != null && pData.abilityData != null && pData.abilityData.isExecutingAbility()) { + event.ammount = pData.abilityData.onDamage(event.source, event.ammount); + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source); cancel = EventHooks.onPlayerDamaged(handler, pevent); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index a653e2a94..3e6489b1c 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -4,6 +4,7 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilityPhase; import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; @@ -417,6 +418,53 @@ public class PlayerAbilityData implements IPlayerAbilityData { } } + /** + * Handle damage taken while an ability is executing. + * Called from LivingHurtEvent BEFORE damage is applied to health. + * Triggers Guard counter detection and handles ability interruption. + * + * @param source The damage source + * @param amount The damage amount (post-armor) + * @return The modified damage amount (reduced by guard, or 0 if counter absorbs) + */ + public float onDamage(DamageSource source, float amount) { + if (currentAbility == null || !currentAbility.isExecuting()) { + return amount; + } + + net.minecraft.entity.Entity sourceEntity = source.getEntity(); + EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null; + + // Track counter state before calling onDamageTaken + boolean wasCounterTriggered = false; + if (currentAbility instanceof AbilityGuard) { + wasCounterTriggered = ((AbilityGuard) currentAbility).isCounterTriggered(); + } + + currentAbility.onDamageTaken(playerData.player, attacker, source, amount); + + // Guard: handle damage reduction and counter absorption + if (currentAbility instanceof AbilityGuard) { + AbilityGuard guard = (AbilityGuard) currentAbility; + if (guard.isGuarding()) { + // Counter just triggered — absorb full damage + if (!wasCounterTriggered && guard.isCounterTriggered()) { + return 0; + } + // Normal guard — apply flat damage reduction + float reduction = guard.getDamageReductionFactor(); + return Math.max(0, amount - reduction); + } + } + + // Check for ability interruption + if (currentAbility != null && currentAbility.canInterrupt(source)) { + interruptCurrentAbility(); + } + + return amount; + } + @Override public boolean isOnCooldown() { EntityPlayer player = playerData.player; From 356ae65b69f4b84e274f2cd4167479ee98451791 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 20:28:50 -0500 Subject: [PATCH 34/76] Fix Dialog and Quest Category Bug --- src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java | 1 - src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java | 2 -- src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java | 1 - 3 files changed, 4 deletions(-) diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java index 3e194f85f..38777d9ab 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java @@ -198,6 +198,5 @@ public class SubGuiNpcDialog extends SubGuiInterface implements ISubGuiListener, } public void save() { - PacketClient.sendClient(new DialogSavePacket(this.dialogCategoryID, dialog.writeToNBT(new NBTTagCompound()), false)); } } diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java index 807a3e719..86f174bc4 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java @@ -521,8 +521,6 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis public void save() { GuiNpcTextField.unfocus(); - if (dialog.id >= 0) - PacketClient.sendClient(new DialogSavePacket(((SubGuiNpcDialog) parent).dialogCategoryID, dialog.writeToNBT(new NBTTagCompound()), false)); } private DialogImage getSelectedImage() { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java index 6406733be..9d693db81 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java @@ -239,6 +239,5 @@ public class SubGuiNpcQuest extends SubGuiInterface implements ISubGuiListener, } public void save() { - PacketClient.sendClient(new QuestSavePacket(this.questCategoryID, quest.writeToNBT(new NBTTagCompound()), false)); } } From 2c00ecae9efb4fb57dbebd6cb3fe03465183b199 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 20:30:12 -0500 Subject: [PATCH 35/76] feat: add built-in ability handling and UI updates for ability management --- .../controllers/data/ability/Ability.java | 4 + .../data/ability/AbilityController.java | 28 +++- .../data/ability/BuiltInAbility.java | 8 +- .../kamkeel/npcs/network/PacketHandler.java | 2 + .../npcs/network/enums/EnumRequestPacket.java | 1 + .../ability/CustomAbilitiesGetPacket.java | 1 + src/main/java/kamkeel/npcs/util/Register.java | 19 ++- .../java/noppes/npcs/NoppesUtilServer.java | 17 +++ .../client/gui/advanced/GuiNPCAbilities.java | 21 ++- .../gui/advanced/SubGuiAbilityTypeSelect.java | 2 + .../gui/global/GuiNpcManageAbilities.java | 144 +++++++++++++----- .../noppes/npcs/constants/EnumScrollData.java | 1 + 12 files changed, 201 insertions(+), 47 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 44bb6beb2..b2743f629 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -1278,6 +1278,10 @@ public abstract class Ability implements IAbility { return typeId; } + public boolean isBuiltIn() { + return false; + } + public int getWeight() { return weight; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 294f9a765..01ddb7b58 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -48,6 +48,9 @@ public class AbilityController implements IAbilityHandler { /** External variant definitions registered by addons, keyed by typeId. */ private final Map> externalVariants = new LinkedHashMap<>(); + /** TypeIds that produce BuiltInAbility instances (non-editable in GUI). */ + private final Set builtInTypeIds = new HashSet<>(); + public AbilityController() { registerBuiltinTypes(); } @@ -173,7 +176,9 @@ public class AbilityController implements IAbilityHandler { if (abilities.containsKey(name)) { LogWriter.info("AbilityController: Overwriting built-in ability: " + name); } - ability.setName(name); + if (!ability.isBuiltIn()) { + ability.setName(name); + } abilities.put(name, ability); LogWriter.info("Registered ability: " + name); } @@ -281,12 +286,22 @@ public class AbilityController implements IAbilityHandler { // ACCESSORS // ═══════════════════════════════════════════════════════════════════════════ - /** Get a built-in ability by name. Returns the stored instance (not a copy). */ + /** Get a built-in ability by map key. Returns the stored instance (not a copy). */ public Ability getAbility(String name) { return abilities.get(name); } - /** Get all built-in ability names. */ + /** Get a built-in ability by its display name (ability.getName()). */ + public Ability getAbilityByDisplayName(String displayName) { + for (Ability ability : abilities.values()) { + if (ability.getName().equals(displayName)) { + return ability; + } + } + return null; + } + + /** Get all built-in ability map keys. */ public Set getAbilityNames() { return new LinkedHashSet<>(abilities.keySet()); } @@ -338,6 +353,10 @@ public class AbilityController implements IAbilityHandler { return typeFactories.keySet().toArray(new String[0]); } + public boolean isBuiltInType(String typeId) { + return builtInTypeIds.contains(typeId); + } + @Override public boolean hasType(String typeId) { return typeFactories.containsKey(typeId); @@ -386,6 +405,9 @@ public class AbilityController implements IAbilityHandler { LogWriter.info("AbilityController: Overwriting type: " + typeId); } typeFactories.put(typeId, factory); + if (temp.isBuiltIn()) { + builtInTypeIds.add(typeId); + } } /** diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java index 904fad0b9..36344e9e5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java @@ -21,7 +21,13 @@ public abstract class BuiltInAbility extends Ability { this.registryKey = registryKey; this.id = registryKey; this.name = registryKey; - this.typeId = registryKey; + // Convert "namespace:name" to "ability.namespace.name" for GUI filter compatibility + this.typeId = "ability." + registryKey.replace(':', '.'); + } + + @Override + public boolean isBuiltIn() { + return true; } /** diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index bcfd18abd..6db07c841 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -96,6 +96,7 @@ import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; +import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket; import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket; @@ -516,6 +517,7 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new CustomAbilityGetPacket()); REQUEST_PACKET.registerPacket(new CustomAbilityRemovePacket()); REQUEST_PACKET.registerPacket(new CustomAbilitySavePacket()); + REQUEST_PACKET.registerPacket(new BuiltInAbilityGetPacket()); // Other Packets REQUEST_PACKET.registerPacket(new IsGuiOpenInform()); diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java index 2f3e6ea94..25ba2bba6 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java @@ -205,6 +205,7 @@ public enum EnumRequestPacket { CustomAbilityGet, CustomAbilityRemove, CustomAbilitySave, + BuiltInAbilityGet, Hammer, RecipeScript, diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java index 8febd9fc0..6097c7483 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java @@ -47,5 +47,6 @@ public final class CustomAbilitiesGetPacket extends AbstractPacket { return; NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); + NoppesUtilServer.sendBuiltInAbilitiesData((EntityPlayerMP) player); } } diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index db6802f34..5a64fca6a 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -37,6 +37,7 @@ public class Register { public static class Abilities extends Register { protected final Map uniqueNames = new LinkedHashMap<>(); + protected final Set typeOnly = new HashSet<>(); private Abilities(String namespace) { super("ability", namespace); @@ -50,9 +51,25 @@ public class Register { return factory.get(); } + /** + * Register a type only (shell template, no built-in preset). + * The type will appear in the ability type picker but won't be + * available as a pre-configured ability by name. + */ + public Ability registerType(String factoryName, Supplier factory) { + String name = registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"); + entries.put(name, factory); + uniqueNames.put(name, factoryName); + typeOnly.add(name); + return factory.get(); + } + public void register() { for (Map.Entry> entry : entries.entrySet()) { - AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get()); + AbilityController.Instance.registerType(entry.getKey(), entry.getValue()); + if (!typeOnly.contains(entry.getKey())) { + AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get()); + } } } diff --git a/src/main/java/noppes/npcs/NoppesUtilServer.java b/src/main/java/noppes/npcs/NoppesUtilServer.java index 7faa7b2b5..b54b4b245 100644 --- a/src/main/java/noppes/npcs/NoppesUtilServer.java +++ b/src/main/java/noppes/npcs/NoppesUtilServer.java @@ -781,12 +781,29 @@ public class NoppesUtilServer { if (controller != null) { int index = 0; for (String typeId : controller.getTypes()) { + // Exclude built-in types from the NPC type list + if (controller.isBuiltInType(typeId)) continue; map.put(typeId, index++); } } sendScrollData(player, map, EnumScrollData.ABILITY_TYPES); } + public static void sendBuiltInAbilitiesData(EntityPlayerMP player) { + HashMap map = new HashMap(); + AbilityController controller = AbilityController.Instance; + if (controller != null) { + int index = 0; + for (String name : controller.getAbilityNames()) { + Ability ability = controller.getAbility(name); + if (ability != null) { + map.put(ability.getName(), index++); + } + } + } + sendScrollData(player, map, EnumScrollData.BUILTIN_ABILITIES); + } + public static void sendCustomAbilitiesData(EntityPlayerMP player) { HashMap map = new HashMap(); kamkeel.npcs.controllers.data.ability.AbilityController controller = kamkeel.npcs.controllers.data.ability.AbilityController.Instance; diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index 7bc5c3846..4b9e99a13 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -168,9 +168,16 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC addButton(toggleBtn); } + // Check if selected ability is built-in (non-editable) + boolean selectedIsBuiltIn = false; + if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { + Ability sel = npcSlots.get(selectedAbilityIndex).getAbility(); + if (sel != null && sel.isBuiltIn()) selectedIsBuiltIn = true; + } + // Right side buttons: Edit and Up/Down carrots with Save button addButton(new GuiNpcButton(72, guiLeft + 210, y + 145, 55, 20, "gui.edit")); - getButton(72).setEnabled(selectedAbilityIndex >= 0); + getButton(72).setEnabled(selectedAbilityIndex >= 0 && !selectedIsBuiltIn); // Up/Down carrot buttons addButton(new GuiNpcButton(73, guiLeft + 270, y + 145, 20, 20, "<")); @@ -180,7 +187,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Save button (to the right of carrots, only enabled when ability is selected) addButton(new GuiNpcButton(76, centerX, y + 82, 40, 20, "gui.save")); - getButton(76).setEnabled(selectedAbilityIndex >= 0); + getButton(76).setEnabled(selectedAbilityIndex >= 0 && !selectedIsBuiltIn); } @Override @@ -464,6 +471,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String displayName = I18n.format(typeId); // Search matches either the display name or the typeId if (search.isEmpty() || displayName.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) { + // Gray out built-in types to distinguish them from configurable types + if (AbilityController.Instance.isBuiltInType(typeId)) { + displayName = "\u00A77" + displayName; + } list.add(displayName); displayNameToTypeId.put(displayName, typeId); } @@ -512,6 +523,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (slot.isReference()) { return colorPrefix + (index + 1) + ". \u00A7e> " + nameDisplay + "\u00A7r"; } + if (ability.isBuiltIn()) { + return colorPrefix + (index + 1) + ". \u00A77" + nameDisplay + "\u00A7r"; + } return colorPrefix + (index + 1) + ". " + nameDisplay; } @@ -612,10 +626,11 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { if (scroll == npcAbilitiesScroll && selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { AbilitySlot slot = npcSlots.get(selectedAbilityIndex); + Ability ability = slot.getAbility(); + if (ability != null && ability.isBuiltIn()) return; if (slot.isReference()) { setSubGui(new SubGuiAbilityEditMode()); } else { - Ability ability = slot.getAbility(); if (ability != null) { setSubGui(ability.createConfigGui(this)); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java index 5d810862f..cce48bd32 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -58,6 +58,8 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS allDisplayNameToTypeId.clear(); String[] types = AbilityController.Instance.getTypes(); for (String typeId : types) { + // Exclude built-in types — they cannot be created as custom presets + if (AbilityController.Instance.isBuiltInType(typeId)) continue; String displayName = I18n.format(typeId); allDisplayNameToTypeId.put(displayName, typeId); } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java index b06f9d097..66e8ed46c 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -6,6 +6,7 @@ import kamkeel.npcs.controllers.data.ability.AbilityController; import java.util.UUID; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; @@ -51,6 +52,7 @@ import java.util.Vector; * - Left side: 3D preview of NPC with ability effects * - Right side: Ability list with search * - Play/Pause/Stop buttons to preview abilities + * - Toggle between Custom and Built-in ability views */ public class GuiNpcManageAbilities extends GuiAbilityInterface implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback, @@ -58,7 +60,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface // ==================== DATA ==================== private GuiCustomScroll scroll; - private HashMap abilityData = new HashMap<>(); + private HashMap customData = new HashMap<>(); + private HashMap builtInData = new HashMap<>(); /** Maps display name -> UUID for custom abilities */ private final HashMap displayToUuid = new HashMap<>(); private String selected = null; @@ -66,6 +69,10 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private String search = ""; private Ability selectedAbility = null; + // ==================== BUILT-IN TOGGLE ==================== + private boolean showingBuiltIn = false; + private boolean currentIsBuiltIn = false; + // ==================== PENDING SAVE ==================== private Ability pendingSaveAbility = null; private boolean pendingNewCreation = false; @@ -88,7 +95,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface previewExecutor = new AbilityPreviewExecutor(); previewExecutor.setParentGui(this); - // Request ability data from server + // Request ability data from server (sends both custom and built-in) PacketClient.sendClient(new CustomAbilitiesGetPacket()); // Enable animation data @@ -100,18 +107,26 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface public void initGui() { super.initGui(); - // Add button - addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); + // Toggle button — added FIRST to maintain stable buttonList index + String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; + addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 52, 45, 20, toggleLabel)); - // Remove button - addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove")); - getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected)); + if (!showingBuiltIn) { + // Add button — only for custom view + addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); - // Edit button - addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 52, 45, 20, "gui.edit")); - getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + // Remove button — only for custom view + addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove")); + getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected)); + } - // Scroll list of saved abilities (right side) + // Edit button — hidden when viewing built-in + if (!showingBuiltIn && !currentIsBuiltIn) { + addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 74, 45, 20, "gui.edit")); + getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + } + + // Scroll list of abilities (right side) if (scroll == null) { scroll = new GuiCustomScroll(this, 0); scroll.setSize(143, 185); @@ -122,7 +137,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface // Update scroll list scroll.setList(getSearchList()); - if (selected != null && displayToUuid.containsKey(selected)) { + if (selected != null) { scroll.setSelected(selected); } @@ -134,9 +149,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface return; } - // ID/Name label (below search bar) - addLabel(new GuiNpcLabel(10, "ID: " + selectedAbility.getId(), guiLeft + 220, guiTop + 215)); - // Play/Pause/Stop buttons (below model preview area) String animTexture = "customnpcs:textures/gui/animation.png"; int playButtonOffsetX = 60; @@ -161,17 +173,34 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface } } + private HashMap getCurrentData() { + return showingBuiltIn ? builtInData : customData; + } + private List getSearchList() { - if (search.isEmpty()) { - return new ArrayList<>(displayToUuid.keySet()); - } - List list = new ArrayList<>(); - for (String name : displayToUuid.keySet()) { - if (name.toLowerCase().contains(search.toLowerCase())) { - list.add(name); + if (showingBuiltIn) { + if (search.isEmpty()) { + return new ArrayList<>(builtInData.keySet()); } + List list = new ArrayList<>(); + for (String name : builtInData.keySet()) { + if (name.toLowerCase().contains(search.toLowerCase())) { + list.add(name); + } + } + return list; + } else { + if (search.isEmpty()) { + return new ArrayList<>(displayToUuid.keySet()); + } + List list = new ArrayList<>(); + for (String name : displayToUuid.keySet()) { + if (name.toLowerCase().contains(search.toLowerCase())) { + list.add(name); + } + } + return list; } - return list; } @Override @@ -227,13 +256,30 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface int id = guibutton.id; - if (id == 2) { + // Toggle between custom and built-in views + if (id == 10) { + showingBuiltIn = !showingBuiltIn; + selected = null; + selectedUuid = null; + selectedAbility = null; + currentIsBuiltIn = false; + search = ""; + previewExecutor.stop(); + if (scroll != null) { + scroll.clear(); + } + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + initGui(); + return; + } + + if (id == 2 && !showingBuiltIn) { // Add — open type selection setSubGui(new SubGuiAbilityTypeSelect()); - } else if (id == 1 && selected != null && selectedUuid != null) { + } else if (id == 1 && !showingBuiltIn && selected != null && selectedUuid != null) { GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), 1); displayGuiScreen(guiyesno); - } else if (id == 100 && selectedAbility != null) { + } else if (id == 100 && !showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) { // Edit previewExecutor.stop(); setSubGui(selectedAbility.createConfigGui(this)); @@ -276,11 +322,20 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface String newSelection = scroll.getSelected(); if (newSelection != null && !newSelection.equals(selected)) { previewExecutor.stop(); - selected = newSelection; - selectedUuid = displayToUuid.get(selected); - if (selectedUuid != null) { - PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); + + if (showingBuiltIn) { + // Fetch built-in ability by display name + selectedUuid = null; + currentIsBuiltIn = true; + PacketClient.sendClient(new BuiltInAbilityGetPacket(selected)); + } else { + // Fetch custom ability by UUID + selectedUuid = displayToUuid.get(selected); + currentIsBuiltIn = false; + if (selectedUuid != null) { + PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); + } } } } @@ -289,8 +344,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { if (scroll.id == 0 && selection != null && !selection.isEmpty()) { - // Double-click to edit - if (selectedAbility != null) { + // Double-click to edit — only for custom, non-built-in abilities + if (!showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) { previewExecutor.stop(); setSubGui(selectedAbility.createConfigGui(this)); } @@ -301,7 +356,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface public void setData(Vector list, HashMap data, EnumScrollData type) { if (type == EnumScrollData.CUSTOM_ABILITIES) { String prevSelected = scroll != null ? scroll.getSelected() : null; - this.abilityData = data; + this.customData = data; displayToUuid.clear(); for (String key : data.keySet()) { // key format: "displayName\tUUID" @@ -314,18 +369,30 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface displayToUuid.put(key, key); } } - if (scroll != null) { + if (!showingBuiltIn && scroll != null) { scroll.setList(getSearchList()); if (prevSelected != null && displayToUuid.containsKey(prevSelected)) { scroll.setSelected(prevSelected); } } initGui(); + } else if (type == EnumScrollData.BUILTIN_ABILITIES) { + this.builtInData = data; + if (showingBuiltIn && scroll != null) { + scroll.setList(getSearchList()); + if (selected != null && builtInData.containsKey(selected)) { + scroll.setSelected(selected); + } + } + initGui(); } } @Override public void setGuiData(NBTTagCompound compound) { + // Check if this is a built-in ability response + currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn"); + // Received ability data from server selectedAbility = AbilityController.Instance.fromNBT(compound); if (selectedAbility != null) { @@ -364,7 +431,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface return; } pendingTypeId = null; - saveAndOpenConfig(newAbility); + openConfig(newAbility); return; } } @@ -390,7 +457,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface setSubGui(new SubGuiDuplicateNameConfirm()); return; } - saveAndOpenConfig(newAbility); + openConfig(newAbility); return; } } @@ -398,7 +465,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui; if (confirm.isConfirmed() && pendingSaveAbility != null) { if (pendingNewCreation) { - saveAndOpenConfig(pendingSaveAbility); + openConfig(pendingSaveAbility); pendingSaveAbility = null; pendingNewCreation = false; return; @@ -434,8 +501,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface initGui(); } - private void saveAndOpenConfig(Ability ability) { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + private void openConfig(Ability ability) { selectedAbility = ability; selected = ability.getName(); selectedUuid = ability.getId(); diff --git a/src/main/java/noppes/npcs/constants/EnumScrollData.java b/src/main/java/noppes/npcs/constants/EnumScrollData.java index 06d5a6ec3..cbec6ad34 100644 --- a/src/main/java/noppes/npcs/constants/EnumScrollData.java +++ b/src/main/java/noppes/npcs/constants/EnumScrollData.java @@ -8,6 +8,7 @@ public enum EnumScrollData { QUEST_GROUP, ABILITY_TYPES, CUSTOM_ABILITIES, + BUILTIN_ABILITIES, ANIMATIONS, BUILTIN_ANIMATIONS } From 5d682962be60d21ec09fb07b73a11fadb625c811 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 20:30:45 -0500 Subject: [PATCH 36/76] feat: add BuiltInAbilityGetPacket for requesting built-in abilities by name --- .../ability/BuiltInAbilityGetPacket.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java new file mode 100644 index 000000000..6e565f3de --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java @@ -0,0 +1,70 @@ +package kamkeel.npcs.network.packets.request.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +import java.io.IOException; + +/** + * Request packet to get a specific built-in ability by name. + * Built-in abilities are registered presets with fixed configurations. + */ +public final class BuiltInAbilityGetPacket extends AbstractPacket { + public static String packetName = "Request|BuiltInAbilityGet"; + + private String abilityName; + + public BuiltInAbilityGetPacket() { + } + + public BuiltInAbilityGetPacket(String abilityName) { + this.abilityName = abilityName; + } + + @Override + public Enum getType() { + return EnumRequestPacket.BuiltInAbilityGet; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityName); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + String name = ByteBufUtils.readString(in); + Ability ability = AbilityController.Instance.getAbilityByDisplayName(name); + if (ability != null) { + NBTTagCompound compound = ability.writeNBT(); + compound.setBoolean("BuiltIn", true); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } + } +} From bc9fd53ae8d33c5aedde4e2b7676f59a51c93b97 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 12 Feb 2026 20:35:03 -0500 Subject: [PATCH 37/76] Beta 2 --- build.gradle | 2 +- src/main/java/noppes/npcs/CustomNpcs.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index a05d5d7a5..46c55e203 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { id "dts.typescript-generator" } -version = "1.11-beta1" +version = "1.11-beta2" group= "kamkeel.customnpc-plus" archivesBaseName = "CustomNPC-Plus" diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 933450557..364598166 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -118,7 +118,7 @@ import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; -@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta1") +@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta2") public class CustomNpcs { @SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy") From ac223cbb53145fbedcd80200534ff59de28522df Mon Sep 17 00:00:00 2001 From: bigguy345 Date: Fri, 13 Feb 2026 04:06:59 +0200 Subject: [PATCH 38/76] IAction exceptions now report to script console --- .../npcs/controllers/data/action/Action.java | 14 ++++++++++++++ .../data/action/action/ConditionalAction.java | 9 +++++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/java/noppes/npcs/controllers/data/action/Action.java b/src/main/java/noppes/npcs/controllers/data/action/Action.java index b7bce1102..cb2af9454 100644 --- a/src/main/java/noppes/npcs/controllers/data/action/Action.java +++ b/src/main/java/noppes/npcs/controllers/data/action/Action.java @@ -6,6 +6,7 @@ import noppes.npcs.api.handler.data.IActionQueue; import noppes.npcs.api.handler.data.actions.IConditionalAction; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.scripted.CustomNPCsException; +import org.apache.commons.lang3.exception.ExceptionUtils; import java.util.HashMap; import java.util.Map; @@ -344,6 +345,10 @@ public class Action implements IAction { try { onStart.accept(this); } catch (Throwable t) { + String err = "IAction" + getName() + " onStart threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("onStart Task of " + this + " threw an exception:", t); } @@ -359,6 +364,11 @@ public class Action implements IAction { task.accept(this); count++; } catch (Throwable t) { + String err = "IAction '" + name + "' threw an exception:"; + + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("Task of " + this + " threw an exception:", t); markDone(); } @@ -374,6 +384,10 @@ public class Action implements IAction { try { onDone.accept(this); } catch (Throwable t) { + String err = "IAction" + getName() + " onDone threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("onDone Task of " + this + " threw an exception:", t); } diff --git a/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java b/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java index 9e608df37..427749e33 100644 --- a/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java +++ b/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java @@ -4,6 +4,7 @@ import noppes.npcs.api.handler.data.IAction; import noppes.npcs.api.handler.data.actions.IConditionalAction; import noppes.npcs.controllers.data.action.Action; import noppes.npcs.controllers.data.action.ActionManager; +import org.apache.commons.lang3.exception.ExceptionUtils; import java.util.function.Consumer; import java.util.function.Function; @@ -130,6 +131,10 @@ public class ConditionalAction extends Action implements IConditionalAction { count++; taskExecuted = true; } catch (Throwable t) { + String err = "IConditionalAction '" + getName() + "' threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("Task of " + this + " threw an exception:", t); markDone(); } @@ -146,6 +151,10 @@ public class ConditionalAction extends Action implements IConditionalAction { try { onTermination.accept(this); } catch (Throwable t) { + String err = "IConditionalAction" + getName() + " onTermination threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("Termination Task of " + this + " threw an exception:", t); } From 185d91592857814765c317d2e9b1512bc38d886c Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 13 Feb 2026 14:17:17 -0500 Subject: [PATCH 39/76] refactor: simplify NBT reading for ability properties and potion effects --- .../controllers/data/ability/Ability.java | 60 ++++------- .../data/ability/AbilityEffect.java | 99 +++++++------------ .../data/ability/data/EnergyAnchorData.java | 8 +- .../data/ability/data/EnergyCombatData.java | 12 +-- .../data/ability/data/EnergyDisplayData.java | 12 +-- .../data/ability/data/EnergyHomingData.java | 8 +- .../data/ability/data/EnergyLifespanData.java | 4 +- .../ability/data/EnergyLightningData.java | 8 +- .../ability/data/EnergyTrajectoryData.java | 6 +- .../data/ability/data/ProjectileData.java | 4 +- .../data/ability/gui/AbilityFieldBuilder.java | 53 +++++++--- .../data/ability/type/AbilityBeam.java | 8 +- .../data/ability/type/AbilityCharge.java | 14 +-- .../data/ability/type/AbilityCutter.java | 16 +-- .../data/ability/type/AbilityDash.java | 4 +- .../data/ability/type/AbilityDisc.java | 14 +-- .../data/ability/type/AbilityGuard.java | 24 ++--- .../data/ability/type/AbilityHazard.java | 10 +- .../data/ability/type/AbilityHeal.java | 14 +-- .../data/ability/type/AbilityHeavyHit.java | 8 +- .../data/ability/type/AbilityLaserShot.java | 6 +- .../data/ability/type/AbilityOrb.java | 6 +- .../data/ability/type/AbilityProjectile.java | 16 +-- .../data/ability/type/AbilityShockwave.java | 8 +- .../data/ability/type/AbilitySlam.java | 10 +- .../data/ability/type/AbilitySweeper.java | 18 ++-- .../data/ability/type/AbilityTeleport.java | 28 +++--- .../data/ability/type/AbilityTrap.java | 16 +-- .../data/ability/type/AbilityVortex.java | 16 +-- .../data/ability/type/AbilityZone.java | 63 ++++++------ src/main/java/noppes/npcs/DataStats.java | 16 ++- .../client/gui/SubGuiNpcMeleeProperties.java | 27 +++-- .../npcs/client/gui/SubGuiNpcProjectiles.java | 24 +++-- .../npcs/client/gui/util/GuiNPCInterface.java | 7 +- .../noppes/npcs/constants/EnumPotionType.java | 80 ++++++++++++++- .../npcs/entity/EntityNPCInterface.java | 35 ++----- .../noppes/npcs/entity/EntityProjectile.java | 82 ++++++--------- .../assets/customnpcs/lang/en_US.lang | 2 + 38 files changed, 429 insertions(+), 417 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 b2743f629..ed3638d40 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -1175,61 +1175,37 @@ public abstract class Ability implements IAbility { maxRange = nbt.getFloat("maxRange"); cooldownTicks = nbt.getInteger("cooldown"); windUpTicks = nbt.getInteger("windUp"); - syncWindupWithAnimation = !nbt.hasKey("syncWindup") || nbt.getBoolean("syncWindup"); + syncWindupWithAnimation = nbt.getBoolean("syncWindup"); dazedTicks = nbt.getInteger("recovery"); interruptible = nbt.getBoolean("interruptible"); lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement")); - if (nbt.hasKey("rotationMode")) { - // Current format - rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); - rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); - } else if (nbt.hasKey("lockType")) { - // Legacy format migration: lockType was LockType enum (0=MOVEMENT, 1=ROTATION, 2=BOTH) - int oldLockType = nbt.getInteger("lockType"); - if (oldLockType == 0) { - // MOVEMENT only: movement locked, rotation was free - rotationMode = RotationMode.FREE; - } else if (oldLockType == 1) { - // ROTATION only: rotation locked same timing as old lockMovement, movement was free - rotationMode = RotationMode.LOCKED; - rotationPhase = lockMovement; - lockMovement = LockMovementType.NO; - } else { - // BOTH: both locked same timing - rotationMode = RotationMode.LOCKED; - rotationPhase = lockMovement; - } - } else { - rotationMode = RotationMode.FREE; - rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; - } + rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); + rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); windUpColor = nbt.getInteger("windUpColor"); activeColor = nbt.getInteger("activeColor"); windUpSound = nbt.getString("windUpSound"); activeSound = nbt.getString("activeSound"); - windUpAnimationId = nbt.hasKey("windUpAnimationId") ? nbt.getInteger("windUpAnimationId") : -1; - activeAnimationId = nbt.hasKey("activeAnimationId") ? nbt.getInteger("activeAnimationId") : -1; + windUpAnimationId = nbt.getInteger("windUpAnimationId"); + activeAnimationId = nbt.getInteger("activeAnimationId"); windUpAnimationName = nbt.getString("windUpAnimationName"); activeAnimationName = nbt.getString("activeAnimationName"); - showTelegraph = !nbt.hasKey("showTelegraph") || nbt.getBoolean("showTelegraph"); - if (nbt.hasKey("telegraphType")) { - try { - telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); - } catch (Exception e) { - telegraphType = TelegraphType.CIRCLE; - } + showTelegraph = nbt.getBoolean("showTelegraph"); + try { + telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); + } catch (Exception e) { + telegraphType = TelegraphType.CIRCLE; } - telegraphHeightOffset = nbt.hasKey("telegraphHeightOffset") ? nbt.getFloat("telegraphHeightOffset") : 0.1f; + telegraphHeightOffset = nbt.getFloat("telegraphHeightOffset"); customData = nbt.getCompoundTag("customData"); - allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH; - ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown"); + allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); + ignoreCooldown = nbt.getBoolean("ignoreCooldown"); // Burst - burstEnabled = nbt.hasKey("burstEnabled") && nbt.getBoolean("burstEnabled"); - burstAmount = nbt.hasKey("burstAmount") ? nbt.getInteger("burstAmount") : 0; - burstDelay = nbt.hasKey("burstDelay") ? nbt.getInteger("burstDelay") : 0; - burstReplayAnimations = !nbt.hasKey("burstReplayAnimations") || nbt.getBoolean("burstReplayAnimations"); - burstOverlap = nbt.hasKey("burstOverlap") && nbt.getBoolean("burstOverlap"); + burstEnabled = nbt.getBoolean("burstEnabled"); + burstAmount = nbt.getInteger("burstAmount"); + burstDelay = nbt.getInteger("burstDelay"); + burstReplayAnimations = nbt.getBoolean("burstReplayAnimations"); + burstOverlap = nbt.getBoolean("burstOverlap"); // Conditions conditions.clear(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java index 73f465049..e2c1da87d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java @@ -2,67 +2,24 @@ package kamkeel.npcs.controllers.data.ability; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; +import noppes.npcs.constants.EnumPotionType; /** * Represents a configurable potion effect that can be applied by abilities. - * Provides a unified system for managing debuffs like slowness, weakness, poison, etc. + * Uses the unified EnumPotionType enum shared across melee, ranged, and ability systems. */ public class AbilityEffect { - public enum EffectType { - NONE("gui.none", -1), - SLOWNESS("potion.moveSlowdown", Potion.moveSlowdown.id), - WEAKNESS("potion.weakness", Potion.weakness.id), - POISON("potion.poison", Potion.poison.id), - WITHER("potion.wither", Potion.wither.id), - BLINDNESS("potion.blindness", Potion.blindness.id), - NAUSEA("potion.confusion", Potion.confusion.id), - HUNGER("potion.hunger", Potion.hunger.id), - MINING_FATIGUE("potion.digSlowDown", Potion.digSlowdown.id), - BURN("ability.effect.burn", -1); - - private final String langKey; - private final int potionId; - - EffectType(String langKey, int potionId) { - this.langKey = langKey; - this.potionId = potionId; - } - - public String getLangKey() { - return langKey; - } - - public int getPotionId() { - return potionId; - } - - public static String[] getLangKeys() { - EffectType[] types = values(); - String[] keys = new String[types.length]; - for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; - return keys; - } - - public static EffectType fromOrdinal(int ordinal) { - EffectType[] values = values(); - if (ordinal >= 0 && ordinal < values.length) { - return values[ordinal]; - } - return NONE; - } - } - - private EffectType type = EffectType.NONE; + private EnumPotionType type = EnumPotionType.None; + private int manualPotionId = 0; private int durationTicks = 60; private int amplifier = 0; // 0-10 public AbilityEffect() { } - public AbilityEffect(EffectType type, int durationTicks, int amplifier) { + public AbilityEffect(EnumPotionType type, int durationTicks, int amplifier) { this.type = type; this.durationTicks = Math.max(1, durationTicks); this.amplifier = Math.max(0, Math.min(10, amplifier)); @@ -72,25 +29,27 @@ public class AbilityEffect { * Creates a copy of this effect. */ public AbilityEffect copy() { - return new AbilityEffect(type, durationTicks, amplifier); + AbilityEffect copy = new AbilityEffect(type, durationTicks, amplifier); + copy.manualPotionId = this.manualPotionId; + return copy; } /** * Applies this effect to the given entity. - * Does nothing if type is NONE. + * Does nothing if type is None. Validates potion IDs before applying. */ public void apply(EntityLivingBase entity) { - if (entity == null || type == EffectType.NONE) { + if (entity == null || type == EnumPotionType.None) { return; } - if (type == EffectType.BURN) { + if (type == EnumPotionType.Fire) { entity.setFire(Math.max(1, durationTicks / 20)); return; } - int potionId = type.getPotionId(); - if (potionId >= 0) { + int potionId = type.getResolvedPotionId(manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier)); } } @@ -100,9 +59,12 @@ public class AbilityEffect { */ public NBTTagCompound writeNBT() { NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("type", type.ordinal()); + nbt.setInteger("potionType", type.ordinal()); nbt.setInteger("duration", durationTicks); nbt.setInteger("amplifier", amplifier); + if (type == EnumPotionType.Manual) { + nbt.setInteger("manualPotionId", manualPotionId); + } return nbt; } @@ -110,9 +72,12 @@ public class AbilityEffect { * Reads this effect from NBT. */ public void readNBT(NBTTagCompound nbt) { - this.type = EffectType.fromOrdinal(nbt.getInteger("type")); - this.durationTicks = nbt.hasKey("duration") ? nbt.getInteger("duration") : 60; - this.amplifier = nbt.hasKey("amplifier") ? nbt.getInteger("amplifier") : 0; + this.type = EnumPotionType.fromOrdinal(nbt.getInteger("potionType")); + this.durationTicks = nbt.getInteger("duration"); + this.amplifier = nbt.getInteger("amplifier"); + if (type == EnumPotionType.Manual) { + this.manualPotionId = nbt.getInteger("manualPotionId"); + } } /** @@ -126,12 +91,20 @@ public class AbilityEffect { // Getters & Setters - public EffectType getType() { + public EnumPotionType getType() { return type; } - public void setType(EffectType type) { - this.type = type != null ? type : EffectType.NONE; + public void setType(EnumPotionType type) { + this.type = type != null ? type : EnumPotionType.None; + } + + public int getManualPotionId() { + return manualPotionId; + } + + public void setManualPotionId(int manualPotionId) { + this.manualPotionId = Math.max(0, manualPotionId); } public int getDurationTicks() { @@ -151,9 +124,9 @@ public class AbilityEffect { } /** - * Returns true if this effect is configured (not NONE). + * Returns true if this effect is configured (not None). */ public boolean isValid() { - return type != EffectType.NONE; + return type != EnumPotionType.None; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java index 2187802a5..99c51b23c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java @@ -91,10 +91,10 @@ public class EnergyAnchorData implements IEnergyAnchorData { } public void readNBT(NBTTagCompound nbt) { - this.anchorPoint = nbt.hasKey("anchorPoint") ? AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")) : AnchorPoint.FRONT; - this.anchorOffsetX = nbt.hasKey("anchorOffsetX") ? nbt.getFloat("anchorOffsetX") : 0; - this.anchorOffsetY = nbt.hasKey("anchorOffsetY") ? nbt.getFloat("anchorOffsetY") : 0; - this.anchorOffsetZ = nbt.hasKey("anchorOffsetZ") ? nbt.getFloat("anchorOffsetZ") : 0; + this.anchorPoint = AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")); + this.anchorOffsetX = nbt.getFloat("anchorOffsetX"); + this.anchorOffsetY = nbt.getFloat("anchorOffsetY"); + this.anchorOffsetZ = nbt.getFloat("anchorOffsetZ"); } public EnergyAnchorData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java index 52f5368f0..e6ccf15a1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java @@ -97,12 +97,12 @@ public class EnergyCombatData implements IEnergyCombatData { } public void readNBT(NBTTagCompound nbt) { - damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f; - knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.0f; - knockbackUp = nbt.hasKey("knockbackUp") ? nbt.getFloat("knockbackUp") : 0.1f; - explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive"); - explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 3.0f; - explosionDamageFalloff = nbt.hasKey("explosionDamageFalloff") ? nbt.getFloat("explosionDamageFalloff") : 0.5f; + damage = nbt.getFloat("damage"); + knockback = nbt.getFloat("knockback"); + knockbackUp = nbt.getFloat("knockbackUp"); + explosive = nbt.getBoolean("explosive"); + explosionRadius = nbt.getFloat("explosionRadius"); + explosionDamageFalloff = nbt.getFloat("explosionDamageFalloff"); } public EnergyCombatData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java index 0d91e1012..559be77f4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java @@ -102,12 +102,12 @@ public class EnergyDisplayData implements IEnergyDisplayData { } public void readNBT(NBTTagCompound nbt) { - innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF; - outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled"); - outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f; - outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; - rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; + innerColor = nbt.getInteger("innerColor"); + outerColor = nbt.getInteger("outerColor"); + outerColorEnabled = nbt.getBoolean("outerColorEnabled"); + outerColorWidth = nbt.getFloat("outerColorWidth"); + outerColorAlpha = nbt.getFloat("outerColorAlpha"); + rotationSpeed = nbt.getFloat("rotationSpeed"); } public EnergyDisplayData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java index 1e81882c7..d385c06e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java @@ -71,10 +71,10 @@ public class EnergyHomingData implements IEnergyHomingData { } public void readNBT(NBTTagCompound nbt) { - speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 0.5f; - homing = !nbt.hasKey("homing") || nbt.getBoolean("homing"); - homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.15f; - homingRange = nbt.hasKey("homingRange") ? nbt.getFloat("homingRange") : 20.0f; + speed = nbt.getFloat("speed"); + homing = nbt.getBoolean("homing"); + homingStrength = nbt.getFloat("homingStrength"); + homingRange = nbt.getFloat("homingRange"); } public EnergyHomingData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java index 9e017e2a5..f320acdb0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java @@ -44,8 +44,8 @@ public class EnergyLifespanData implements IEnergyLifespanData { } public void readNBT(NBTTagCompound nbt) { - maxDistance = nbt.hasKey("maxDistance") ? nbt.getFloat("maxDistance") : 30.0f; - maxLifetime = nbt.hasKey("maxLifetime") ? nbt.getInteger("maxLifetime") : 200; + maxDistance = nbt.getFloat("maxDistance"); + maxLifetime = nbt.getInteger("maxLifetime"); } public EnergyLifespanData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java index 00d0eaa96..66786a14a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java @@ -71,10 +71,10 @@ public class EnergyLightningData implements IEnergyLightningData { } public void readNBT(NBTTagCompound nbt) { - lightningEffect = nbt.hasKey("lightningEffect") && nbt.getBoolean("lightningEffect"); - lightningDensity = nbt.hasKey("lightningDensity") ? nbt.getFloat("lightningDensity") : 0.15f; - lightningRadius = nbt.hasKey("lightningRadius") ? nbt.getFloat("lightningRadius") : 0.5f; - lightningFadeTime = nbt.hasKey("lightningFadeTime") ? nbt.getInteger("lightningFadeTime") : 6; + lightningEffect = nbt.getBoolean("lightningEffect"); + lightningDensity = nbt.getFloat("lightningDensity"); + lightningRadius = nbt.getFloat("lightningRadius"); + lightningFadeTime = nbt.getInteger("lightningFadeTime"); } public EnergyLightningData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java index 7cc15a706..15adb3062 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java @@ -184,7 +184,7 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { } public void readNBT(NBTTagCompound nbt) { - this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0; + this.currentPath = nbt.getInteger("currentPath"); int i = 0; while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) { @@ -275,8 +275,8 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { } public void readNBT(NBTTagCompound nbt) { - this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0; - this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded"); + this.delayTicks = nbt.getInteger("delay"); + this.concluded = nbt.getBoolean("concluded"); double x = nbt.getDouble("X"); double y = nbt.getDouble("Y"); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java index 49ee50f7e..94850470f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -44,8 +44,8 @@ public class ProjectileData { anchor.readNBT(nbt); colorOverride = nbt.getBoolean("colorOverride"); if (colorOverride) { - innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF; + innerColor = nbt.getInteger("overrideInnerColor"); + outerColor = nbt.getInteger("overrideOuterColor"); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java index 5edd0a718..219479614 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java @@ -12,6 +12,7 @@ import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.constants.EnumPotionType; import java.util.ArrayList; import java.util.HashMap; @@ -26,7 +27,7 @@ import java.util.Map; public class AbilityFieldBuilder extends GuiFieldBuilder { // Effects list metadata: widgetId -> [effectIndex, action] - // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add + // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text) private final Map effectWidgetMeta = new HashMap<>(); public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { @@ -57,15 +58,15 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { List effects = (List) def.getValue(); if (effects == null) effects = new ArrayList<>(); - String[] typeNames = AbilityEffect.EffectType.getLangKeys(); + String[] typeNames = EnumPotionType.getLangKeysNoNone(); String[] ampValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; for (int e = 0; e < effects.size() && e < 5; e++) { AbilityEffect effect = effects.get(e); - // Type selector button - int typeIdx = effect.getType().ordinal(); - GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx); + // Type selector button (index offset by -1 since None is excluded) + int typeIdx = effect.getType().ordinal() - 1; + GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, Math.max(0, typeIdx)); sw.addButton(typeBtn); buttonFieldMap.put(widgetId, def); effectWidgetMeta.put(widgetId, new int[]{e, 0}); @@ -81,12 +82,16 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { effectWidgetMeta.put(widgetId, new int[]{e, 1}); widgetId++; - // Amplifier selector (0-10) - GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); - sw.addButton(ampBtn); - buttonFieldMap.put(widgetId, def); - effectWidgetMeta.put(widgetId, new int[]{e, 2}); - widgetId++; + if (effect.getType() != EnumPotionType.Fire) { + // Amplifier selector (0-10) — not applicable to Fire + GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); + sw.addButton(ampBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 2}); + widgetId++; + } else { + widgetId++; // keep widgetId in sync + } // Delete button GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); @@ -96,6 +101,20 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { clearId++; y += rowHeight; + + // Manual potion ID field (shown on next row when type is Manual) + if (effect.getType() == EnumPotionType.Manual) { + sw.addLabel(new GuiNpcLabel(labelId++, "effect.potionid", colLLabel, y + 5, 0xFFFFFF)); + GuiNpcTextField idField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 80, y, 50, 20, String.valueOf(effect.getManualPotionId())); + idField.setIntegersOnly(); + idField.setMinMaxDefault(0, Integer.MAX_VALUE, 0); + sw.addTextField(idField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 5}); + widgetId++; + y += rowHeight; + } } // Add button (if < 5 effects) @@ -133,7 +152,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { switch (action) { case 0: // Type changed if (effectIdx < effects.size()) { - effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue())); + effects.get(effectIdx).setType(EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue())); } return true; case 2: // Amp changed @@ -148,7 +167,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { return true; case 4: // Add if (effects.size() < 5) { - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0)); + effects.add(new AbilityEffect(EnumPotionType.Slowness, 60, 0)); } return true; } @@ -162,12 +181,16 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @SuppressWarnings("unchecked") public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { int[] meta = effectWidgetMeta.get(textFieldId); - if (meta != null && meta[1] == 1) { // duration field + if (meta != null) { FieldDef def = textFieldMap.get(textFieldId); if (def != null && def.getType() == FieldType.EFFECTS_LIST) { List effects = (List) def.getValue(); if (effects != null && meta[0] < effects.size()) { - effects.get(meta[0]).setDurationTicks(field.getInteger()); + if (meta[1] == 1) { // duration field + effects.get(meta[0]).setDurationTicks(field.getInteger()); + } else if (meta[1] == 5) { // manual potion ID field + effects.get(meta[0]).setManualPotionId(field.getInteger()); + } } return true; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 8bf2341f5..d02c19bdd 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -356,13 +356,13 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; + this.beamWidth = nbt.getFloat("beamWidth"); + this.headSize = nbt.getFloat("headSize"); - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + int count = nbt.getInteger("projectileCount"); initProjectiles(count); - this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; + this.fireDelay = nbt.getInteger("fireDelay"); combatData.readNBT(nbt); homingData.readNBT(nbt); 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 a7430ce20..50257e023 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 @@ -334,16 +334,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.chargeSpeed = nbt.hasKey("chargeSpeed") ? nbt.getFloat("chargeSpeed") : 0.8f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 3.0f; - if (nbt.hasKey("hitWidth")) { - this.hitWidth = nbt.getFloat("hitWidth"); - } else if (nbt.hasKey("hitRadius")) { - this.hitWidth = nbt.getFloat("hitRadius"); - } else { - this.hitWidth = 1.5f; - } + this.chargeSpeed = nbt.getFloat("chargeSpeed"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.hitWidth = nbt.getFloat("hitWidth"); } // Getters & Setters 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 900ae6080..110bda19f 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 @@ -326,19 +326,19 @@ public class AbilityCutter extends Ability implements IAbilityCutter { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.arcAngle = nbt.hasKey("arcAngle") ? nbt.getFloat("arcAngle") : 90.0f; - this.range = nbt.hasKey("range") ? nbt.getFloat("range") : 6.0f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.5f; + this.arcAngle = nbt.getFloat("arcAngle"); + this.range = nbt.getFloat("range"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); try { this.sweepMode = SweepMode.valueOf(nbt.getString("sweepMode")); } catch (Exception e) { this.sweepMode = SweepMode.SWIPE; } - this.sweepSpeed = nbt.hasKey("sweepSpeed") ? nbt.getFloat("sweepSpeed") : 6.0f; - this.spinDurationTicks = nbt.hasKey("spinDurationTicks") ? nbt.getInteger("spinDurationTicks") : 60; - this.piercing = !nbt.hasKey("piercing") || nbt.getBoolean("piercing"); - this.innerRadius = nbt.hasKey("innerRadius") ? nbt.getFloat("innerRadius") : 0.0f; + this.sweepSpeed = nbt.getFloat("sweepSpeed"); + this.spinDurationTicks = nbt.getInteger("spinDurationTicks"); + this.piercing = nbt.getBoolean("piercing"); + this.innerRadius = nbt.getFloat("innerRadius"); } // Getters & Setters 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 0f8cbe374..7e3375ca7 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 @@ -284,8 +284,8 @@ public class AbilityDash extends Ability implements IAbilityDash { } catch (Exception e) { this.dashMode = DashMode.DEFENSIVE; } - this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; - this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 0.5f; + this.dashDistance = nbt.getFloat("dashDistance"); + this.dashSpeed = nbt.getFloat("dashSpeed"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 886a269e2..2448642e0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -368,16 +368,16 @@ public class AbilityDisc extends Ability implements IAbilityDisc { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; - this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; - this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); - this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); - this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; + this.discRadius = nbt.getFloat("discRadius"); + this.discThickness = nbt.getFloat("discThickness"); + this.vertical = nbt.getBoolean("vertical"); + this.boomerang = nbt.getBoolean("boomerang"); + this.boomerangDelay = nbt.getInteger("boomerangDelay"); - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + int count = nbt.getInteger("projectileCount"); initProjectiles(count); - this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; + this.fireDelay = nbt.getInteger("fireDelay"); // Shared combat/movement data combatData.readNBT(nbt); 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 461fef2bd..87fd21a7f 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 @@ -238,27 +238,19 @@ public class AbilityGuard extends Ability implements IAbilityGuard { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; - this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f; - this.canCounter = nbt.hasKey("canCounter") && nbt.getBoolean("canCounter"); - this.counterWindow = nbt.hasKey("counterWindow") ? nbt.getInteger("counterWindow") : 10; + this.durationTicks = nbt.getInteger("durationTicks"); + this.damageReduction = nbt.getFloat("damageReduction"); + this.canCounter = nbt.getBoolean("canCounter"); + this.counterWindow = nbt.getInteger("counterWindow"); try { this.counterType = CounterType.valueOf(nbt.getString("counterType")); } catch (Exception e) { this.counterType = CounterType.FLAT; } - if (nbt.hasKey("counterValue")) { - this.counterValue = nbt.getFloat("counterValue"); - } else if (nbt.hasKey("counterDamage")) { - this.counterValue = nbt.getFloat("counterDamage"); - } else { - this.counterValue = 6.0f; - } - this.counterSound = nbt.hasKey("counterSound") ? nbt.getString("counterSound") : "random.wood_click"; - this.counterAnimationId = nbt.hasKey("counterAnimationId") ? nbt.getInteger("counterAnimationId") : -1; - this.counterAnimationName = nbt.hasKey("counterAnimationName") ? - nbt.getString("counterAnimationName") : - "Ability_Guard_Counter"; + this.counterValue = nbt.getFloat("counterValue"); + this.counterSound = nbt.getString("counterSound"); + this.counterAnimationId = nbt.getInteger("counterAnimationId"); + this.counterAnimationName = nbt.getString("counterAnimationName"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index a8bbafc1a..e5dfde01e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -115,11 +115,11 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { @Override public void readTypeNBT(NBTTagCompound nbt) { readZoneNBT(nbt, 300); - this.radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 2.0f; - this.damagePerSecond = nbt.hasKey("damagePerSecond") ? nbt.getFloat("damagePerSecond") : 1.0f; - this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 20; - this.ignoreInvulnFrames = nbt.hasKey("ignoreInvulnFrames") && nbt.getBoolean("ignoreInvulnFrames"); - this.affectsCaster = nbt.hasKey("affectsCaster") && nbt.getBoolean("affectsCaster"); + this.radius = nbt.getFloat("radius"); + this.damagePerSecond = nbt.getFloat("damagePerSecond"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.ignoreInvulnFrames = nbt.getBoolean("ignoreInvulnFrames"); + this.affectsCaster = nbt.getBoolean("affectsCaster"); } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index d913fe586..d2714ddd2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -227,13 +227,13 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; - this.healAmount = nbt.hasKey("healAmount") ? nbt.getFloat("healAmount") : 10.0f; - this.healPercent = nbt.hasKey("healPercent") ? nbt.getFloat("healPercent") : 0.0f; - this.healSelf = !nbt.hasKey("healSelf") || nbt.getBoolean("healSelf"); - this.healAllies = nbt.hasKey("healAllies") && nbt.getBoolean("healAllies"); - this.healRadius = nbt.hasKey("healRadius") ? nbt.getFloat("healRadius") : 0.0f; - this.instantHeal = !nbt.hasKey("instantHeal") || nbt.getBoolean("instantHeal"); + this.durationTicks = nbt.getInteger("durationTicks"); + this.healAmount = nbt.getFloat("healAmount"); + this.healPercent = nbt.getFloat("healPercent"); + this.healSelf = nbt.getBoolean("healSelf"); + this.healAllies = nbt.getBoolean("healAllies"); + this.healRadius = nbt.getFloat("healRadius"); + this.instantHeal = nbt.getBoolean("instantHeal"); } // Getters & Setters 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 dd5d5fc09..cf49cade6 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 @@ -135,10 +135,10 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 2.0f; - this.hitLength = nbt.hasKey("hitLength") ? nbt.getFloat("hitLength") : 4.0f; - this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 3.0f; + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.hitLength = nbt.getFloat("hitLength"); + this.hitWidth = nbt.getFloat("hitWidth"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index afffa9c13..a726e4c25 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -190,9 +190,9 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.laserWidth = nbt.hasKey("laserWidth") ? nbt.getFloat("laserWidth") : 0.3f; - this.expansionSpeed = nbt.hasKey("expansionSpeed") ? nbt.getFloat("expansionSpeed") : 3.0f; - this.lingerTicks = nbt.hasKey("lingerTicks") ? nbt.getInteger("lingerTicks") : 8; + this.laserWidth = nbt.getFloat("laserWidth"); + this.expansionSpeed = nbt.getFloat("expansionSpeed"); + this.lingerTicks = nbt.getInteger("lingerTicks"); anchorData.readNBT(nbt); colorData.readNBT(nbt); combatData.readNBT(nbt); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 8b4783f7c..5dbf58424 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -364,12 +364,12 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; + this.orbSize = nbt.getFloat("orbSize"); - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + int count = nbt.getInteger("projectileCount"); initProjectiles(count); - this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; + this.fireDelay = nbt.getInteger("fireDelay"); // Shared combat/movement data combatData.readNBT(nbt); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index 8abd5d01e..d79f783d1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -273,14 +273,14 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 6.0f; - this.speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 1.5f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; - this.projectileType = nbt.hasKey("projectileType") ? nbt.getString("projectileType") : "fireball"; - this.explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive"); - this.explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 0.0f; - this.homing = nbt.hasKey("homing") && nbt.getBoolean("homing"); - this.homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.1f; + this.damage = nbt.getFloat("damage"); + this.speed = nbt.getFloat("speed"); + this.knockback = nbt.getFloat("knockback"); + this.projectileType = nbt.getString("projectileType"); + this.explosive = nbt.getBoolean("explosive"); + this.explosionRadius = nbt.getFloat("explosionRadius"); + this.homing = nbt.getBoolean("homing"); + this.homingStrength = nbt.getFloat("homingStrength"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 0ef0dc50f..17fdecceb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -127,10 +127,10 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.pushRadius = nbt.hasKey("pushRadius") ? nbt.getFloat("pushRadius") : 8.0f; - this.pushStrength = nbt.hasKey("pushStrength") ? nbt.getFloat("pushStrength") : 1.5f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.maxTargets = nbt.hasKey("maxTargets") ? nbt.getInteger("maxTargets") : 10; + this.pushRadius = nbt.getFloat("pushRadius"); + this.pushStrength = nbt.getFloat("pushStrength"); + this.damage = nbt.getFloat("damage"); + this.maxTargets = nbt.getInteger("maxTargets"); } // Getters & Setters 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 a03ecdf6a..0bd9613a5 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 @@ -490,11 +490,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void readTypeNBT(NBTTagCompound nbt) { - damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 10.0f; - radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 5.0f; - knockbackStrength = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.5f; - leapSpeed = nbt.hasKey("leapSpeed") ? nbt.getFloat("leapSpeed") : 1.0f; - leapHeight = nbt.hasKey("leapHeight") ? nbt.getFloat("leapHeight") : 4.0f; + damage = nbt.getFloat("damage"); + radius = nbt.getFloat("radius"); + knockbackStrength = nbt.getFloat("knockback"); + leapSpeed = nbt.getFloat("leapSpeed"); + leapHeight = nbt.getFloat("leapHeight"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 8638dd2a4..43a152f7a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -172,15 +172,15 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.beamLength = nbt.hasKey("beamLength") ? nbt.getFloat("beamLength") : 10.0f; - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.3f; - this.beamHeight = nbt.hasKey("beamHeight") ? nbt.getFloat("beamHeight") : 0.5f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 5.0f; - this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 5; - this.piercing = !nbt.hasKey("piercing") || nbt.getBoolean("piercing"); - this.sweepSpeed = nbt.hasKey("sweepSpeed") ? nbt.getFloat("sweepSpeed") : 3.0f; - this.numberOfRotations = nbt.hasKey("numberOfRotations") ? nbt.getInteger("numberOfRotations") : 2; - this.lockOnTarget = nbt.hasKey("lockOnTarget") && nbt.getBoolean("lockOnTarget"); + this.beamLength = nbt.getFloat("beamLength"); + this.beamWidth = nbt.getFloat("beamWidth"); + this.beamHeight = nbt.getFloat("beamHeight"); + this.damage = nbt.getFloat("damage"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.piercing = nbt.getBoolean("piercing"); + this.sweepSpeed = nbt.getFloat("sweepSpeed"); + this.numberOfRotations = nbt.getInteger("numberOfRotations"); + this.lockOnTarget = nbt.getBoolean("lockOnTarget"); colorData.readNBT(nbt); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index 29eb73832..d9e05c382 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -430,24 +430,20 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { @Override public void readTypeNBT(NBTTagCompound nbt) { - if (nbt.hasKey("mode")) { - try { - this.mode = TeleportMode.valueOf(nbt.getString("mode")); - } catch (Exception e) { - this.mode = TeleportMode.BLINK; - } - } else { + try { + this.mode = TeleportMode.valueOf(nbt.getString("mode")); + } catch (Exception e) { this.mode = TeleportMode.BLINK; } - this.blinkCount = nbt.hasKey("blinkCount") ? nbt.getInteger("blinkCount") : 3; - this.blinkDelayTicks = nbt.hasKey("blinkDelayTicks") ? nbt.getInteger("blinkDelayTicks") : 10; - this.blinkRadius = nbt.hasKey("blinkRadius") ? nbt.getFloat("blinkRadius") : 8.0f; - this.behindDistance = nbt.hasKey("behindDistance") ? nbt.getFloat("behindDistance") : 2.0f; - this.requireLineOfSight = !nbt.hasKey("requireLineOfSight") || nbt.getBoolean("requireLineOfSight"); - this.damageAtStart = nbt.hasKey("damageAtStart") && nbt.getBoolean("damageAtStart"); - this.damageAtEnd = nbt.hasKey("damageAtEnd") && nbt.getBoolean("damageAtEnd"); - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 5.0f; - this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 2.0f; + this.blinkCount = nbt.getInteger("blinkCount"); + this.blinkDelayTicks = nbt.getInteger("blinkDelayTicks"); + this.blinkRadius = nbt.getFloat("blinkRadius"); + this.behindDistance = nbt.getFloat("behindDistance"); + this.requireLineOfSight = nbt.getBoolean("requireLineOfSight"); + this.damageAtStart = nbt.getBoolean("damageAtStart"); + this.damageAtEnd = nbt.getBoolean("damageAtEnd"); + this.damage = nbt.getFloat("damage"); + this.damageRadius = nbt.getFloat("damageRadius"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index b35891d9a..84bafc726 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -119,14 +119,14 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { @Override public void readTypeNBT(NBTTagCompound nbt) { readZoneNBT(nbt, 300); - this.triggerRadius = nbt.hasKey("triggerRadius") ? nbt.getFloat("triggerRadius") : 2.0f; - this.armTime = nbt.hasKey("armTime") ? nbt.getInteger("armTime") : 20; - this.maxTriggers = nbt.hasKey("maxTriggers") ? nbt.getInteger("maxTriggers") : 1; - this.triggerCooldown = nbt.hasKey("triggerCooldown") ? nbt.getInteger("triggerCooldown") : 20; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 6.0f; - this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 0.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; - this.visible = !nbt.hasKey("visible") || nbt.getBoolean("visible"); + this.triggerRadius = nbt.getFloat("triggerRadius"); + this.armTime = nbt.getInteger("armTime"); + 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"); } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index 90aaf054b..d9d253d29 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -236,14 +236,14 @@ public class AbilityVortex extends Ability implements IAbilityVortex { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.pullRadius = nbt.hasKey("pullRadius") ? nbt.getFloat("pullRadius") : 8.0f; - this.pullStrength = nbt.hasKey("pullStrength") ? nbt.getFloat("pullStrength") : 0.8f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 0.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.0f; - this.aoe = nbt.hasKey("aoe") && nbt.getBoolean("aoe"); - this.maxTargets = nbt.hasKey("maxTargets") ? nbt.getInteger("maxTargets") : 5; - this.damageOnPull = nbt.hasKey("damageOnPull") && nbt.getBoolean("damageOnPull"); - this.pullDamage = nbt.hasKey("pullDamage") ? nbt.getFloat("pullDamage") : 0.0f; + this.pullRadius = nbt.getFloat("pullRadius"); + this.pullStrength = nbt.getFloat("pullStrength"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.aoe = nbt.getBoolean("aoe"); + this.maxTargets = nbt.getInteger("maxTargets"); + this.damageOnPull = nbt.getBoolean("damageOnPull"); + this.pullDamage = nbt.getFloat("pullDamage"); } // Getters & Setters 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 8a15c2ce5..9a296e836 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 @@ -15,6 +15,7 @@ import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion; import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumPotionType; import net.minecraft.util.DamageSource; import net.minecraft.world.World; @@ -255,7 +256,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 1; particleGlow = true; particleDir = "mc:mobSpell"; colorData.innerColor = 0x44DD44; colorData.outerColor = 0x116611; windUpColor = 0x6044DD44; activeColor = 0xC044FF44; - effects.add(new AbilityEffect(AbilityEffect.EffectType.POISON, 100, 0)); + effects.add(new AbilityEffect(EnumPotionType.Poison, 100, 0)); break; case "INFERNO": groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; @@ -264,7 +265,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 0; particleGlow = true; particleDir = "mc:flame"; colorData.innerColor = 0xFF6611; colorData.outerColor = 0xCC2200; windUpColor = 0x60FF6611; activeColor = 0xC0FF4400; - effects.add(new AbilityEffect(AbilityEffect.EffectType.BURN, 60, 0)); + effects.add(new AbilityEffect(EnumPotionType.Fire, 60, 0)); break; case "ARCANE": groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; @@ -273,7 +274,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 1; particleGlow = true; particleDir = "mc:portal"; colorData.innerColor = 0xAA44FF; colorData.outerColor = 0x6622BB; windUpColor = 0x60AA44FF; activeColor = 0xC0CC66FF; - effects.add(new AbilityEffect(AbilityEffect.EffectType.WEAKNESS, 100, 0)); + effects.add(new AbilityEffect(EnumPotionType.Weakness, 100, 0)); break; case "ELECTRIC": groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; @@ -282,7 +283,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 2; particleGlow = true; particleDir = "mc:enchantmenttable"; colorData.innerColor = 0x4488FF; colorData.outerColor = 0x2244BB; windUpColor = 0x604488FF; activeColor = 0xC066AAFF; - effects.add(new AbilityEffect(AbilityEffect.EffectType.MINING_FATIGUE, 80, 1)); + effects.add(new AbilityEffect(EnumPotionType.MiningFatigue, 80, 1)); break; case "FROST": groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; @@ -291,7 +292,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 1; particleGlow = true; particleDir = "mc:snowshovel"; colorData.innerColor = 0x88CCFF; colorData.outerColor = 0x4488CC; windUpColor = 0x6088CCFF; activeColor = 0xC0AADDFF; - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 100, 1)); + effects.add(new AbilityEffect(EnumPotionType.Slowness, 100, 1)); break; case "DEFAULT": groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; @@ -354,37 +355,33 @@ public abstract class AbilityZone extends Ability { } protected void readZoneNBT(NBTTagCompound nbt, int defaultDuration) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : defaultDuration; - if (nbt.hasKey("zoneShape")) { - try { this.zoneShape = ZoneShape.valueOf(nbt.getString("zoneShape")); } - catch (Exception e) { this.zoneShape = ZoneShape.CIRCLE; } - } else { - this.zoneShape = ZoneShape.CIRCLE; - } - this.spawnRadius = nbt.hasKey("spawnRadius") ? nbt.getFloat("spawnRadius") : 10.0f; - this.zoneCount = nbt.hasKey("zoneCount") ? nbt.getInteger("zoneCount") : 3; - 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.durationTicks = nbt.getInteger("durationTicks"); + try { this.zoneShape = ZoneShape.valueOf(nbt.getString("zoneShape")); } + catch (Exception e) { this.zoneShape = ZoneShape.CIRCLE; } + this.spawnRadius = nbt.getFloat("spawnRadius"); + this.zoneCount = nbt.getInteger("zoneCount"); + this.zoneHeight = nbt.getFloat("zoneHeight"); + this.particleDensity = nbt.getFloat("particleDensity"); + this.particleScale = nbt.getFloat("particleScale"); + this.animSpeed = nbt.getFloat("animSpeed"); + this.lightningDensity = nbt.getFloat("lightningDensity"); colorData.readNBT(nbt); // Visual layer fields - this.groundFill = !nbt.hasKey("groundFill") || nbt.getBoolean("groundFill"); - this.groundAlpha = nbt.hasKey("groundAlpha") ? nbt.getFloat("groundAlpha") : 0.25f; - this.rings = !nbt.hasKey("rings") || nbt.getBoolean("rings"); - this.ringCount = nbt.hasKey("ringCount") ? nbt.getInteger("ringCount") : 3; - this.border = !nbt.hasKey("border") || nbt.getBoolean("border"); - this.borderSpeed = nbt.hasKey("borderSpeed") ? nbt.getFloat("borderSpeed") : 1.0f; - this.accents = !nbt.hasKey("accents") || nbt.getBoolean("accents"); - this.accentStyle = nbt.hasKey("accentStyle") ? nbt.getInteger("accentStyle") : 0; - this.lightning = nbt.hasKey("lightning") && nbt.getBoolean("lightning"); - this.particles = !nbt.hasKey("particles") || nbt.getBoolean("particles"); - this.particleMotion = nbt.hasKey("particleMotion") ? nbt.getInteger("particleMotion") : 0; - this.particleDir = nbt.hasKey("particleDir") ? nbt.getString("particleDir") : ""; - this.particleSize = nbt.hasKey("particleSize") ? nbt.getInteger("particleSize") : 32; - this.particleGlow = !nbt.hasKey("particleGlow") || nbt.getBoolean("particleGlow"); + 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"); } // ═════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/DataStats.java b/src/main/java/noppes/npcs/DataStats.java index 0d085d823..7db32bc66 100644 --- a/src/main/java/noppes/npcs/DataStats.java +++ b/src/main/java/noppes/npcs/DataStats.java @@ -20,6 +20,7 @@ public class DataStats { public EnumPotionType potionType = EnumPotionType.None; public int potionDuration = 5; //20 = 1 second public int potionAmp = 0; + public int potionManualId = 0; public double maxHealth = 20; public int respawnTime = 20; @@ -45,6 +46,7 @@ public class DataStats { public boolean pPhysics = true, pXlr8 = false, pGlows = false, pExplode = false; public boolean pRender3D = false, pSpin = false, pStick = false, pBurnItem = false; public EnumPotionType pEffect = EnumPotionType.None; + public int pManualId = 0; public EnumParticleType pTrail = EnumParticleType.None; public ScriptParticle pCustom = new ScriptParticle(""); public int pEffAmp = 0; @@ -88,6 +90,8 @@ public class DataStats { compound.setInteger("PotionEffect", potionType.ordinal()); compound.setInteger("PotionDuration", potionDuration); compound.setInteger("PotionAmp", potionAmp); + if (potionType == EnumPotionType.Manual) + compound.setInteger("PotionManualId", potionManualId); compound.setInteger("MaxFiringRange", rangedRange); compound.setInteger("FireRate", fireRate); @@ -122,6 +126,8 @@ public class DataStats { compound.setTag("pCustom", pCustom.writeToNBT()); if (pEffect == EnumPotionType.Fire) compound.setBoolean("pBurnItem", pBurnItem); + if (pEffect == EnumPotionType.Manual) + compound.setInteger("pManualId", pManualId); compound.setBoolean("ImmuneToFire", immuneToFire); compound.setBoolean("PotionImmune", potionImmune); @@ -145,7 +151,7 @@ public class DataStats { aggroRange = compound.getInteger("AggroRange"); respawnTime = compound.getInteger("RespawnTime"); spawnCycle = compound.getInteger("SpawnCycle"); - creatureType = EnumCreatureAttribute.values()[compound.getInteger("CreatureType") % EnumPotionType.values().length]; + creatureType = EnumCreatureAttribute.values()[compound.getInteger("CreatureType") % EnumCreatureAttribute.values().length]; ignoreCobweb = compound.getBoolean("IgnoreCobweb"); healthRegen = compound.getFloat("HealthRegen"); combatRegen = compound.getFloat("CombatRegen"); @@ -155,9 +161,11 @@ public class DataStats { swingWarmUp = ValueUtil.clamp(compound.getInteger("SwingWarmup"), 0, 1000); attackRange = compound.getInteger("AttackRange"); knockback = compound.getInteger("KnockBack"); - potionType = EnumPotionType.values()[compound.getInteger("PotionEffect") % EnumPotionType.values().length]; + potionType = EnumPotionType.fromOrdinal(compound.getInteger("PotionEffect")); potionDuration = compound.getInteger("PotionDuration"); potionAmp = compound.getInteger("PotionAmp"); + if (potionType == EnumPotionType.Manual) + potionManualId = compound.getInteger("PotionManualId"); rangedRange = compound.getInteger("MaxFiringRange"); fireRate = compound.getInteger("FireRate"); @@ -180,7 +188,7 @@ public class DataStats { pRender3D = compound.getBoolean("pRender3D"); pSpin = compound.getBoolean("pSpin"); pStick = compound.getBoolean("pStick"); - pEffect = EnumPotionType.values()[compound.getInteger("pEffect") % EnumPotionType.values().length]; + pEffect = EnumPotionType.fromOrdinal(compound.getInteger("pEffect")); pTrail = EnumParticleType.values()[compound.getInteger("pTrail") % EnumParticleType.values().length]; pEffAmp = compound.getInteger("pEffAmp"); fireSound = compound.getString("FiringSound"); @@ -195,6 +203,8 @@ public class DataStats { pCustom = ScriptParticle.fromNBT(compound.getCompoundTag("pCustom")); if (pEffect == EnumPotionType.Fire) pBurnItem = compound.getBoolean("pBurnItem"); + if (pEffect == EnumPotionType.Manual) + pManualId = compound.getInteger("pManualId"); immuneToFire = compound.getBoolean("ImmuneToFire"); potionImmune = compound.getBoolean("PotionImmune"); diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java index a128d3760..36cbfff37 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java @@ -12,7 +12,6 @@ import noppes.npcs.constants.EnumPotionType; public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfieldListener { private DataStats stats; - private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"}; public SubGuiNpcMeleeProperties(DataStats stats) { this.stats = stats; @@ -42,18 +41,28 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi getTextField(4).integersOnly = true; getTextField(4).setMinMaxDefault(0, Integer.MAX_VALUE, 0); addLabel(new GuiNpcLabel(5, "stats.meleeeffect", guiLeft + 5, guiTop + 135)); - addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, potionNames, stats.potionType.ordinal())); + addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, EnumPotionType.getLangKeys(), stats.potionType.ordinal())); + if (stats.potionType == EnumPotionType.Manual) { + addLabel(new GuiNpcLabel(8, "effect.potionid", guiLeft + 198, guiTop + 119)); + addTextField(new GuiNpcTextField(8, this, fontRendererObj, guiLeft + 200, guiTop + 132, 40, 18, stats.potionManualId + "")); + getTextField(8).integersOnly = true; + getTextField(8).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + } + + int y = guiTop + 160; if (stats.potionType != EnumPotionType.None) { - addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, guiTop + 165)); - addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, guiTop + 160, 40, 18, stats.potionDuration + "")); + addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, y + 5)); + addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, y, 40, 18, stats.potionDuration + "")); getTextField(6).integersOnly = true; getTextField(6).setMinMaxDefault(1, Integer.MAX_VALUE, 5); if (stats.potionType != EnumPotionType.Fire) { - addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, guiTop + 195)); - addButton(new GuiButtonBiDirectional(7, guiLeft + 85, guiTop + 190, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp)); + y += 30; + addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, y + 5)); + addButton(new GuiButtonBiDirectional(7, guiLeft + 85, y, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp)); } } - addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + 190, 60, 20, "gui.done")); + + addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + ySize - 26, 60, 20, "gui.done")); } public void unFocused(GuiNpcTextField textfield) { @@ -67,13 +76,15 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi stats.knockback = textfield.getInteger(); } else if (textfield.id == 6) { stats.potionDuration = textfield.getInteger(); + } else if (textfield.id == 8) { + stats.potionManualId = textfield.getInteger(); } } protected void actionPerformed(GuiButton guibutton) { GuiNpcButton button = (GuiNpcButton) guibutton; if (button.id == 5) { - stats.potionType = EnumPotionType.values()[button.getValue()]; + stats.potionType = EnumPotionType.fromOrdinal(button.getValue()); initGui(); } if (button.id == 7) { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java index 8acb8fc8c..e0806a538 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java @@ -15,7 +15,6 @@ import noppes.npcs.constants.EnumPotionType; public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { private DataStats stats; - private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"}; private String[] trailNames = new String[]{"gui.none", "trail.smoke", "trail.portal", "trail.redstone", "trail.lightning", "trail.largesmoke", "trail.magic", "trail.enchant", "trail.crit", "trail.explode", "trail.music", "trail.flame", "trail.lava", "trail.splash", @@ -76,22 +75,29 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL } addLabel(new GuiNpcLabel(7, "stats.rangedeffect", guiLeft + 210, y + 5)); - addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, potionNames, stats.pEffect.ordinal())); + addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, EnumPotionType.getLangKeys(), stats.pEffect.ordinal())); if (stats.pEffect != EnumPotionType.None) { int internalY = y + 30; + if (stats.pEffect == EnumPotionType.Manual) { + addLabel(new GuiNpcLabel(110, "effect.potionid", guiLeft + 210, internalY + 5)); + addTextField(new GuiNpcTextField(11, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pManualId + "")); + getTextField(11).integersOnly = true; + getTextField(11).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + internalY += 30; + } addLabel(new GuiNpcLabel(50, "gui.time", guiLeft + 210, internalY + 5)); addTextField(new GuiNpcTextField(5, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pDur + "")); getTextField(5).integersOnly = true; getTextField(5).setMinMaxDefault(1, Integer.MAX_VALUE, 5); - if (stats.pEffect != EnumPotionType.Fire) { - internalY += 30; - addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5)); - addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp)); - } else { + if (stats.pEffect == EnumPotionType.Fire) { internalY += 30; addLabel(new GuiNpcLabel(100, "stats.burnItem", guiLeft + 210, internalY + 5)); addButton(new GuiNpcButtonYesNo(100, guiLeft + 330, internalY, 52, 20, stats.pBurnItem)); + } else { + internalY += 30; + addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5)); + addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp)); } } @@ -126,6 +132,8 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pSpeed = textfield.getInteger(); } else if (textfield.id == 5) { stats.pDur = textfield.getInteger(); + } else if (textfield.id == 11) { + stats.pManualId = textfield.getInteger(); } } @@ -146,7 +154,7 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pArea = button.getValue(); } if (button.id == 4) { - stats.pEffect = EnumPotionType.values()[button.getValue()]; + stats.pEffect = EnumPotionType.fromOrdinal(button.getValue()); initGui(); } if (button.id == 5) { diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java index b5847d0a0..658cfc022 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -180,7 +180,7 @@ public abstract class GuiNPCInterface extends GuiScreen { return; } } - + for (GuiNpcTextField tf : new ArrayList(textfields.values())) if (tf.enabled) tf.mouseClicked(i, j, k); @@ -415,7 +415,7 @@ public abstract class GuiNPCInterface extends GuiScreen { if (tf.hasHoverText()) tf.drawHover(i, j, subGui); } - + for (GuiScreen gui : extra.values()) gui.drawScreen(i, j, f); @@ -439,8 +439,7 @@ public abstract class GuiNPCInterface extends GuiScreen { int bottomHeight = 0; int bottomTextureV = 0; if (ySize < bgTextureHeight) { - // Keep bottom border from texture bottom (last 6 pixels of actual content) - bottomHeight = 6; + bottomHeight = -1; topHeight = ySize - bottomHeight; bottomTextureV = bgTextureHeight - bottomHeight; } diff --git a/src/main/java/noppes/npcs/constants/EnumPotionType.java b/src/main/java/noppes/npcs/constants/EnumPotionType.java index f6d5ad111..4cf6bc8f8 100644 --- a/src/main/java/noppes/npcs/constants/EnumPotionType.java +++ b/src/main/java/noppes/npcs/constants/EnumPotionType.java @@ -1,5 +1,83 @@ package noppes.npcs.constants; +import net.minecraft.potion.Potion; + public enum EnumPotionType { - None, Fire, Poison, Hunger, Weakness, Slowness, Nausea, Blindness, Wither; + None("gui.none", -1), + Fire("tile.fire.name", -1), + Poison("potion.poison", Potion.poison.id), + Hunger("potion.hunger", Potion.hunger.id), + Weakness("potion.weakness", Potion.weakness.id), + Slowness("potion.moveSlowdown", Potion.moveSlowdown.id), + Nausea("potion.confusion", Potion.confusion.id), + Blindness("potion.blindness", Potion.blindness.id), + Wither("potion.wither", Potion.wither.id), + MiningFatigue("potion.digSlowDown", Potion.digSlowdown.id), + Manual("effect.manual", -1); + + private final String langKey; + private final int potionId; + + EnumPotionType(String langKey, int potionId) { + this.langKey = langKey; + this.potionId = potionId; + } + + public String getLangKey() { + return langKey; + } + + public int getPotionId() { + return potionId; + } + + /** + * Returns the actual potion ID to apply. + * For Manual type, returns the provided manualId. + * For all others, returns the mapped potionId. + */ + public int getResolvedPotionId(int manualId) { + if (this == Manual) return manualId; + return potionId; + } + + public static String[] getLangKeys() { + EnumPotionType[] types = values(); + String[] keys = new String[types.length]; + for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; + return keys; + } + + /** + * Returns lang keys excluding None. For use in effect lists where None is not a valid choice. + */ + public static String[] getLangKeysNoNone() { + EnumPotionType[] types = values(); + String[] keys = new String[types.length - 1]; + for (int i = 1; i < types.length; i++) keys[i - 1] = types[i].langKey; + return keys; + } + + /** + * Maps a 0-based index (excluding None) back to the corresponding EnumPotionType. + * Index 0 = Fire, 1 = Poison, etc. + */ + public static EnumPotionType fromIndexNoNone(int index) { + return fromOrdinal(index + 1); + } + + public static EnumPotionType fromOrdinal(int ordinal) { + EnumPotionType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return None; + } + + /** + * Checks if the given potion ID is valid and registered in the Minecraft potion registry. + */ + public static boolean isValidPotionId(int id) { + return id >= 0 && id < Potion.potionTypes.length && Potion.potionTypes[id] != null; + } } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 6e4b40884..187ce583d 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -384,11 +384,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti } } - if (stats.potionType != EnumPotionType.None) { - if (stats.potionType != EnumPotionType.Fire) - ((EntityLivingBase) receiver).addPotionEffect(new PotionEffect(this.getPotionEffect(stats.potionType), stats.potionDuration * 20, stats.potionAmp)); - else - receiver.setFire(stats.potionDuration); + if (stats.potionType == EnumPotionType.Fire) { + receiver.setFire(stats.potionDuration); + } else if (stats.potionType != EnumPotionType.None) { + int potionId = stats.potionType.getResolvedPotionId(stats.potionManualId); + if (EnumPotionType.isValidPotionId(potionId)) { + ((EntityLivingBase) receiver).addPotionEffect(new PotionEffect(potionId, stats.potionDuration * 20, stats.potionAmp)); + } } return didAttack; } @@ -1043,29 +1045,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti return weight; } - /* - * Used for getting the applied potion effect from dataStats. - */ - private int getPotionEffect(EnumPotionType p) { - switch (p) { - case Poison: - return Potion.poison.id; - case Hunger: - return Potion.hunger.id; - case Weakness: - return Potion.weakness.id; - case Slowness: - return Potion.moveSlowdown.id; - case Nausea: - return Potion.confusion.id; - case Blindness: - return Potion.blindness.id; - case Wither: - return Potion.wither.id; - default: - return 0; - } - } @Override public void setAir(int air) { diff --git a/src/main/java/noppes/npcs/entity/EntityProjectile.java b/src/main/java/noppes/npcs/entity/EntityProjectile.java index e25a66083..5d322ade8 100644 --- a/src/main/java/noppes/npcs/entity/EntityProjectile.java +++ b/src/main/java/noppes/npcs/entity/EntityProjectile.java @@ -94,6 +94,7 @@ public class EntityProjectile extends EntityThrowable { public boolean destroyTerrain = true; public int explosiveRadius = 0; public EnumPotionType effect = EnumPotionType.None; + public int manualPotionId = 0; public boolean burnItem = true; public int duration = 5; public int amplify = 0; @@ -508,12 +509,12 @@ public class EntityProjectile extends EntityThrowable { } } - if (this.effect != EnumPotionType.None && entityliving != null) { - if (this.effect != EnumPotionType.Fire) { - int p = this.getPotionEffect(effect); - entityliving.addPotionEffect(new PotionEffect(p, this.duration * 20, this.amplify)); - } else { - movingobjectposition.entityHit.setFire(duration); + if (this.effect == EnumPotionType.Fire && entityliving != null) { + movingobjectposition.entityHit.setFire(duration); + } else if (this.effect != EnumPotionType.None && entityliving != null) { + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { + entityliving.addPotionEffect(new PotionEffect(potionId, this.duration * 20, this.amplify)); } } } else if (this.hasGravity() && (this.isArrow() || this.sticksToWalls())) { @@ -637,21 +638,23 @@ public class EntityProjectile extends EntityThrowable { d1 = 1.0D; } - int i = this.getPotionEffect(effect); + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); - if (Potion.potionTypes[i].isInstant()) { - Potion.potionTypes[i].affectEntity(this.getThrower(), entitylivingbase, this.amplify, d1); - } else { - int j = (int) (d1 * (double) this.duration + 0.5D); + if (EnumPotionType.isValidPotionId(potionId)) { + if (Potion.potionTypes[potionId].isInstant()) { + Potion.potionTypes[potionId].affectEntity(this.getThrower(), entitylivingbase, this.amplify, d1); + } else { + int j = (int) (d1 * (double) this.duration + 0.5D); - if (j > 20) { - entitylivingbase.addPotionEffect(new PotionEffect(i, j, this.amplify)); + if (j > 20) { + entitylivingbase.addPotionEffect(new PotionEffect(potionId, j, this.amplify)); + } } } } } } - this.worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), this.getPotionColor(this.effect)); + this.worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), this.getPotionColor()); } } @@ -693,6 +696,8 @@ public class EntityProjectile extends EntityThrowable { par1NBTTagCompound.setBoolean("explosive", explosive); par1NBTTagCompound.setInteger("accuracy", accuracy); par1NBTTagCompound.setInteger("PotionEffect", effect.ordinal()); + if (effect == EnumPotionType.Manual) + par1NBTTagCompound.setInteger("PotionManualId", manualPotionId); par1NBTTagCompound.setString("trail", this.dataWatcher.getWatchableObjectString(22)); par1NBTTagCompound.setByte("Render3D", this.dataWatcher.getWatchableObjectByte(28)); par1NBTTagCompound.setByte("Spins", this.dataWatcher.getWatchableObjectByte(29)); @@ -723,7 +728,9 @@ public class EntityProjectile extends EntityThrowable { this.accelerate = par1NBTTagCompound.getBoolean("accelerate"); this.explosive = par1NBTTagCompound.getBoolean("explosive"); this.accuracy = par1NBTTagCompound.getInteger("accuracy"); - this.effect = EnumPotionType.values()[par1NBTTagCompound.getInteger("PotionEffect") % EnumPotionType.values().length]; + this.effect = EnumPotionType.fromOrdinal(par1NBTTagCompound.getInteger("PotionEffect")); + if (effect == EnumPotionType.Manual) + this.manualPotionId = par1NBTTagCompound.getInteger("PotionManualId"); this.dataWatcher.updateObject(22, par1NBTTagCompound.getString("trail")); this.dataWatcher.updateObject(23, Integer.valueOf(par1NBTTagCompound.getInteger("size"))); this.dataWatcher.updateObject(24, Byte.valueOf((byte) (par1NBTTagCompound.getBoolean("glows") ? 1 : 0))); @@ -774,46 +781,12 @@ public class EntityProjectile extends EntityThrowable { return this.thrower; } - private int getPotionEffect(EnumPotionType p) { - switch (p) { - case Poison: - return Potion.poison.id; - case Hunger: - return Potion.hunger.id; - case Weakness: - return Potion.weakness.id; - case Slowness: - return Potion.moveSlowdown.id; - case Nausea: - return Potion.confusion.id; - case Blindness: - return Potion.blindness.id; - case Wither: - return Potion.wither.id; - default: - return 0; - } - } - - private int getPotionColor(EnumPotionType p) { - switch (p) { - case Poison: - return 32660; - case Hunger: - return 32660; - case Weakness: - return 32696; - case Slowness: - return 32698; - case Nausea: - return 32732; - case Blindness: - return Potion.blindness.id; - case Wither: - return 32732; - default: - return 0; + private int getPotionColor() { + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { + return Potion.potionTypes[potionId].getLiquidColor(); } + return 0; } public void getStatProperties(DataStats stats) { @@ -823,6 +796,7 @@ public class EntityProjectile extends EntityThrowable { this.explosive = stats.pExplode; this.explosiveRadius = stats.pArea; this.effect = stats.pEffect; + this.manualPotionId = stats.pManualId; this.burnItem = stats.pBurnItem; this.duration = stats.pDur; this.amplify = stats.pEffAmp; diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 3e8fa323a..a29759c31 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2007,6 +2007,8 @@ condition.hover.threshold=Health percentage threshold (1-99%) effect.hover.type=Potion effect type to apply to targets effect.hover.duration=Effect duration in ticks (20 ticks = 1 second) effect.hover.amplifier=Effect strength level (higher = stronger) +effect.manual=Manual +effect.potionid=Potion ID # ========================================= # Auction House From f4d7861a9d3337f49bb9c41643d6a2aaf8588ae5 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 13 Feb 2026 14:52:58 -0500 Subject: [PATCH 40/76] fix: prevent special key detection when a screen is open --- src/main/java/noppes/npcs/client/ClientTickHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 203cef3e2..631ad92b0 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -62,7 +62,7 @@ public class ClientTickHandler { if (event.phase == Phase.START) { EntityPlayer player = mc.thePlayer; if (player != null) { - boolean specialKeyDown = ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode()); + boolean specialKeyDown = mc.currentScreen == null && ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode()); if (specialKeyDown != lastSpecialKeyDown) { PlayerData data = CustomNpcs.proxy.getPlayerData(player); if (data != null) { From 910f3b3744a2b8399b1ec2aea3702e3149f7d6be Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 13 Feb 2026 15:01:28 -0500 Subject: [PATCH 41/76] Add NPC inline edit support and adjust ability launch mechanics --- .../controllers/data/ability/Ability.java | 14 ++++++++++ .../npcs/entity/EntityAbilityBeam.java | 3 +++ .../npcs/entity/EntityAbilityDisc.java | 3 +++ .../kamkeel/npcs/entity/EntityAbilityOrb.java | 3 +++ .../npcs/entity/EntityAbilityProjectile.java | 27 +++++++++++++++++++ .../kamkeel/npcs/util/AnchorPointHelper.java | 25 ++++++++++++++--- .../client/gui/advanced/GuiNPCAbilities.java | 4 +++ 7 files changed, 76 insertions(+), 3 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 b2743f629..f0b8ceb07 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -130,6 +130,12 @@ public abstract class Ability implements IAbility { protected transient boolean previewMode = false; protected transient PreviewEntityHandler previewEntityHandler; + // ═══════════════════════════════════════════════════════════════════ + // GUI CONTEXT (client-side only, not saved) + // ═══════════════════════════════════════════════════════════════════ + + protected transient boolean npcInlineEdit = false; + // ═══════════════════════════════════════════════════════════════════ // ABSTRACT METHODS // ═══════════════════════════════════════════════════════════════════ @@ -1282,6 +1288,14 @@ public abstract class Ability implements IAbility { return false; } + public boolean isNpcInlineEdit() { + return npcInlineEdit; + } + + public void setNpcInlineEdit(boolean npcInlineEdit) { + this.npcInlineEdit = npcInlineEdit; + } + public int getWeight() { return weight; } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 1427b298f..488dfa39e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -274,6 +274,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { setCharging(false); + // For player casters, snap to look vector for crosshair-aligned launch + snapToPlayerLookVector(); + // Origin (tail) stays at the charged position - where the orb was // This is the same for both anchored and non-anchored modes startX = posX; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index edd7b3dff..04bf2b777 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -226,6 +226,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { setCharging(false); + // For player casters, snap to look vector for crosshair-aligned launch + snapToPlayerLookVector(); + // Update start position to current position startX = posX; startY = posY; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java index 73e8c26f3..c461e9575 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -200,6 +200,9 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { setCharging(false); + // For player casters, snap to look vector for crosshair-aligned launch + snapToPlayerLookVector(); + // Update start position to current position startX = posX; startY = posY; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index 7080ce2ef..e70b06009 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -17,6 +17,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.NpcDamageSource; import noppes.npcs.api.entity.IEnergyProjectile; @@ -428,6 +429,32 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP } } + // ==================== LAUNCH HELPERS ==================== + + /** + * For player casters, snap the projectile to a position along the player's look vector. + * This ensures projectiles launch aligned with the crosshair rather than from the hand anchor. + * Only affects player casters; NPC projectiles launch from their anchor position as configured. + * Should be called in startMoving/startFiring BEFORE setting startX/Y/Z. + */ + protected void snapToPlayerLookVector() { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityPlayer)) return; + + Vec3 look = owner.getLookVec(); + double eyeY = owner.posY + owner.getEyeHeight(); + float frontDist = Math.max(0.5f, size * 0.5f); + + double newX = owner.posX + look.xCoord * frontDist; + double newY = eyeY + look.yCoord * frontDist; + double newZ = owner.posZ + look.zCoord * frontDist; + + setPosition(newX, newY, newZ); + prevPosX = newX; + prevPosY = newY; + prevPosZ = newZ; + } + // ==================== ENTITY HELPERS ==================== public Entity getOwnerEntity() { diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index 20d557bef..802841c2a 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -2,6 +2,7 @@ package kamkeel.npcs.util; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.EnergyAnchorData; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.Vec3; import noppes.npcs.constants.EnumAnimationPart; @@ -18,6 +19,12 @@ import noppes.npcs.entity.data.ModelScalePart; */ public class AnchorPointHelper { + // Y offset correction for the local client player. + // EntityPlayerSP.posY is at feet, but the renderer adds yOffset (1.62) visually, + // so anchor positions computed from posY appear ~1.6 blocks too high for the local player. + // Remote players and NPCs don't have this discrepancy. + private static final float CLIENT_PLAYER_Y_OFFSET = -1.6F; + // Default biped model constants (in model units, 1 unit = 1/16 block) private static final float MODEL_SCALE = 1f / 16f; @@ -68,7 +75,7 @@ public class AnchorPointHelper { float anchorZ = anchorData.anchorOffsetZ; double x = entity.posX; - double y = entity.posY; + double y = entity.posY + getClientPlayerYCorrection(entity); double z = entity.posZ; float headYaw = (float) Math.toRadians(entity.rotationYawHead); @@ -127,6 +134,18 @@ public class AnchorPointHelper { return 1f; } + /** + * Returns Y offset correction for the local client player. + * On the client, EntityPlayerSP.posY is at feet level but the renderer adds yOffset (1.62), + * causing anchor positions to appear ~1.6 blocks too high. This matches DBC's correction. + */ + private static double getClientPlayerYCorrection(EntityLivingBase entity) { + if (entity.worldObj.isRemote && entity instanceof EntityPlayerSP) { + return CLIENT_PLAYER_Y_OFFSET; + } + return 0.0; + } + // Default arm scale (no scaling) private static final ModelScalePart DEFAULT_ARM_SCALE = new ModelScalePart(); @@ -251,7 +270,7 @@ public class AnchorPointHelper { // Final world position double worldX = entity.posX + worldOffsetX; - double worldY = entity.posY + shoulderHeight - blockY; + double worldY = entity.posY + getClientPlayerYCorrection(entity) + shoulderHeight - blockY; double worldZ = entity.posZ + worldOffsetZ; // Rotate offsets relative to entity's body yaw @@ -324,7 +343,7 @@ public class AnchorPointHelper { double armLengthOffset = armScale.scaleY * 0.3 * scale; double x = entity.posX + lateralX + forwardX; - double y = entity.posY + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset; + double y = entity.posY + getClientPlayerYCorrection(entity) + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset; double z = entity.posZ + lateralZ + forwardZ; // Rotate offsets relative to entity's body yaw diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index 4b9e99a13..f8ed53c7c 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -254,6 +254,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } else { Ability ability = slot.getAbility(); if (ability != null) { + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } } @@ -303,6 +304,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Ability abilityToSave = npcSlots.get(selectedAbilityIndex).getAbility(); if (abilityToSave != null) { if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) { + abilityToSave.setNpcInlineEdit(true); setSubGui(abilityToSave.createConfigGui(this)); } else { setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave, null, existingPresetNames)); @@ -632,6 +634,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC setSubGui(new SubGuiAbilityEditMode()); } else { if (ability != null) { + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } } @@ -690,6 +693,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Ability ability = slot.getAbility(); if (ability != null) { ability.setId(UUID.randomUUID().toString()); + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } updateNpcAbilitiesList(); From 09ab6458a14e62535ce59cd267624509ee9db5ce Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 13 Feb 2026 16:28:45 -0500 Subject: [PATCH 42/76] refactor: enhance collision detection for ability movement --- .../data/ability/type/AbilityCharge.java | 27 +++++++++++++++++- .../data/ability/type/AbilityDash.java | 28 ++++++++++++++++++- .../data/ability/type/AbilitySlam.java | 11 ++++---- 3 files changed, 59 insertions(+), 7 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 50257e023..7cfb44428 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 @@ -258,7 +258,32 @@ public class AbilityCharge extends Ability implements IAbilityCharge { double nextX = chargeDirection.xCoord * chargeSpeed; double nextZ = chargeDirection.zCoord * chargeSpeed; AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); - return !caster.worldObj.getCollidingBoundingBoxes(caster, nextBox).isEmpty(); + double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); + + int x1 = (int) Math.floor(nextBox.minX); + int x2 = (int) Math.floor(nextBox.maxX + 1.0); + int y1 = (int) Math.floor(nextBox.minY) - 1; + int y2 = (int) Math.floor(nextBox.maxY + 1.0); + int z1 = (int) Math.floor(nextBox.minZ); + int z2 = (int) Math.floor(nextBox.maxZ + 1.0); + + java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); + for (int bx = x1; bx < x2; bx++) { + for (int bz = z1; bz < z2; bz++) { + for (int by = y1; by < y2; by++) { + net.minecraft.block.Block block = caster.worldObj.getBlock(bx, by, bz); + if (!block.getMaterial().blocksMovement()) continue; + collisionBoxes.clear(); + block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); + for (AxisAlignedBB box : collisionBoxes) { + if (box.maxY > stepThreshold) { + return true; + } + } + } + } + } + return false; } @Override 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 7e3375ca7..6070342d7 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 @@ -257,7 +257,33 @@ public class AbilityDash extends Ability implements IAbilityDash { if (dashDirection == null) return true; double nextX = dashDirection.xCoord * dashSpeed; double nextZ = dashDirection.zCoord * dashSpeed; - return !caster.worldObj.getCollidingBoundingBoxes(caster, caster.boundingBox.copy().offset(nextX, 0, nextZ)).isEmpty(); + AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); + double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); + + int x1 = (int) Math.floor(nextBox.minX); + int x2 = (int) Math.floor(nextBox.maxX + 1.0); + int y1 = (int) Math.floor(nextBox.minY) - 1; + int y2 = (int) Math.floor(nextBox.maxY + 1.0); + int z1 = (int) Math.floor(nextBox.minZ); + int z2 = (int) Math.floor(nextBox.maxZ + 1.0); + + java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); + for (int bx = x1; bx < x2; bx++) { + for (int bz = z1; bz < z2; bz++) { + for (int by = y1; by < y2; by++) { + net.minecraft.block.Block block = caster.worldObj.getBlock(bx, by, bz); + if (!block.getMaterial().blocksMovement()) continue; + collisionBoxes.clear(); + block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); + for (AxisAlignedBB box : collisionBoxes) { + if (box.maxY > stepThreshold) { + return true; + } + } + } + } + } + return false; } @Override 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 0bd9613a5..31c109ab8 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 @@ -283,11 +283,12 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.fallDistance = 0; } - // Check for landing - if (caster.onGround && airTicks > 3) { - // Landed! - onLanding(caster, world); - return; + // Check for landing: hit the ground or hit a wall mid-flight + if (airTicks > 3) { + if (caster.onGround || caster.isCollidedHorizontally) { + onLanding(caster, world); + return; + } } // Timeout protection - force landing after max air time From 0b0dcdc58dfabc6fc89887bc60804a498211e949 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 14 Feb 2026 03:50:28 -0500 Subject: [PATCH 43/76] feat: implement player ability state management with rotation and position locking --- .../data/ability/type/AbilitySlam.java | 54 +++-- .../kamkeel/npcs/network/PacketHandler.java | 2 + .../npcs/network/enums/EnumDataPacket.java | 1 + .../ability/PlayerAbilityStatePacket.java | 84 +++++++ .../noppes/npcs/ScriptPlayerEventHandler.java | 10 +- .../npcs/client/ClientAbilityState.java | 59 +++++ .../noppes/npcs/client/ClientTickHandler.java | 14 ++ .../controllers/data/PlayerAbilityData.java | 224 +++++++++++++++++- 8 files changed, 427 insertions(+), 21 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java create mode 100644 src/main/java/noppes/npcs/client/ClientAbilityState.java 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 31c109ab8..22fd99416 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 @@ -86,10 +86,20 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { if (isPlayerCaster(caster)) { - // Player: slam will launch from current position, no target tracking needed - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; + // Player: update target along look direction during windup + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else { + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); + double launchDist = Math.max(4.0, maxRange * 0.5); + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + } } else { // NPC: update target position during windup for telegraph tracking if (targetingMode == TargetingMode.AOE_SELF) { @@ -139,18 +149,22 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } /** - * Player slam: Launch straight up. Player controls horizontal movement via WASD. + * Player slam: Launch in look direction using same ballistic arc as NPC slam. * AOE damage triggers wherever the player lands. */ private void executePlayerSlam(EntityLivingBase caster) { - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; + // Calculate target position along player's look direction (horizontal only) + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); - double vy = calculateLaunchVelocity(Math.max(1.0, leapHeight)); - caster.motionY = vy; - hasLaunched = true; - caster.velocityChanged = true; + double launchDist = Math.max(4.0, maxRange * 0.5); + + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + + launchTowardTarget(caster); } /** @@ -297,14 +311,18 @@ public class AbilitySlam extends Ability implements IAbilitySlam { return; } - // NPC: face toward target destination while in air - // Player: free look — player controls their own camera - if (!isPreview() && !isPlayerCaster(caster)) { + // Face toward target destination while in air (both NPC and Player) + if (!isPreview()) { double dx = targetX - caster.posX; double dz = targetZ - caster.posZ; - float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); - caster.rotationYaw = targetYaw; - caster.rotationYawHead = targetYaw; + if (dx * dx + dz * dz > 0.25) { + float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); + caster.rotationYaw = targetYaw; + caster.rotationYawHead = targetYaw; + if (isPlayerCaster(caster)) { + caster.velocityChanged = true; + } + } } } diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index 6db07c841..dee4a3a94 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.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; @@ -588,6 +589,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new TelegraphSpawnPacket()); DATA_PACKET.registerPacket(new TelegraphRemovePacket()); DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); + DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); } 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 18321d0a4..8362cb3c5 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -63,6 +63,7 @@ public enum EnumDataPacket { TELEGRAPH_SPAWN, TELEGRAPH_REMOVE, PLAYER_ABILITY_SYNC, + PLAYER_ABILITY_STATE, // Auction System AUCTION_DATA, diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java new file mode 100644 index 000000000..03c0b82b4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java @@ -0,0 +1,84 @@ +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 net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.client.ClientAbilityState; + +import java.io.IOException; + +/** + * Lightweight packet syncing ability lock state from server to client. + * Sent every tick during ability execution when flags change, and once when ability ends. + * + * Flags byte layout: + * bit 0: movement locked (suppress WASD, zero motion) + * bit 1: rotation locked (freeze yaw/pitch) + * bit 2: has ability movement (ability controls motion — suppress WASD but don't zero) + * bit 3: position locked (freeze position) + */ +public final class PlayerAbilityStatePacket extends AbstractPacket { + public static final String packetName = "Data|PlayerAbilityState"; + + public static final byte FLAG_MOVEMENT_LOCKED = 1; + public static final byte FLAG_ROTATION_LOCKED = 2; + public static final byte FLAG_HAS_ABILITY_MOVEMENT = 4; + public static final byte FLAG_POSITION_LOCKED = 8; + + private byte flags; + private float lockedYaw; + private float lockedPitch; + + public PlayerAbilityStatePacket() { + } + + public PlayerAbilityStatePacket(byte flags, float lockedYaw, float lockedPitch) { + this.flags = flags; + this.lockedYaw = lockedYaw; + this.lockedPitch = lockedPitch; + } + + @Override + public Enum getType() { + return EnumDataPacket.PLAYER_ABILITY_STATE; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeByte(flags); + if ((flags & FLAG_ROTATION_LOCKED) != 0) { + out.writeFloat(lockedYaw); + out.writeFloat(lockedPitch); + } + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + byte flags = in.readByte(); + float yaw = 0, pitch = 0; + if ((flags & FLAG_ROTATION_LOCKED) != 0) { + yaw = in.readFloat(); + pitch = in.readFloat(); + } + ClientAbilityState.update(flags, yaw, pitch); + } + + /** + * Send the current ability state to the player's client. + */ + public static void sendToPlayer(EntityPlayerMP player, byte flags, float lockedYaw, float lockedPitch) { + PacketHandler.Instance.sendToPlayer(new PlayerAbilityStatePacket(flags, lockedYaw, lockedPitch), player); + } +} diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index c77083fa1..909634a09 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -8,6 +8,7 @@ import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.addon.DBCAddon; import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.util.AttributeAttackUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -100,9 +101,14 @@ public class ScriptPlayerEventHandler { playerData.abilityData.tick(player); // Lock player movement during ability phases that require it + // Skip zeroing if the ability has its own movement (Charge/Dash/Slam) if (playerData.abilityData.isMovementLocked()) { - player.motionX = 0; - player.motionZ = 0; + Ability current = playerData.abilityData.getCurrentAbility(); + if (current == null || !current.hasAbilityMovement()) { + player.motionX = 0; + player.motionZ = 0; + player.velocityChanged = true; + } } if (playerData.updateClient) { diff --git a/src/main/java/noppes/npcs/client/ClientAbilityState.java b/src/main/java/noppes/npcs/client/ClientAbilityState.java new file mode 100644 index 000000000..8092a69a3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/ClientAbilityState.java @@ -0,0 +1,59 @@ +package noppes.npcs.client; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; + +/** + * Client-side state holder for player ability lock flags. + * Updated by {@link PlayerAbilityStatePacket} from the server. + * Read by {@link ClientTickHandler} to suppress WASD input and enforce rotation. + */ +@SideOnly(Side.CLIENT) +public class ClientAbilityState { + public static boolean movementLocked = false; + public static boolean rotationLocked = false; + public static boolean hasAbilityMovement = false; + public static boolean positionLocked = false; + public static float lockedYaw = 0; + public static float lockedPitch = 0; + + /** + * Update state from a received packet. + */ + public static void update(byte flags, float yaw, float pitch) { + movementLocked = (flags & PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED) != 0; + rotationLocked = (flags & PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED) != 0; + hasAbilityMovement = (flags & PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT) != 0; + positionLocked = (flags & PlayerAbilityStatePacket.FLAG_POSITION_LOCKED) != 0; + lockedYaw = yaw; + lockedPitch = pitch; + } + + /** + * Whether player WASD movement input should be suppressed. + * True when movement/position is locked or ability has its own movement. + */ + public static boolean shouldSuppressMovementInput() { + return movementLocked || hasAbilityMovement || positionLocked; + } + + /** + * Whether player camera rotation should be locked. + */ + public static boolean shouldLockRotation() { + return rotationLocked; + } + + /** + * Reset all state. Called on world change / disconnect. + */ + public static void reset() { + movementLocked = false; + rotationLocked = false; + hasAbilityMovement = false; + positionLocked = false; + lockedYaw = 0; + lockedPitch = 0; + } +} diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 631ad92b0..4c6b7a044 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -56,6 +56,7 @@ public class ClientTickHandler { if ((this.prevWorld == null || mc.theWorld == null) && this.prevWorld != mc.theWorld) { if (mc.theWorld == null) { ClientCacheHandler.clearCache(); + ClientAbilityState.reset(); } this.prevWorld = mc.theWorld; } @@ -72,6 +73,19 @@ public class ClientTickHandler { lastSpecialKeyDown = specialKeyDown; } + // Suppress player input during ability-controlled phases + if (ClientAbilityState.shouldSuppressMovementInput()) { + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + } + if (ClientAbilityState.shouldLockRotation()) { + mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch; + } + if (player.ridingEntity instanceof EntityNPCInterface) { EntityNPCInterface mount = (EntityNPCInterface) player.ridingEntity; if (mount.advanced.role == EnumRoleType.Mount && mount.roleInterface instanceof RoleMount) { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 3e6489b1c..7807074f3 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -19,6 +19,7 @@ import noppes.npcs.api.ability.IPlayerAbilityData; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import java.util.ArrayList; @@ -77,6 +78,26 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private transient EntityLivingBase currentTarget; + /** + * Rotation lock state - freezes player yaw/pitch during ability phases. + */ + private transient boolean rotationLocked = false; + private transient float lockedYaw = 0; + private transient float lockedPitch = 0; + + /** + * Position lock state - freezes player position during ability phases. + */ + private transient boolean positionLocked = false; + private transient double lockedPosX = 0; + private transient double lockedPosY = 0; + private transient double lockedPosZ = 0; + + /** + * Last synced state flags byte for change detection (avoids spamming packets). + */ + private transient byte lastSyncedFlags = 0; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -100,6 +121,20 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (currentAbility != null && currentAbility.isExecuting()) { tickCurrentAbility(player); + + // Apply rotation and position locks after ability tick + applyRotationControl(player); + applyPositionLock(player); + + // Sync lock state to client (only sends when flags change) + syncAbilityStateIfNeeded(player); + } else { + // Safety: release orphaned locks if no ability is executing + if (rotationLocked || positionLocked) { + releaseRotationControl(); + releaseLockedPosition(); + syncAbilityStateClear(player); + } } } @@ -114,17 +149,47 @@ public class PlayerAbilityData implements IPlayerAbilityData { switch (currentAbility.getPhase()) { case WINDUP: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up locks + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(player); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(player); + } + spawnTelegraph(currentAbility, player, null); + playAbilitySound(player, currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } currentAbility.onWindUpTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); break; case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { // Just entered ACTIVE phase - lock all telegraph positions for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } removeTelegraph(currentAbility, player); + // Handle rotation control transition from WINDUP to ACTIVE + if (currentAbility.isRotationLockedDuringActive()) { + if (!rotationLocked) { + captureLockedRotation(player); + } + } else if (rotationLocked) { + releaseRotationControl(); + } + + // Handle position lock transition from WINDUP to ACTIVE + if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { + if (!positionLocked) { + captureLockedPosition(player); + } + } else if (positionLocked) { + releaseLockedPosition(); + } + // Play active sound and animation playAbilitySound(player, currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); @@ -143,6 +208,18 @@ public class PlayerAbilityData implements IPlayerAbilityData { handleAbilityCompletion(player); return; } + + // Release locks during burst delay + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); break; case DAZED: @@ -163,6 +240,10 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentAbility.onComplete(player, currentTarget); + // Release all locks + releaseRotationControl(); + releaseLockedPosition(); + // Apply universal cooldown (using base cooldownTicks only, not min/max random) if (!currentAbility.isIgnoreCooldown()) { cooldownEndTime = player.worldObj.getTotalWorldTime() + currentAbility.getCooldownTicks(); @@ -174,6 +255,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentAbility = null; currentAbilityKey = null; currentTarget = null; + + // Send cleared state to client + syncAbilityStateClear(player); } // ═══════════════════════════════════════════════════════════════════ @@ -231,9 +315,21 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (ability.getPhase() == AbilityPhase.ACTIVE) { // Windup was 0 — skip telegraph/windup and go straight to active + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(player); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(player); + } executeImmediate(ability, player); } else { // Normal windup flow + if (ability.isRotationLockedDuringWindup()) { + captureLockedRotation(player); + } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(player); + } spawnTelegraph(ability, player, null); playAbilitySound(player, ability.getWindUpSound()); playAbilityAnimation(ability.getWindUpAnimation()); @@ -412,9 +508,12 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (currentAbility != null && currentAbility.isExecuting()) { currentAbility.interrupt(); stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); currentAbility = null; currentAbilityKey = null; currentTarget = null; + syncAbilityStateClear(playerData.player); } } @@ -493,6 +592,129 @@ public class PlayerAbilityData implements IPlayerAbilityData { && currentAbility.isMovementLockedForCurrentPhase(); } + // ═══════════════════════════════════════════════════════════════════ + // ROTATION CONTROL + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current rotation values to lock player's look direction. + */ + private void captureLockedRotation(EntityPlayer player) { + lockedYaw = player.rotationYaw; + lockedPitch = player.rotationPitch; + rotationLocked = true; + } + + /** + * Release rotation lock. + */ + private void releaseRotationControl() { + rotationLocked = false; + } + + /** + * Apply rotation control on the server side. + * Enforces locked rotation values on the player entity. + */ + private void applyRotationControl(EntityPlayer player) { + if (!rotationLocked || currentAbility == null) return; + + if (currentAbility.isRotationLockedForCurrentPhase()) { + player.rotationYaw = lockedYaw; + player.rotationPitch = lockedPitch; + player.prevRotationYaw = lockedYaw; + player.prevRotationPitch = lockedPitch; + if (player instanceof EntityPlayerMP) { + player.rotationYawHead = lockedYaw; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current position to lock player in place. + */ + private void captureLockedPosition(EntityPlayer player) { + lockedPosX = player.posX; + lockedPosY = player.posY; + lockedPosZ = player.posZ; + positionLocked = true; + } + + /** + * Release position lock. + */ + private void releaseLockedPosition() { + positionLocked = false; + } + + /** + * Apply position lock on the server side. + * Snaps player back to locked position and zeroes motion. + */ + private void applyPositionLock(EntityPlayer player) { + if (!positionLocked) return; + + player.setPosition(lockedPosX, lockedPosY, lockedPosZ); + player.prevPosX = lockedPosX; + player.prevPosY = lockedPosY; + player.prevPosZ = lockedPosZ; + player.motionX = 0; + player.motionZ = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // ABILITY STATE SYNC + // ═══════════════════════════════════════════════════════════════════ + + /** + * Build the current ability state flags byte. + */ + private byte getAbilityStateFlags() { + byte flags = 0; + if (currentAbility == null || !currentAbility.isExecuting()) return flags; + + if (currentAbility.isMovementLockedForCurrentPhase()) { + flags |= PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED; + } + if (rotationLocked && currentAbility.isRotationLockedForCurrentPhase()) { + flags |= PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED; + } + if (currentAbility.hasAbilityMovement() && currentAbility.getPhase() == AbilityPhase.ACTIVE) { + flags |= PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT; + } + if (positionLocked) { + flags |= PlayerAbilityStatePacket.FLAG_POSITION_LOCKED; + } + return flags; + } + + /** + * Send ability state to client if flags changed since last sync. + */ + private void syncAbilityStateIfNeeded(EntityPlayer player) { + if (!(player instanceof EntityPlayerMP)) return; + byte flags = getAbilityStateFlags(); + if (flags != lastSyncedFlags) { + lastSyncedFlags = flags; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, flags, lockedYaw, lockedPitch); + } + } + + /** + * Send cleared (all-zero) state to client. Called on ability completion/interrupt. + */ + private void syncAbilityStateClear(EntityPlayer player) { + if (!(player instanceof EntityPlayerMP)) return; + if (lastSyncedFlags != 0) { + lastSyncedFlags = 0; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0); + } + } + // ═══════════════════════════════════════════════════════════════════ // TELEGRAPH // ═══════════════════════════════════════════════════════════════════ From 9fcda980ee56cab60a69178184612eadf69c4683 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 14 Feb 2026 03:57:40 -0500 Subject: [PATCH 44/76] fix: convert gradle-plugins from directory to submodule Matches dev branch's submodule reference so branch switching works seamlessly. Co-Authored-By: Claude Opus 4.6 --- gradle-plugins | 1 + gradle-plugins/.gitignore | 9 - gradle-plugins/README.md | 94 -- gradle-plugins/build.gradle | 50 - gradle-plugins/settings.gradle | 1 - .../groovy/dts/GenerateTypeScriptTask.groovy | 175 --- .../dts/JavaToTypeScriptConverter.groovy | 1353 ----------------- .../dts/TypeScriptGeneratorPlugin.groovy | 17 - .../dts.typescript-generator.properties | 1 - 9 files changed, 1 insertion(+), 1700 deletions(-) create mode 160000 gradle-plugins delete mode 100644 gradle-plugins/.gitignore delete mode 100644 gradle-plugins/README.md delete mode 100644 gradle-plugins/build.gradle delete mode 100644 gradle-plugins/settings.gradle delete mode 100644 gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy delete mode 100644 gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy delete mode 100644 gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy delete mode 100644 gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties diff --git a/gradle-plugins b/gradle-plugins new file mode 160000 index 000000000..f1c82c10c --- /dev/null +++ b/gradle-plugins @@ -0,0 +1 @@ +Subproject commit f1c82c10c8c92eaaf55044cf931da5e1c7a2668f diff --git a/gradle-plugins/.gitignore b/gradle-plugins/.gitignore deleted file mode 100644 index 22bff6717..000000000 --- a/gradle-plugins/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -/.gradle -/build -/out -/bin -/.idea -/.vscode -/.settings -.project -.classpath \ No newline at end of file diff --git a/gradle-plugins/README.md b/gradle-plugins/README.md deleted file mode 100644 index 1e0e7fba2..000000000 --- a/gradle-plugins/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# dts-gradle-plugin - -This repo contains the Gradle plugin for generating TypeScript `.d.ts` files for the CustomNPC-Plus API. - -These files are used for the generation of auto-completion suggestions and type/interface documentation when scripting -in the Script Editor in-game. - -### Implementation using JitPack - -Add JitPack to the buildscript and depend on the plugin JAR. Using `main-SNAPSHOT` will build the latest `main` commit; -for reproducible builds use a tag or commit hash instead. - -`settings.gradle` -```gradle -pluginManagement { - resolutionStrategy { - eachPlugin { - if(requested.id.toString() == "dts.typescript-generator") { - useModule("com.github.bigguy345:dts-gradle-plugin:main-SNAPSHOT") - } - } - } - - - repositories { - maven { url "https://jitpack.io" } - gradlePluginPortal() - mavenCentral() - mavenLocal() - } -} -``` - - - - -`build.gradle`: - -```gradle -plugins { - id 'dts.typescript-generator' -} - -// ============================================================================ -// TypeScript Definition Generation Task -// Generates .d.ts files from Java API sources for scripting IDE support -// ============================================================================ -// TypeScript plugin is applied above in the main plugins block - -tasks.named("generateTypeScriptDefinitions").configure { - // Source directories containing the Java API code - sourceDirectories = ['src/main/java'] - - // Packages in source directories to generate .d.ts files for - apiPackages = ['noppes.npcs.api'] as Set - - // Output directory for the generated .d.ts files - // Must be within resources/assets/${modId}/api to be detected by CNPC+ - outputDirectory = "src/main/resources/assets/${modId}/api" - - // Whether to clean old generated files before regenerating - cleanOutputFirst = true - - // Optional: copy external patch .d.ts files into assets//api/patches - patchesDirectory = "dts-patches" -} - - -// Optional: To ensure definitions are generated on processing resources on jar build -// But in most cases, you may want to run the task manually when needed -// processResources.dependsOn generateTypeScriptDefinitions -``` - ---- - -## Patches (optional overrides) - -Use `dts-patches/` to override or refine generated types. Files in this folder are copied to -`assets//api/patches` after generation. - -### Example: override `IPlayer.getDBCPlayer()` to return `IDBCAddon` instead of `IDBCPlayer` - -File: `dts-patches/IPlayer.d.ts` - -```ts -/** - * DBC Addon patch for IPlayer - * @javaFqn noppes.npcs.api.entity.IPlayer - */ -export interface IPlayer { - getDBCPlayer(): IDBCAddon; -} -``` - diff --git a/gradle-plugins/build.gradle b/gradle-plugins/build.gradle deleted file mode 100644 index 0deda7acc..000000000 --- a/gradle-plugins/build.gradle +++ /dev/null @@ -1,50 +0,0 @@ -plugins { - id 'groovy-gradle-plugin' - id 'maven-publish' -} - -group = 'dts' -version = '1.0.0' - -repositories { - mavenCentral() -} - -dependencies { - implementation gradleApi() - implementation localGroovy() -} - -// Configure source sets if building as standalone -sourceSets { - main { - groovy { - srcDirs = ['src/main/groovy'] - } - resources { - srcDirs = ['src/main/resources'] - } - } -} - -gradlePlugin { - plugins { - typescriptGenerator { - id = 'dts.typescript-generator' - implementationClass = 'dts.TypeScriptGeneratorPlugin' - displayName = 'TypeScript Definition Generator' - description = 'Generates TypeScript definition files from Java API sources' - } - } -} - -publishing { - repositories { - mavenLocal() - } -} - -// Handle duplicate resources -tasks.processResources { - duplicatesStrategy = 'include' -} diff --git a/gradle-plugins/settings.gradle b/gradle-plugins/settings.gradle deleted file mode 100644 index 14cad52d4..000000000 --- a/gradle-plugins/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'dts-gradle-plugin' diff --git a/gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy b/gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy deleted file mode 100644 index b62e6cedc..000000000 --- a/gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy +++ /dev/null @@ -1,175 +0,0 @@ -package dts - -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.TaskAction -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputDirectory -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.Optional - -/** - * Gradle task that generates TypeScript definition (.d.ts) files from Java API sources. - * - * Usage in build.gradle: - * - * tasks.withType(GenerateTypeScriptTask).configureEach { - * sourceDirectories = ['src/api/java'] // Strings are converted to Files - * outputDirectory = 'src/main/resources/${modid}/api' // String converted to File - * apiPackages = ['noppes.npcs.api', 'kamkeel.npcdbc.api'] - * } - */ -abstract class GenerateTypeScriptTask extends DefaultTask { - - // Accept Object types (String or File) with @Internal annotation - @Internal - List sourceDirectories = [] - - @Internal - Object outputDirectory - - @Input - Set apiPackages = [] - - @Input - Boolean cleanOutputFirst = false - - @Input - List excludePatterns = [] - - @Internal - Object patchesDirectory - - // Provide task input/output properties that Gradle can validate - @InputFiles - protected List getResolvedSourceDirectories() { - return sourceDirectories.collect { obj -> - if (obj instanceof File) return obj - String pathStr = obj.toString() - if (pathStr.contains('${modid}')) { - String modid = project.archivesBaseName ?: 'mod' - pathStr = pathStr.replace('${modid}', modid) - } - File f = new File(pathStr) - if (!f.isAbsolute()) { - f = new File(project.projectDir, pathStr) - } - return f - } - } - - @OutputDirectory - protected File getResolvedOutputDirectory() { - def obj = outputDirectory - if (obj instanceof File) return obj - String pathStr = obj.toString() - if (pathStr.contains('${modid}')) { - String modid = project.archivesBaseName ?: 'mod' - pathStr = pathStr.replace('${modid}', modid) - } - File f = new File(pathStr) - if (!f.isAbsolute()) { - f = new File(project.projectDir, pathStr) - } - return f - } - - @Optional - @InputDirectory - protected File getResolvedDtsPatchesDirectory() { - if (patchesDirectory == null) return null - def obj = patchesDirectory - if (obj instanceof File) return obj - String pathStr = obj.toString() - if (pathStr.contains('${modid}')) { - String modid = project.archivesBaseName ?: 'mod' - pathStr = pathStr.replace('${modid}', modid) - } - File f = new File(pathStr) - if (!f.isAbsolute()) { - f = new File(project.projectDir, pathStr) - } - return f - } - - /** - * Converts a value (String or File) to a File object. - * Supports special tokens like ${modid}. - */ - // conversion logic inlined into getters to avoid calling private helper at configuration time - - GenerateTypeScriptTask() { - group = 'api' - description = 'Generates TypeScript definition files from Java API sources' - } - - @TaskAction - void generate() { - List srcDirs = getResolvedSourceDirectories() - File outDir = getResolvedOutputDirectory() - File patchesDir = getResolvedDtsPatchesDirectory() - - logger.lifecycle("=".multiply(60)) - logger.lifecycle("Generating TypeScript definitions...") - logger.lifecycle("=".multiply(60)) - - if (srcDirs.isEmpty()) { - logger.warn("No source directories specified!") - return - } - - // Validate directories - srcDirs.each { dir -> - if (!dir.exists()) { - logger.warn("Source directory does not exist: ${dir}") - } else { - logger.lifecycle("Source: ${dir}") - } - } - - logger.lifecycle("Output: ${outDir}") - logger.lifecycle("API Packages: ${apiPackages}") - - // Clean output if requested - if (cleanOutputFirst && outDir.exists()) { - logger.lifecycle("Cleaning output directory...") - outDir.eachFileRecurse { file -> - if (file.name.endsWith('.d.ts') && !file.name.equals('minecraft-raw.d.ts') && !file.name.equals('forge-events-raw.d.ts')) { - file.delete() - } - } - } - - // Create converter and process - JavaToTypeScriptConverter converter = new JavaToTypeScriptConverter(outDir, apiPackages) - - List validDirs = srcDirs.findAll { it.exists() } - if (validDirs.isEmpty()) { - logger.error("No valid source directories found!") - return - } - - converter.processDirectories(validDirs, logger) - - if (patchesDir != null) { - if (!patchesDir.exists()) { - logger.lifecycle("Patches directory does not exist: ${patchesDir}") - } else { - File patchOutputDir = new File(outDir, "patches") - if (patchOutputDir.exists()) { - patchOutputDir.deleteDir() - } - project.copy { - from patchesDir - into patchOutputDir - } - logger.lifecycle("Copied .d.ts patches to: ${patchOutputDir}") - } - } - - logger.lifecycle("=".multiply(60)) - logger.lifecycle("TypeScript definition generation complete!") - logger.lifecycle("=".multiply(60)) - } -} diff --git a/gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy b/gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy deleted file mode 100644 index 9d96633ed..000000000 --- a/gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy +++ /dev/null @@ -1,1353 +0,0 @@ -package dts - -import groovy.transform.TypeChecked -import org.gradle.api.logging.Logger - -import java.util.regex.Pattern -import java.util.regex.Matcher - -/** - * Parses Java source files and converts them to TypeScript definition (.d.ts) files. - * Handles interfaces, classes, nested types, generics, and JavaDoc preservation. - */ -class JavaToTypeScriptConverter { - - // Common Java type mappings to TypeScript - private static final Map PRIMITIVE_MAPPINGS = [ - 'void': 'void', - 'boolean': 'boolean', - 'byte': 'number', - 'short': 'number', - 'int': 'number', - 'long': 'number', - 'float': 'number', - 'double': 'number', - 'char': 'string', - 'String': 'string', - 'Object': 'any', - 'Boolean': 'boolean', - 'Byte': 'number', - 'Short': 'number', - 'Integer': 'number', - 'Long': 'number', - 'Float': 'number', - 'Double': 'number', - 'Character': 'string', - 'Number': 'number', - ] - - // Java functional interface mappings - private static final Map FUNCTIONAL_MAPPINGS = [ - 'Consumer': '(arg: %s) => void', - 'Supplier': '() => %s', - 'Function': '(arg: %s) => %s', - 'Predicate': '(arg: %s) => boolean', - 'BiConsumer': '(arg1: %s, arg2: %s) => void', - 'BiFunction': '(arg1: %s, arg2: %s) => %s', - 'Runnable': '() => void', - 'Callable': '() => %s', - ] - - // Packages that are part of API (generate imports to local .d.ts) - private Set apiPackages = [] as Set - - // Base output directory for generated files - private File outputDir - - // Track all generated types for index.d.ts - private List generatedTypes = [] - - // Track hooks for hooks.d.ts - // Hooks are organized by their parent event type (e.g., INpcEvent, IPlayerEvent) - // The namespace in hooks.d.ts matches the event type name directly - private Map> hooks = [:] - - private Logger logger; - - JavaToTypeScriptConverter(File outputDir, Set apiPackages) { - this.outputDir = outputDir - this.apiPackages = apiPackages - } - - /** - * Process all Java files in the given directories - */ - void processDirectories(List sourceDirs, Logger logger) { - this.logger = logger - sourceDirs.each { dir -> - if (dir.exists()) { - processDirectory(dir, dir) - } - } - - // Generate index.d.ts - generateIndexFile() - - // Generate hooks.d.ts - generateHooksFile() - } - - private void processDirectory(File dir, File baseDir) { - dir.eachFileRecurse { file -> - if (file.name.endsWith('.java') && !file.name.equals('package-info.java')) { - // Early filtering - check if file matches any API package - String relativePath = baseDir.toPath().relativize(file.toPath()).toString() - String packagePath = relativePath.replace('\\', '/').replace('.java', '').replace('/', '.') - - // Only process if the package starts with one of the apiPackages - boolean shouldProcess = apiPackages.any { apiPkg -> packagePath.startsWith(apiPkg) } - - if (shouldProcess) - processJavaFile(file, baseDir) - } - } - } - - - - /** - * Process a single Java file - */ - void processJavaFile(File javaFile, File baseDir) { - String content = javaFile.text - ParsedJavaFile parsed = parseJavaFile(content) - - if (parsed == null) { - logger.warn("Failed to parse ${javaFile.name} - parseJavaFile returned null") - return - } - if (parsed.types.isEmpty()) { - logger.warn("No types extracted from ${javaFile.name} - package: ${parsed.packageName}") - return - } - // logger.lifecycle("Successfully parsed ${javaFile.name}: ${parsed.types.size()} type(s) found: ${parsed.types*.name}") - - // Determine output path - String relativePath = baseDir.toPath().relativize(javaFile.toPath()).toString() - String dtsPath = relativePath.replace('.java', '.d.ts').replace('\\', '/') - File outputFile = new File(outputDir, dtsPath) - - // Generate TypeScript content - String tsContent = generateTypeScript(parsed, dtsPath) - - // Write file - outputFile.parentFile.mkdirs() - outputFile.text = tsContent - - // Track for index generation - parsed.types.each { type -> - generatedTypes << new TypeInfo( - name: type.name, - packageName: parsed.packageName, - filePath: dtsPath, - isClass: type.isClass, - isInterface: type.isInterface, - extendsType: type.extendsType - ) - - // Track nested types - type.nestedTypes.each { nested -> - generatedTypes << new TypeInfo( - name: "${type.name}.${nested.name}", - packageName: parsed.packageName, - filePath: dtsPath, - isClass: nested.isClass, - isInterface: nested.isInterface, - parentType: type.name - ) - } - } - - // Collect hooks from event interfaces - collectHooks(parsed) - } - - /** - * Parse a Java file into structured data - */ - ParsedJavaFile parseJavaFile(String content) { - ParsedJavaFile result = new ParsedJavaFile() - - // Extract package - def packageMatcher = content =~ /package\s+([\w.]+)\s*;/ - if (packageMatcher.find()) { - result.packageName = packageMatcher.group(1) - } - - // Extract imports - def importMatcher = content =~ /import\s+([\w.*]+)\s*;/ - while (importMatcher.find()) { - result.imports << importMatcher.group(1) - } - - // Parse types (interfaces and classes) - parseTypes(content, result) - - return result - } - - private void parseTypes(String content, ParsedJavaFile result) { - // Match ONLY top-level (public) interface or class declarations - // Top-level types MUST have 'public' modifier in Java - // Use a simpler pattern first, then manually extract type parameters - // Handle modifiers like abstract, final, static (in any order) - def typePattern = ~/(\/\*\*[\s\S]*?\*\/\s*)?public\s+(?:(?:abstract|final|static)\s+)*(interface|class)\s+(\w+)/ - - def matcher = content =~ typePattern - while (matcher.find()) { - JavaType type = new JavaType() - type.jsdoc = matcher.group(1)?.trim() - type.isInterface = matcher.group(2) == 'interface' - type.isClass = matcher.group(2) == 'class' - type.name = matcher.group(3) - - // Manually extract type parameters with balanced bracket matching - int afterName = matcher.end() - String remainder = content.substring(afterName) - - // Check if there are type parameters - if (remainder.trim().startsWith('<')) { - int startIndex = remainder.indexOf('<') - int depth = 0 - int endIndex = -1 - - for (int i = startIndex; i < remainder.length(); i++) { - char c = remainder.charAt(i) - if (c == '<') { - depth++ - } else if (c == '>') { - depth-- - if (depth == 0) { - endIndex = i - break - } - } - } - - if (endIndex > startIndex) { - type.typeParams = remainder.substring(startIndex + 1, endIndex).trim() - // Parse type parameters with full class names - type.parsedTypeParams = parseTypeParams(type.typeParams, result) - remainder = remainder.substring(endIndex + 1) - } - } - - // Now parse extends and implements - def extendsPattern = ~/\s+extends\s+([\w.<>,\s]+?)(?:\s+implements|\s*\{)/ - def extendsMatcher = remainder =~ extendsPattern - if (extendsMatcher.find()) { - type.extendsType = extendsMatcher.group(1)?.trim() - } - - def implementsPattern = ~/\s+implements\s+([\w.<>,\s]+?)\s*\{/ - def implementsMatcher = remainder =~ implementsPattern - if (implementsMatcher.find()) { - type.implementsTypes = implementsMatcher.group(1)?.split(',')?.collect { it.trim() } ?: [] - } else { - type.implementsTypes = [] - } - - // Find the opening brace for the body - int braceIndex = content.indexOf('{', afterName) - if (braceIndex == -1) { - continue // No body found, skip this type - } - - // Find the body of this type - int bodyStart = braceIndex - int bodyEnd = findMatchingBrace(content, bodyStart) - if (bodyEnd > bodyStart) { - String body = content.substring(bodyStart + 1, bodyEnd) - - // Parse methods - pass original body for JSDoc extraction - type.methods = parseMethods(body) - - // Parse nested types - type.nestedTypes = parseNestedTypes(body, type.name) - - // Parse fields (for classes) - if (type.isClass) { - type.fields = parseFields(body) - } - } - - result.types << type - } - } - - /** - * Remove nested type bodies from a string so we only parse top-level methods - */ - private String removeNestedTypeBodies(String body) { - StringBuilder result = new StringBuilder() - int depth = 0 - boolean inNestedType = false - int nestedStart = -1 - - // Find nested type declarations and remove their bodies - def nestedPattern = ~/(?:public\s+)?(?:static\s+)?(interface|class)\s+\w+/ - - int i = 0 - while (i < body.length()) { - char c = body.charAt(i) - - if (c == '{') { - if (!inNestedType) { - // Check if this brace starts a nested type - String before = body.substring(Math.max(0, i - 100), i) - if (before =~ /(?:public\s+)?(?:static\s+)?(?:interface|class)\s+\w+[^{]*$/) { - inNestedType = true - nestedStart = i - depth = 1 - i++ - continue - } - } - if (inNestedType) { - depth++ - } - } else if (c == '}') { - if (inNestedType) { - depth-- - if (depth == 0) { - inNestedType = false - // Don't add the nested type body to result - i++ - continue - } - } - } - - if (!inNestedType) { - result.append(c) - } - i++ - } - - return result.toString() - } - - private List parseMethods(String body) { - List methods = [] - - // Remove nested type bodies first to only get top-level methods - String topLevelBody = removeNestedTypeBodies(body) - - // Match method signatures - handles complex generics - // Anchored with (?m)^ to prevent matching inside // comment lines - // Capture JSDoc in group 1, returnType in group 2, methodName in group 3, params in group 4 - def methodPattern = ~/(?m)^\s*(\/\*\*[\s\S]*?\*\/\s*)?(?:@\w+(?:\([^)]*\))?\s*)*(?:public\s+|protected\s+|private\s+)?(?:static\s+)?(?:abstract\s+)?(?:default\s+)?(?:synchronized\s+)?(?:final\s+)?(?:<[^>]+>\s+)?(\w[\w.<>,\[\]\s]*?)\s+(\w+)\s*\(([^)]*)\)\s*(?:throws\s+[\w,\s]+)?[;{]/ - - def matcher = topLevelBody =~ methodPattern - while (matcher.find()) { - String jsdoc = matcher.group(1)?.trim() - String returnType = matcher.group(2).trim() - String methodName = matcher.group(3) - - // Skip constructors - where return type is a visibility modifier - // or the method name matches the class name (which we'd need to track) - if (['public', 'protected', 'private', 'abstract', 'static', 'final', 'synchronized', 'native', 'strictfp'].contains(returnType)) { - continue - } - - JavaMethod method = new JavaMethod() - method.returnType = returnType - method.name = methodName - method.parameters = parseParameters(matcher.group(4)) - method.jsdoc = jsdoc - - methods << method - } - - return methods - } - - private List parseFields(String body) { - List fields = [] - - // Remove nested type bodies first - String topLevelBody = removeNestedTypeBodies(body) - - // Capture JSDoc in group 1, visibility in group 2, fieldType in group 3, fieldName in group 4 - def fieldPattern = ~/(\/\*\*[\s\S]*?\*\/\s*)?(public\s+|protected\s+|private\s+)(?:static\s+)?(?:final\s+)?(\w[\w.<>,\[\]]*)\s+(\w+)\s*[;=]/ - - def matcher = topLevelBody =~ fieldPattern - while (matcher.find()) { - String jsdoc = matcher.group(1)?.trim() - String fieldType = matcher.group(3).trim() - String fieldName = matcher.group(4) - - // Skip Java keywords that might be mismatched - if (['return', 'if', 'else', 'for', 'while', 'switch', 'case', 'break', 'continue', 'throw', 'try', 'catch', 'finally', 'new', 'this', 'super'].contains(fieldType)) { - continue - } - - JavaField field = new JavaField() - field.type = fieldType - field.name = fieldName - field.jsdoc = jsdoc - - fields << field - } - - return fields - } - - private List parseNestedTypes(String body, String parentName) { - List nestedTypes = [] - - // Capture JSDoc in group 1, interface/class in group 2, name in group 3, typeParams in group 4, extends in group 5 - def nestedPattern = ~/(\/\*\*[\s\S]*?\*\/\s*)?(?:@\w+(?:\([^)]*\))?\s*)*(?:public\s+)?(?:static\s+)?(interface|class)\s+(\w+)(?:<([^>]+)>)?(?:\s+extends\s+([\w.<>,\s]+))?\s*\{/ - - // We need to track position and skip over bodies of found types to avoid finding nested-nested types - int searchStart = 0 - def matcher = nestedPattern.matcher(body) - - while (matcher.find(searchStart)) { - JavaType nested = new JavaType() - nested.jsdoc = matcher.group(1)?.trim() - nested.isInterface = matcher.group(2) == 'interface' - nested.isClass = matcher.group(2) == 'class' - nested.name = matcher.group(3) - nested.typeParams = matcher.group(4) - nested.extendsType = matcher.group(5)?.trim() - - int bodyStart = matcher.end() - 1 - int bodyEnd = findMatchingBrace(body, bodyStart) - if (bodyEnd > bodyStart) { - String nestedBody = body.substring(bodyStart + 1, bodyEnd) - nested.methods = parseMethods(nestedBody) - // Recursively parse nested types within this nested type - nested.nestedTypes = parseNestedTypes(nestedBody, nested.name) - - // Skip past the entire body of this type for the next search - searchStart = bodyEnd + 1 - } else { - // If we couldn't find the matching brace, move past this match - searchStart = matcher.end() - } - - nestedTypes << nested - } - - return nestedTypes - } - - private List parseParameters(String paramsStr) { - List params = [] - if (paramsStr == null || paramsStr.trim().isEmpty()) return params - - // Handle complex generic parameters - List paramParts = splitParameters(paramsStr) - - paramParts.each { part -> - part = part.trim() - if (part.isEmpty()) return - - // Handle varargs - boolean isVarargs = part.contains('...') - part = part.replace('...', '[]') - - // Split type and name - int lastSpace = part.lastIndexOf(' ') - if (lastSpace > 0 && lastSpace < part.length() - 1) { - JavaParameter param = new JavaParameter() - param.type = part.substring(0, lastSpace).trim() - param.name = part.substring(lastSpace + 1).trim() - param.isVarargs = isVarargs - params << param - } else if (lastSpace == -1 && !part.isEmpty()) { - // No space found - might be a single token, skip it - // This can happen with malformed or unusual parameter declarations - } - } - - return params - } - - /** - * Split parameters handling nested generics - */ - private List splitParameters(String params) { - List result = [] - int depth = 0 - StringBuilder current = new StringBuilder() - - params.each { ch -> - if (ch == '<') depth++ - else if (ch == '>') depth-- - else if (ch == ',' && depth == 0) { - result << current.toString() - current = new StringBuilder() - return - } - current.append(ch) - } - - if (current.length() > 0) { - result << current.toString() - } - - return result - } - - private String extractJsDocBefore(String content, int position) { - // Look backwards for JSDoc - String before = content.substring(0, position) - def jsdocMatcher = before =~ /\/\*\*[\s\S]*?\*\/\s*$/ - if (jsdocMatcher.find()) { - return jsdocMatcher.group(0).trim() - } - return null - } - - private int findMatchingBrace(String content, int start) { - int depth = 0 - for (int i = start; i < content.length(); i++) { - char c = content.charAt(i) - if (c == '{') depth++ - else if (c == '}') { - depth-- - if (depth == 0) return i - } - } - return -1 - } - - private String removeBlockComments(String content) { - // Remove JSDoc and block comments for structure parsing - return content.replaceAll(/\/\*[\s\S]*?\*\//, '') - } - - /** - * Generate TypeScript content from parsed Java - */ - String generateTypeScript(ParsedJavaFile parsed, String currentPath) { - StringBuilder sb = new StringBuilder() - - // Header comment - sb.append('/**\n') - sb.append(' * Generated from Java file for CustomNPC+ Minecraft Mod 1.7.10\n') - sb.append(" * Package: ${parsed.packageName}\n") - sb.append(' */\n\n') - - parsed.types.each { type -> - generateType(sb, type, parsed, currentPath, '') - } - - return sb.toString() - } - - private void generateType(StringBuilder sb, JavaType type, ParsedJavaFile parsed, String currentPath, String indent) { - // Build a set of type parameter names for this type (e.g., "T", "U", etc.) - Set typeParamNames = type.parsedTypeParams?.collect { it.name }?.toSet() ?: [] as Set - - // JSDoc - String javaFqn = buildJavaFqn(parsed.packageName, type.name) - String typeJsDoc = ensureJavaFqnTag(type.jsdoc, javaFqn, indent) - if (typeJsDoc) { - sb.append(typeJsDoc) - sb.append('\n') - } - - // Type declaration - String keyword = type.isClass ? 'export class' : 'export interface' - sb.append("${indent}${keyword} ${type.name}") - - // Type parameters with full class name bounds in JSDoc comment - if (type.typeParams) { - sb.append("<${convertTypeParams(type.typeParams, type.parsedTypeParams)}>") - } - - // Extends - skip if extending itself - if (type.extendsType && type.extendsType != type.name) { - sb.append(" extends ${convertType(type.extendsType, parsed, currentPath, typeParamNames)}") - } - - sb.append(' {\n') - - // Methods - compact format, no comments - type.methods.each { method -> - generateMethod(sb, method, parsed, currentPath, indent + ' ', typeParamNames) - } - - // Fields (for classes) - type.fields.each { field -> - generateField(sb, field, parsed, currentPath, indent + ' ', typeParamNames) - } - - sb.append("${indent}}\n") - - // Nested types as namespace - if (!type.nestedTypes.isEmpty()) { - sb.append("\n${indent}export namespace ${type.name} {\n") - type.nestedTypes.each { nested -> - // Always generate as interface, even if empty - // Empty interfaces with extends are important for type hierarchy - generateNestedType(sb, nested, type.name, type.name, parsed, currentPath, indent + ' ') - } - sb.append("${indent}}\n") - } - sb.append('\n') - } - - /** - * Generate a nested type (interface/class within a namespace) - * Recursively handles nested types that themselves have nested types - */ - private void generateNestedType(StringBuilder sb, JavaType type, String parentTypeName, String parentTypeChain, ParsedJavaFile parsed, String currentPath, String indent) { - // Build a set of type parameter names for this nested type - Set typeParamNames = type.parsedTypeParams?.collect { it.name }?.toSet() ?: [] as Set - - // JSDoc - String nestedChain = parentTypeChain ? "${parentTypeChain}.${type.name}" : type.name - String javaFqn = buildJavaFqn(parsed.packageName, nestedChain) - String nestedJsDoc = ensureJavaFqnTag(type.jsdoc, javaFqn, indent) - if (nestedJsDoc) { - sb.append(nestedJsDoc) - sb.append('\n') - } - - // Type declaration - String keyword = type.isClass ? 'export class' : 'export interface' - sb.append("${indent}${keyword} ${type.name}") - - // Type parameters with full class name bounds - if (type.typeParams) { - sb.append("<${convertTypeParams(type.typeParams, type.parsedTypeParams)}>") - } - - // Extends - handle parent type reference specially, skip if extending itself - if (type.extendsType && type.extendsType != type.name) { - String extendsRef = convertTypeForNested(type.extendsType, parentTypeName, parsed, currentPath, typeParamNames) - sb.append(" extends ${extendsRef}") - } - - sb.append(' {\n') - - // Methods - compact format, no comments - type.methods.each { method -> - generateMethod(sb, method, parsed, currentPath, indent + ' ', typeParamNames) - } - - sb.append("${indent}}\n") - - // If this nested type also has nested types, create a namespace for them - if (!type.nestedTypes.isEmpty()) { - sb.append("${indent}export namespace ${type.name} {\n") - type.nestedTypes.each { nested -> - // Always generate as interface, even if empty - // Empty interfaces with extends are important for type hierarchy - generateNestedType(sb, nested, type.name, nestedChain, parsed, currentPath, indent + ' ') - } - sb.append("${indent}}\n") - } - } - - /** - * Convert type reference for nested types - handle parent type specially - */ - private String convertTypeForNested(String javaType, String parentTypeName, ParsedJavaFile parsed, String currentPath, Set typeParamNames) { - if (javaType == null || javaType.isEmpty()) return 'any' - - javaType = javaType.trim() - - // If the type is the parent type name, use it directly (not as import from same file) - if (javaType == parentTypeName) { - return parentTypeName - } - - // Otherwise use normal conversion - return convertType(javaType, parsed, currentPath, typeParamNames) - } - - private void generateMethod(StringBuilder sb, JavaMethod method, ParsedJavaFile parsed, String currentPath, String indent, Set typeParamNames) { - // JSDoc - if (method.jsdoc) { - sb.append(convertJsDoc(method.jsdoc, indent)) - sb.append('\n') - } - - sb.append("${indent}${method.name}(") - - // Parameters - List paramStrs = method.parameters.collect { param -> - String tsType = convertType(param.type, parsed, currentPath, typeParamNames) - if (param.isVarargs) { - return "...${param.name}: ${tsType}" - } - return "${param.name}: ${tsType}" - } - sb.append(paramStrs.join(', ')) - - sb.append('): ') - sb.append(convertType(method.returnType, parsed, currentPath, typeParamNames)) - sb.append(';\n') - } - - private void generateField(StringBuilder sb, JavaField field, ParsedJavaFile parsed, String currentPath, String indent, Set typeParamNames) { - if (field.jsdoc) { - sb.append(convertJsDoc(field.jsdoc, indent)) - sb.append('\n') - } - sb.append("${indent}${field.name}: ${convertType(field.type, parsed, currentPath, typeParamNames)};\n") - } - - /** - * Convert Java type to TypeScript type - * @param typeParamNames Set of type parameter names from the enclosing type (e.g., "T", "U") - */ - String convertType(String javaType, ParsedJavaFile parsed, String currentPath, Set typeParamNames = [] as Set) { - if (javaType == null || javaType.isEmpty()) return 'any' - - javaType = javaType.trim() - - // Check if it's a type parameter (like T, U, etc.) - if (typeParamNames.contains(javaType)) { - return javaType - } - - // Check primitives first - if (PRIMITIVE_MAPPINGS.containsKey(javaType)) { - return PRIMITIVE_MAPPINGS[javaType] - } - - // Handle arrays - if (javaType.endsWith('[]') && javaType.length() > 2) { - String baseType = javaType.substring(0, javaType.length() - 2) - return convertType(baseType, parsed, currentPath, typeParamNames) + '[]' - } - - // Handle generics - if (javaType.contains('<')) { - return convertGenericType(javaType, parsed, currentPath, typeParamNames) - } - - // Check if it is an API type (needs import) - String importPath = resolveImportPath(javaType, parsed, currentPath) - if (importPath != null) { - return "import('${importPath}').${javaType}" - } - - // Check if it is a java.* type - String fullType = resolveFullType(javaType, parsed) - if (fullType != null && fullType.startsWith('java.')) { - return "Java.${fullType}" - } - - // Default - return as is (might be a type parameter like T, or unknown type) - return javaType - } - - private String convertGenericType(String type, ParsedJavaFile parsed, String currentPath, Set typeParamNames = [] as Set) { - int ltIndex = type.indexOf('<') - int gtIndex = type.lastIndexOf('>') - if (ltIndex == -1 || gtIndex == -1 || ltIndex >= gtIndex) { - // Malformed generic, return as-is - return type - } - String baseType = type.substring(0, ltIndex).trim() - String genericPart = type.substring(ltIndex + 1, gtIndex).trim() - - // Handle common collections - switch (baseType) { - case 'List': - case 'ArrayList': - case 'LinkedList': - case 'Collection': - case 'Set': - case 'HashSet': - case 'Queue': - return convertType(genericPart, parsed, currentPath, typeParamNames) + '[]' - - case 'Map': - case 'HashMap': - case 'LinkedHashMap': - List parts = splitGenericParams(genericPart) - if (parts.size() >= 2) { - String keyType = convertType(parts[0], parsed, currentPath, typeParamNames) - String valueType = convertType(parts[1], parsed, currentPath, typeParamNames) - return "Record<${keyType}, ${valueType}>" - } - return 'Record' - - case 'Optional': - return convertType(genericPart, parsed, currentPath, typeParamNames) + ' | null' - - // Functional interfaces - case 'Consumer': - return "(arg: ${convertType(genericPart, parsed, currentPath, typeParamNames)}) => void" - - case 'Supplier': - return "() => ${convertType(genericPart, parsed, currentPath, typeParamNames)}" - - case 'Function': - List funcParts = splitGenericParams(genericPart) - if (funcParts.size() >= 2) { - return "(arg: ${convertType(funcParts[0], parsed, currentPath, typeParamNames)}) => ${convertType(funcParts[1], parsed, currentPath, typeParamNames)}" - } - return '(arg: any) => any' - - case 'Predicate': - return "(arg: ${convertType(genericPart, parsed, currentPath, typeParamNames)}) => boolean" - - case 'BiConsumer': - List biParts = splitGenericParams(genericPart) - if (biParts.size() >= 2) { - return "(arg1: ${convertType(biParts[0], parsed, currentPath, typeParamNames)}, arg2: ${convertType(biParts[1], parsed, currentPath, typeParamNames)}) => void" - } - return '(arg1: any, arg2: any) => void' - - case 'BiFunction': - List biFuncParts = splitGenericParams(genericPart) - if (biFuncParts.size() >= 3) { - return "(arg1: ${convertType(biFuncParts[0], parsed, currentPath, typeParamNames)}, arg2: ${convertType(biFuncParts[1], parsed, currentPath, typeParamNames)}) => ${convertType(biFuncParts[2], parsed, currentPath, typeParamNames)}" - } - return '(arg1: any, arg2: any) => any' - - default: - // Regular generic type - String convertedBase = convertType(baseType, parsed, currentPath, typeParamNames) - List convertedParams = splitGenericParams(genericPart).collect { - convertType(it, parsed, currentPath, typeParamNames) - } - // For import types, we cannot add generics easily, so simplify - if (convertedBase.startsWith('import(')) { - return convertedBase - } - return "${convertedBase}<${convertedParams.join(', ')}>" - } - } - - private List splitGenericParams(String params) { - List result = [] - int depth = 0 - StringBuilder current = new StringBuilder() - - params.each { ch -> - if (ch == '<') depth++ - else if (ch == '>') depth-- - else if (ch == ',' && depth == 0) { - result << current.toString().trim() - current = new StringBuilder() - return - } - current.append(ch) - } - - if (current.length() > 0) { - result << current.toString().trim() - } - - return result - } - - /** - * Convert Java type parameters to TypeScript - * Outputs format like: T extends EntityPlayerMP /`*` net.minecraft.entity.player.EntityPlayerMP `*`/ - * This allows runtime parsing to extract the full Java class name for the type bound. - */ - private String convertTypeParams(String typeParams, List parsedParams) { - if (typeParams == null || typeParams.isEmpty()) return typeParams - if (parsedParams == null || parsedParams.isEmpty()) return typeParams - - // Build result by iterating over parsed params - List convertedParams = [] - for (TypeParamInfo info in parsedParams) { - StringBuilder sb = new StringBuilder() - sb.append(info.name) - - if (info.boundType != null) { - sb.append(" extends ") - sb.append(info.boundType) - - // Add full class name as JSDoc-style comment if available - if (info.fullBoundType != null) { - sb.append(" /* ${info.fullBoundType} */") - } - } - - convertedParams << sb.toString() - } - - return convertedParams.join(', ') - } - - private String resolveImportPath(String typeName, ParsedJavaFile parsed, String currentPath) { - // Check imports for this type - String fullType = resolveFullType(typeName, parsed) - - if (fullType == null) return null - - // Check if it is an API type - int lastDotIndex = fullType.lastIndexOf('.') - if (lastDotIndex == -1) return null - String packagePrefix = fullType.substring(0, lastDotIndex) - if (apiPackages.any { fullType.startsWith(it) }) { - // Calculate relative path - String typeFilePath = fullType.replace('.', '/') + '.d.ts' - return calculateRelativePath(currentPath, typeFilePath) - } - - return null - } - - private String resolveFullType(String typeName, ParsedJavaFile parsed) { - // Check explicit imports - String explicitImport = parsed.imports.find { it.endsWith(".${typeName}") } - if (explicitImport) return explicitImport - - // Check wildcard imports - parsed.imports.each { imp -> - if (imp.endsWith('.*')) { - // Would need classpath to resolve, skip for now - } - } - - // Same package - return "${parsed.packageName}.${typeName}" - } - - /** - * Parse type parameters like "T extends EntityPlayerMP" into structured TypeParamInfo - * with full class names resolved from imports - */ - private List parseTypeParams(String typeParams, ParsedJavaFile parsed) { - List result = [] - if (typeParams == null || typeParams.isEmpty()) return result - - // Split by comma, but respect nested angle brackets - List params = splitGenericParams(typeParams) - - for (String param in params) { - param = param.trim() - TypeParamInfo info = new TypeParamInfo() - - // Check for "T extends BoundType" pattern - def extendsMatcher = param =~ /(\w+)\s+extends\s+(.+)/ - if (extendsMatcher.find()) { - info.name = extendsMatcher.group(1).trim() - String boundType = extendsMatcher.group(2).trim() - - // Handle generic bounds like "Comparable" - extract base type - int angleIndex = boundType.indexOf('<') - String baseBoundType = angleIndex > 0 ? boundType.substring(0, angleIndex) : boundType - - info.boundType = baseBoundType - info.fullBoundType = resolveFullType(baseBoundType, parsed) - } else { - // Just a type param like "T" with no explicit bound - info.name = param - info.boundType = null - info.fullBoundType = null - } - - result << info - } - - return result - } - - private String calculateRelativePath(String fromPath, String toPath) { - // Calculate relative path between two .d.ts files - String[] fromParts = fromPath.split('/') - String[] toParts = toPath.split('/') - - // Find common prefix - int common = 0 - while (common < fromParts.length - 1 && common < toParts.length && fromParts[common] == toParts[common]) { - common++ - } - - // Build relative path - StringBuilder result = new StringBuilder() - - // Go up from current location - int ups = fromParts.length - common - 1 - if (ups == 0) { - result.append('./') - } else { - for (int i = 0; i < ups; i++) { - result.append('../') - } - } - - // Go down to target - for (int i = common; i < toParts.length; i++) { - if (i > common) result.append('/') - result.append(toParts[i]) - } - - // Remove .d.ts extension for imports - String path = result.toString() - if (path.endsWith('.d.ts')) { - path = path.substring(0, path.length() - 5) - } - - return path - } - - /** - * Convert JavaDoc to JSDoc format - */ - private String convertJsDoc(String jsdoc, String indent) { - if (jsdoc == null) return '' - - // Already in JSDoc format, just fix indentation - String[] lines = jsdoc.split('\n') - return lines.collect { line -> - String trimmed = line.trim() - if (trimmed.startsWith('*')) { - return "${indent} ${trimmed}" - } else if (trimmed.startsWith('/**') || trimmed.startsWith('*/')) { - return "${indent}${trimmed}" - } else { - return "${indent}${trimmed}" - } - }.join('\n') - } - - private String ensureJavaFqnTag(String jsdoc, String javaFqn, String indent) { - if (javaFqn == null || javaFqn.isEmpty()) { - return convertJsDoc(jsdoc, indent) - } - - if (jsdoc != null && jsdoc.contains('@javaFqn')) { - return convertJsDoc(jsdoc, indent) - } - - if (jsdoc == null || jsdoc.trim().isEmpty()) { - return "${indent}/**\n${indent} * @javaFqn ${javaFqn}\n${indent} */" - } - - String converted = convertJsDoc(jsdoc, indent) - int endIndex = converted.lastIndexOf('*/') - if (endIndex >= 0) { - String insert = "${indent} * @javaFqn ${javaFqn}\n" - return converted.substring(0, endIndex) + insert + converted.substring(endIndex) - } - - return converted + "\n${indent} * @javaFqn ${javaFqn}" - } - - private String buildJavaFqn(String packageName, String typeName) { - if (typeName == null || typeName.isEmpty()) return null - if (packageName == null || packageName.isEmpty()) return typeName - return packageName + '.' + typeName - } - - /** - * Extract @hookName value from a JSDoc comment. - * - * @param jsdoc The JSDoc comment string (may be null) - * @return The hook name if @hookName tag is present, null otherwise - */ - private String extractHookNameFromJsDoc(String jsdoc) { - if (jsdoc == null || jsdoc.isEmpty()) return null - - // Match @hookName followed by the hook name value - // Examples: @hookName animationStart, @hookName customGuiButton - def matcher = jsdoc =~ /@hookName\s+(\w+)/ - if (matcher.find()) { - return matcher.group(1) - } - return null - } - - /** - * Collect hook information from event interfaces. - * - * Looks for interfaces that: - * 1. End with 'Event' (e.g., IPlayerEvent, IDBCEvent) - * 2. Are in an 'event' package - * 3. Have nested types that are also events - * - * Hook names are determined by: - * 1. @hookName JSDoc tag if present (e.g., @hookName animationStart) - * 2. Otherwise derived from the event class name (e.g., InitEvent -> init) - * - * The parent event type name (e.g., "INpcEvent", "IPlayerEvent") is used directly - * as the namespace in hooks.d.ts. This allows any mod to register event interfaces - * and have them automatically organized by their type name. - */ - private void collectHooks(ParsedJavaFile parsed) { - boolean isEventPackage = parsed.packageName.contains('.event') - - parsed.types.each { type -> - // Check if this is an event interface: - // - Must be an interface - // - Either ends with 'Event' OR is in an event package - boolean isEventType = type.isInterface && ( - type.name.endsWith('Event') || type.name.endsWith('Events') || - isEventPackage - ) - - if (isEventType && !type.nestedTypes.isEmpty()) { - collectHooksFromNestedTypes(type.nestedTypes, type.name, parsed.packageName, isEventPackage) - } - } - } - - /** - * Recursively collect hooks from nested types. - * This handles deeply nested event types like IAnimationEvent.IFrameEvent.Entered - */ - private void collectHooksFromNestedTypes(List nestedTypes, String parentTypeName, String packageName, boolean isEventPackage) { - nestedTypes.each { nested -> - // Check if this nested type should be processed as a hook - boolean isNestedEvent = nested.isInterface && ( - nested.name.endsWith('Event') || - nested.name.endsWith('Events') || - isEventPackage || - // Also include simple names like "Started", "Ended", "Entered", "Exited" - // if they're inside an event interface - parentTypeName.endsWith('Event') - ) - - if (isNestedEvent) { - // Check for @hookName in JSDoc first, otherwise derive from class name - String hookName = extractHookNameFromJsDoc(nested.jsdoc) - if (hookName == null) { - hookName = deriveHookName(nested.name) - } - - if (!hooks.containsKey(hookName)) { - hooks[hookName] = [] - } - - // Use the root event type name as the namespace - // Extract the root type (e.g., "IAnimationEvent" from "IAnimationEvent.IFrameEvent") - String rootType = parentTypeName.contains('.') ? - parentTypeName.substring(0, parentTypeName.indexOf('.')) : parentTypeName - - hooks[hookName] << new HookInfo( - eventType: rootType, - subEvent: nested.name, - fullType: "${parentTypeName}.${nested.name}", - packageName: packageName, - contextNamespace: rootType - ) - - // Recursively process any nested types within this nested type - if (!nested.nestedTypes.isEmpty()) { - collectHooksFromNestedTypes(nested.nestedTypes, "${parentTypeName}.${nested.name}", packageName, isEventPackage) - } - } - } - } - - private String deriveHookName(String eventName) { - // Convert event names to hook function names - // e.g., "InitEvent" -> "init", "DamagedEvent" -> "damaged" - String name = eventName - if (name.endsWith('Event') && name.length() > 5) { - name = name.substring(0, name.length() - 5) - } - // Convert to camelCase - if (name.isEmpty()) return 'event' - String hookName = name.length() > 1 ? (name.substring(0, 1).toLowerCase() + name.substring(1)) : name.toLowerCase() - - // Handle JavaScript reserved words - Set reservedWords = ['break', 'case', 'catch', 'continue', 'debugger', 'default', 'delete', - 'do', 'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof', - 'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var', - 'void', 'while', 'with', 'class', 'const', 'enum', 'export', 'extends', - 'import', 'super', 'implements', 'interface', 'let', 'package', 'private', - 'protected', 'public', 'static', 'yield'] as Set - - if (reservedWords.contains(hookName)) { - // Prefix with 'on' for reserved words - hookName = 'on' + name - } - - return hookName - } - - /** - * Generate index.d.ts with all type aliases - */ - private void generateIndexFile() { - StringBuilder sb = new StringBuilder() - - sb.append('/**\n') - sb.append(' * Centralized global declarations for CustomNPC+ scripting.\n') - sb.append(' * Auto-generated - do not edit manually.\n') - sb.append(' */\n\n') - - sb.append('declare global {\n') - sb.append(' // ============================================================================\n') - sb.append(' // TYPE ALIASES - Make all interfaces available globally\n') - sb.append(' // ============================================================================\n\n') - - generatedTypes.sort { a, b -> a.name <=> b.name } - - generatedTypes.each { type -> - if (!type.name.contains('.')) { // Skip nested types here - sb.append(" type ${type.name} = import('./${type.filePath.replace('.d.ts', '')}').${type.name};\n") - } - } - - // Collect all parent types that have nested types (for namespace declarations) - Map> parentToNested = [:] - generatedTypes.each { type -> - if (type.parentType) { - if (!parentToNested.containsKey(type.parentType)) { - parentToNested[type.parentType] = [] - } - parentToNested[type.parentType] << type - } - } - - // Generate namespace declarations for types with nested interfaces - if (!parentToNested.isEmpty()) { - sb.append('\n // ============================================================================\n') - sb.append(' // NESTED INTERFACES - Allow autocomplete like INpcEvent.InitEvent\n') - sb.append(' // ============================================================================\n\n') - - parentToNested.sort { a, b -> a.key <=> b.key }.each { parentName, nestedTypes -> - sb.append(" namespace ${parentName} {\n") - nestedTypes.sort { a, b -> a.name <=> b.name }.each { nested -> - // Extract just the nested type name (e.g., "InitEvent" from "IPlayerEvent.InitEvent") - String nestedName = nested.name.contains('.') ? - nested.name.substring(nested.name.lastIndexOf('.') + 1) : nested.name - sb.append(" interface ${nestedName} extends ${parentName} {}\n") - } - sb.append(" }\n\n") - } - } - - sb.append('}\n\n') - sb.append('export {};\n') - - new File(outputDir, 'index.d.ts').text = sb.toString() - } - - /** - * Generate hooks.d.ts with event hook function declarations. - * - * Hooks are organized by their parent event interface type, using the type name - * directly as the namespace. This provides context-aware autocomplete where - * the same hook name (e.g., "interact") can have different event types depending - * on the script context. - * - * Output format example: - * declare namespace INpcEvent { - * function interact(event: INpcEvent.InteractEvent): void; - * function init(event: INpcEvent.InitEvent): void; - * } - * - * declare namespace IPlayerEvent { - * function interact(event: IPlayerEvent.InteractEvent): void; - * function init(event: IPlayerEvent.InitEvent): void; - * } - * - * The namespace name matches the event interface type exactly, making it easy - * for the runtime parser to match hooks to their correct context. - */ - private void generateHooksFile() { - StringBuilder sb = new StringBuilder() - - sb.append('/**\n') - sb.append(' * CustomNPC+ Event Hook Declarations\n') - sb.append(' *\n') - sb.append(' * Hooks are organized by their parent event interface (e.g., INpcEvent, IPlayerEvent).\n') - sb.append(' * This allows the same hook name to have different event types per script context.\n') - sb.append(' *\n') - sb.append(' * Auto-generated from Java event interfaces - do not edit manually.\n') - sb.append(' */\n\n') - - sb.append("import './minecraft-raw.d.ts';\n") - sb.append("import './forge-events-raw.d.ts';\n\n") - - // Group hooks by their parent event type (contextNamespace = type.name) - Map>> hooksByEventType = [:].withDefault { [:].withDefault { [] } } - - hooks.each { hookName, hookInfos -> - hookInfos.each { info -> - hooksByEventType[info.contextNamespace][hookName] << info - } - } - - // Output each event type as a namespace - hooksByEventType.sort { a, b -> a.key <=> b.key }.each { eventTypeName, eventHooks -> - sb.append("declare namespace ${eventTypeName} {\n") - - // Output all hooks for this event type, sorted alphabetically - eventHooks.sort { a, b -> a.key <=> b.key }.each { hookName, hookInfos -> - hookInfos.each { info -> - sb.append(" function ${hookName}(event: ${info.fullType}): void;\n") - } - } - - sb.append('}\n\n') - } - - sb.append('export {};\n') - - new File(outputDir, 'hooks.d.ts').text = sb.toString() - } - - // Data classes - static class ParsedJavaFile { - String packageName = '' - List imports = [] - List types = [] - } - - static class JavaType { - String name - String typeParams // Raw string like "T extends EntityPlayerMP" - List parsedTypeParams = [] // Parsed type parameters with full class names - String extendsType - List implementsTypes = [] - boolean isInterface - boolean isClass - String jsdoc - List methods = [] - List fields = [] - List nestedTypes = [] - } - - static class JavaMethod { - String name - String returnType - List parameters = [] - String jsdoc - } - - static class JavaParameter { - String name - String type - boolean isVarargs - } - - static class JavaField { - String name - String type - String jsdoc - } - - static class TypeParamInfo { - String name // e.g., "T" - String boundType // e.g., "EntityPlayerMP" - String fullBoundType // e.g., "net.minecraft.entity.player.EntityPlayerMP" - } - - static class TypeInfo { - String name - String packageName - String filePath - boolean isClass - boolean isInterface - String extendsType - String parentType - } - - static class HookInfo { - String eventType // Parent event interface name (e.g., "INpcEvent") - String subEvent // Nested event type name (e.g., "InteractEvent") - String fullType // Full type path (e.g., "INpcEvent.InteractEvent") - String packageName // Java package (e.g., "noppes.npcs.api.event") - String contextNamespace // Namespace in hooks.d.ts (same as eventType, e.g., "INpcEvent") - } -} diff --git a/gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy b/gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy deleted file mode 100644 index 3165e3744..000000000 --- a/gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy +++ /dev/null @@ -1,17 +0,0 @@ -package dts - -import org.gradle.api.Plugin -import org.gradle.api.Project - -/** - * Gradle plugin for generating TypeScript definition files from Java API sources. - */ -class TypeScriptGeneratorPlugin implements Plugin { - - @Override - void apply(Project project) { - if (project.tasks.findByName('generateTypeScriptDefinitions') == null) { - project.tasks.register('generateTypeScriptDefinitions', GenerateTypeScriptTask) - } - } -} \ No newline at end of file diff --git a/gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties b/gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties deleted file mode 100644 index f27cbecea..000000000 --- a/gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties +++ /dev/null @@ -1 +0,0 @@ -implementation-class=dts.TypeScriptGeneratorPlugin From befebdb9f72fc9c1b9e31171b76d72c3a1a82f06 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 13 Feb 2026 16:28:45 -0500 Subject: [PATCH 45/76] refactor: enhance collision detection for ability movement --- .../data/ability/type/AbilityCharge.java | 27 +++++++++++++++++- .../data/ability/type/AbilityDash.java | 28 ++++++++++++++++++- .../data/ability/type/AbilitySlam.java | 11 ++++---- 3 files changed, 59 insertions(+), 7 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 a7430ce20..d9fd9b598 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 @@ -258,7 +258,32 @@ public class AbilityCharge extends Ability implements IAbilityCharge { double nextX = chargeDirection.xCoord * chargeSpeed; double nextZ = chargeDirection.zCoord * chargeSpeed; AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); - return !caster.worldObj.getCollidingBoundingBoxes(caster, nextBox).isEmpty(); + double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); + + int x1 = (int) Math.floor(nextBox.minX); + int x2 = (int) Math.floor(nextBox.maxX + 1.0); + int y1 = (int) Math.floor(nextBox.minY) - 1; + int y2 = (int) Math.floor(nextBox.maxY + 1.0); + int z1 = (int) Math.floor(nextBox.minZ); + int z2 = (int) Math.floor(nextBox.maxZ + 1.0); + + java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); + for (int bx = x1; bx < x2; bx++) { + for (int bz = z1; bz < z2; bz++) { + for (int by = y1; by < y2; by++) { + net.minecraft.block.Block block = caster.worldObj.getBlock(bx, by, bz); + if (!block.getMaterial().blocksMovement()) continue; + collisionBoxes.clear(); + block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); + for (AxisAlignedBB box : collisionBoxes) { + if (box.maxY > stepThreshold) { + return true; + } + } + } + } + } + return false; } @Override 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 0f8cbe374..b15f1f822 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 @@ -257,7 +257,33 @@ public class AbilityDash extends Ability implements IAbilityDash { if (dashDirection == null) return true; double nextX = dashDirection.xCoord * dashSpeed; double nextZ = dashDirection.zCoord * dashSpeed; - return !caster.worldObj.getCollidingBoundingBoxes(caster, caster.boundingBox.copy().offset(nextX, 0, nextZ)).isEmpty(); + AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); + double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); + + int x1 = (int) Math.floor(nextBox.minX); + int x2 = (int) Math.floor(nextBox.maxX + 1.0); + int y1 = (int) Math.floor(nextBox.minY) - 1; + int y2 = (int) Math.floor(nextBox.maxY + 1.0); + int z1 = (int) Math.floor(nextBox.minZ); + int z2 = (int) Math.floor(nextBox.maxZ + 1.0); + + java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); + for (int bx = x1; bx < x2; bx++) { + for (int bz = z1; bz < z2; bz++) { + for (int by = y1; by < y2; by++) { + net.minecraft.block.Block block = caster.worldObj.getBlock(bx, by, bz); + if (!block.getMaterial().blocksMovement()) continue; + collisionBoxes.clear(); + block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); + for (AxisAlignedBB box : collisionBoxes) { + if (box.maxY > stepThreshold) { + return true; + } + } + } + } + } + return false; } @Override 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 a03ecdf6a..f1281d7be 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 @@ -283,11 +283,12 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.fallDistance = 0; } - // Check for landing - if (caster.onGround && airTicks > 3) { - // Landed! - onLanding(caster, world); - return; + // Check for landing: hit the ground or hit a wall mid-flight + if (airTicks > 3) { + if (caster.onGround || caster.isCollidedHorizontally) { + onLanding(caster, world); + return; + } } // Timeout protection - force landing after max air time From 85db3df355fa4172497c5ac1c0739c44ab37c279 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 14 Feb 2026 03:50:28 -0500 Subject: [PATCH 46/76] feat: implement player ability state management with rotation and position locking --- .../data/ability/type/AbilitySlam.java | 54 +++-- .../kamkeel/npcs/network/PacketHandler.java | 2 + .../npcs/network/enums/EnumDataPacket.java | 1 + .../ability/PlayerAbilityStatePacket.java | 84 +++++++ .../noppes/npcs/ScriptPlayerEventHandler.java | 10 +- .../npcs/client/ClientAbilityState.java | 59 +++++ .../noppes/npcs/client/ClientTickHandler.java | 14 ++ .../controllers/data/PlayerAbilityData.java | 224 +++++++++++++++++- 8 files changed, 427 insertions(+), 21 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java create mode 100644 src/main/java/noppes/npcs/client/ClientAbilityState.java 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 f1281d7be..fc9a6b5be 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 @@ -86,10 +86,20 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { if (isPlayerCaster(caster)) { - // Player: slam will launch from current position, no target tracking needed - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; + // Player: update target along look direction during windup + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else { + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); + double launchDist = Math.max(4.0, maxRange * 0.5); + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + } } else { // NPC: update target position during windup for telegraph tracking if (targetingMode == TargetingMode.AOE_SELF) { @@ -139,18 +149,22 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } /** - * Player slam: Launch straight up. Player controls horizontal movement via WASD. + * Player slam: Launch in look direction using same ballistic arc as NPC slam. * AOE damage triggers wherever the player lands. */ private void executePlayerSlam(EntityLivingBase caster) { - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; + // Calculate target position along player's look direction (horizontal only) + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); - double vy = calculateLaunchVelocity(Math.max(1.0, leapHeight)); - caster.motionY = vy; - hasLaunched = true; - caster.velocityChanged = true; + double launchDist = Math.max(4.0, maxRange * 0.5); + + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + + launchTowardTarget(caster); } /** @@ -297,14 +311,18 @@ public class AbilitySlam extends Ability implements IAbilitySlam { return; } - // NPC: face toward target destination while in air - // Player: free look — player controls their own camera - if (!isPreview() && !isPlayerCaster(caster)) { + // Face toward target destination while in air (both NPC and Player) + if (!isPreview()) { double dx = targetX - caster.posX; double dz = targetZ - caster.posZ; - float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); - caster.rotationYaw = targetYaw; - caster.rotationYawHead = targetYaw; + if (dx * dx + dz * dz > 0.25) { + float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); + caster.rotationYaw = targetYaw; + caster.rotationYawHead = targetYaw; + if (isPlayerCaster(caster)) { + caster.velocityChanged = true; + } + } } } diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index 6db07c841..dee4a3a94 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.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; @@ -588,6 +589,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new TelegraphSpawnPacket()); DATA_PACKET.registerPacket(new TelegraphRemovePacket()); DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); + DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); } 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 18321d0a4..8362cb3c5 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -63,6 +63,7 @@ public enum EnumDataPacket { TELEGRAPH_SPAWN, TELEGRAPH_REMOVE, PLAYER_ABILITY_SYNC, + PLAYER_ABILITY_STATE, // Auction System AUCTION_DATA, diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java new file mode 100644 index 000000000..03c0b82b4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java @@ -0,0 +1,84 @@ +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 net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.client.ClientAbilityState; + +import java.io.IOException; + +/** + * Lightweight packet syncing ability lock state from server to client. + * Sent every tick during ability execution when flags change, and once when ability ends. + * + * Flags byte layout: + * bit 0: movement locked (suppress WASD, zero motion) + * bit 1: rotation locked (freeze yaw/pitch) + * bit 2: has ability movement (ability controls motion — suppress WASD but don't zero) + * bit 3: position locked (freeze position) + */ +public final class PlayerAbilityStatePacket extends AbstractPacket { + public static final String packetName = "Data|PlayerAbilityState"; + + public static final byte FLAG_MOVEMENT_LOCKED = 1; + public static final byte FLAG_ROTATION_LOCKED = 2; + public static final byte FLAG_HAS_ABILITY_MOVEMENT = 4; + public static final byte FLAG_POSITION_LOCKED = 8; + + private byte flags; + private float lockedYaw; + private float lockedPitch; + + public PlayerAbilityStatePacket() { + } + + public PlayerAbilityStatePacket(byte flags, float lockedYaw, float lockedPitch) { + this.flags = flags; + this.lockedYaw = lockedYaw; + this.lockedPitch = lockedPitch; + } + + @Override + public Enum getType() { + return EnumDataPacket.PLAYER_ABILITY_STATE; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeByte(flags); + if ((flags & FLAG_ROTATION_LOCKED) != 0) { + out.writeFloat(lockedYaw); + out.writeFloat(lockedPitch); + } + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + byte flags = in.readByte(); + float yaw = 0, pitch = 0; + if ((flags & FLAG_ROTATION_LOCKED) != 0) { + yaw = in.readFloat(); + pitch = in.readFloat(); + } + ClientAbilityState.update(flags, yaw, pitch); + } + + /** + * Send the current ability state to the player's client. + */ + public static void sendToPlayer(EntityPlayerMP player, byte flags, float lockedYaw, float lockedPitch) { + PacketHandler.Instance.sendToPlayer(new PlayerAbilityStatePacket(flags, lockedYaw, lockedPitch), player); + } +} diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index c77083fa1..909634a09 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -8,6 +8,7 @@ import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.addon.DBCAddon; import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.util.AttributeAttackUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -100,9 +101,14 @@ public class ScriptPlayerEventHandler { playerData.abilityData.tick(player); // Lock player movement during ability phases that require it + // Skip zeroing if the ability has its own movement (Charge/Dash/Slam) if (playerData.abilityData.isMovementLocked()) { - player.motionX = 0; - player.motionZ = 0; + Ability current = playerData.abilityData.getCurrentAbility(); + if (current == null || !current.hasAbilityMovement()) { + player.motionX = 0; + player.motionZ = 0; + player.velocityChanged = true; + } } if (playerData.updateClient) { diff --git a/src/main/java/noppes/npcs/client/ClientAbilityState.java b/src/main/java/noppes/npcs/client/ClientAbilityState.java new file mode 100644 index 000000000..8092a69a3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/ClientAbilityState.java @@ -0,0 +1,59 @@ +package noppes.npcs.client; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; + +/** + * Client-side state holder for player ability lock flags. + * Updated by {@link PlayerAbilityStatePacket} from the server. + * Read by {@link ClientTickHandler} to suppress WASD input and enforce rotation. + */ +@SideOnly(Side.CLIENT) +public class ClientAbilityState { + public static boolean movementLocked = false; + public static boolean rotationLocked = false; + public static boolean hasAbilityMovement = false; + public static boolean positionLocked = false; + public static float lockedYaw = 0; + public static float lockedPitch = 0; + + /** + * Update state from a received packet. + */ + public static void update(byte flags, float yaw, float pitch) { + movementLocked = (flags & PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED) != 0; + rotationLocked = (flags & PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED) != 0; + hasAbilityMovement = (flags & PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT) != 0; + positionLocked = (flags & PlayerAbilityStatePacket.FLAG_POSITION_LOCKED) != 0; + lockedYaw = yaw; + lockedPitch = pitch; + } + + /** + * Whether player WASD movement input should be suppressed. + * True when movement/position is locked or ability has its own movement. + */ + public static boolean shouldSuppressMovementInput() { + return movementLocked || hasAbilityMovement || positionLocked; + } + + /** + * Whether player camera rotation should be locked. + */ + public static boolean shouldLockRotation() { + return rotationLocked; + } + + /** + * Reset all state. Called on world change / disconnect. + */ + public static void reset() { + movementLocked = false; + rotationLocked = false; + hasAbilityMovement = false; + positionLocked = false; + lockedYaw = 0; + lockedPitch = 0; + } +} diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 203cef3e2..b4e8738c8 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -56,6 +56,7 @@ public class ClientTickHandler { if ((this.prevWorld == null || mc.theWorld == null) && this.prevWorld != mc.theWorld) { if (mc.theWorld == null) { ClientCacheHandler.clearCache(); + ClientAbilityState.reset(); } this.prevWorld = mc.theWorld; } @@ -72,6 +73,19 @@ public class ClientTickHandler { lastSpecialKeyDown = specialKeyDown; } + // Suppress player input during ability-controlled phases + if (ClientAbilityState.shouldSuppressMovementInput()) { + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + } + if (ClientAbilityState.shouldLockRotation()) { + mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch; + } + if (player.ridingEntity instanceof EntityNPCInterface) { EntityNPCInterface mount = (EntityNPCInterface) player.ridingEntity; if (mount.advanced.role == EnumRoleType.Mount && mount.roleInterface instanceof RoleMount) { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 3e6489b1c..7807074f3 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -19,6 +19,7 @@ import noppes.npcs.api.ability.IPlayerAbilityData; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import java.util.ArrayList; @@ -77,6 +78,26 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private transient EntityLivingBase currentTarget; + /** + * Rotation lock state - freezes player yaw/pitch during ability phases. + */ + private transient boolean rotationLocked = false; + private transient float lockedYaw = 0; + private transient float lockedPitch = 0; + + /** + * Position lock state - freezes player position during ability phases. + */ + private transient boolean positionLocked = false; + private transient double lockedPosX = 0; + private transient double lockedPosY = 0; + private transient double lockedPosZ = 0; + + /** + * Last synced state flags byte for change detection (avoids spamming packets). + */ + private transient byte lastSyncedFlags = 0; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -100,6 +121,20 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (currentAbility != null && currentAbility.isExecuting()) { tickCurrentAbility(player); + + // Apply rotation and position locks after ability tick + applyRotationControl(player); + applyPositionLock(player); + + // Sync lock state to client (only sends when flags change) + syncAbilityStateIfNeeded(player); + } else { + // Safety: release orphaned locks if no ability is executing + if (rotationLocked || positionLocked) { + releaseRotationControl(); + releaseLockedPosition(); + syncAbilityStateClear(player); + } } } @@ -114,17 +149,47 @@ public class PlayerAbilityData implements IPlayerAbilityData { switch (currentAbility.getPhase()) { case WINDUP: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up locks + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(player); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(player); + } + spawnTelegraph(currentAbility, player, null); + playAbilitySound(player, currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } currentAbility.onWindUpTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); break; case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { // Just entered ACTIVE phase - lock all telegraph positions for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } removeTelegraph(currentAbility, player); + // Handle rotation control transition from WINDUP to ACTIVE + if (currentAbility.isRotationLockedDuringActive()) { + if (!rotationLocked) { + captureLockedRotation(player); + } + } else if (rotationLocked) { + releaseRotationControl(); + } + + // Handle position lock transition from WINDUP to ACTIVE + if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { + if (!positionLocked) { + captureLockedPosition(player); + } + } else if (positionLocked) { + releaseLockedPosition(); + } + // Play active sound and animation playAbilitySound(player, currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); @@ -143,6 +208,18 @@ public class PlayerAbilityData implements IPlayerAbilityData { handleAbilityCompletion(player); return; } + + // Release locks during burst delay + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); break; case DAZED: @@ -163,6 +240,10 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentAbility.onComplete(player, currentTarget); + // Release all locks + releaseRotationControl(); + releaseLockedPosition(); + // Apply universal cooldown (using base cooldownTicks only, not min/max random) if (!currentAbility.isIgnoreCooldown()) { cooldownEndTime = player.worldObj.getTotalWorldTime() + currentAbility.getCooldownTicks(); @@ -174,6 +255,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentAbility = null; currentAbilityKey = null; currentTarget = null; + + // Send cleared state to client + syncAbilityStateClear(player); } // ═══════════════════════════════════════════════════════════════════ @@ -231,9 +315,21 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (ability.getPhase() == AbilityPhase.ACTIVE) { // Windup was 0 — skip telegraph/windup and go straight to active + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(player); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(player); + } executeImmediate(ability, player); } else { // Normal windup flow + if (ability.isRotationLockedDuringWindup()) { + captureLockedRotation(player); + } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(player); + } spawnTelegraph(ability, player, null); playAbilitySound(player, ability.getWindUpSound()); playAbilityAnimation(ability.getWindUpAnimation()); @@ -412,9 +508,12 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (currentAbility != null && currentAbility.isExecuting()) { currentAbility.interrupt(); stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); currentAbility = null; currentAbilityKey = null; currentTarget = null; + syncAbilityStateClear(playerData.player); } } @@ -493,6 +592,129 @@ public class PlayerAbilityData implements IPlayerAbilityData { && currentAbility.isMovementLockedForCurrentPhase(); } + // ═══════════════════════════════════════════════════════════════════ + // ROTATION CONTROL + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current rotation values to lock player's look direction. + */ + private void captureLockedRotation(EntityPlayer player) { + lockedYaw = player.rotationYaw; + lockedPitch = player.rotationPitch; + rotationLocked = true; + } + + /** + * Release rotation lock. + */ + private void releaseRotationControl() { + rotationLocked = false; + } + + /** + * Apply rotation control on the server side. + * Enforces locked rotation values on the player entity. + */ + private void applyRotationControl(EntityPlayer player) { + if (!rotationLocked || currentAbility == null) return; + + if (currentAbility.isRotationLockedForCurrentPhase()) { + player.rotationYaw = lockedYaw; + player.rotationPitch = lockedPitch; + player.prevRotationYaw = lockedYaw; + player.prevRotationPitch = lockedPitch; + if (player instanceof EntityPlayerMP) { + player.rotationYawHead = lockedYaw; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current position to lock player in place. + */ + private void captureLockedPosition(EntityPlayer player) { + lockedPosX = player.posX; + lockedPosY = player.posY; + lockedPosZ = player.posZ; + positionLocked = true; + } + + /** + * Release position lock. + */ + private void releaseLockedPosition() { + positionLocked = false; + } + + /** + * Apply position lock on the server side. + * Snaps player back to locked position and zeroes motion. + */ + private void applyPositionLock(EntityPlayer player) { + if (!positionLocked) return; + + player.setPosition(lockedPosX, lockedPosY, lockedPosZ); + player.prevPosX = lockedPosX; + player.prevPosY = lockedPosY; + player.prevPosZ = lockedPosZ; + player.motionX = 0; + player.motionZ = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // ABILITY STATE SYNC + // ═══════════════════════════════════════════════════════════════════ + + /** + * Build the current ability state flags byte. + */ + private byte getAbilityStateFlags() { + byte flags = 0; + if (currentAbility == null || !currentAbility.isExecuting()) return flags; + + if (currentAbility.isMovementLockedForCurrentPhase()) { + flags |= PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED; + } + if (rotationLocked && currentAbility.isRotationLockedForCurrentPhase()) { + flags |= PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED; + } + if (currentAbility.hasAbilityMovement() && currentAbility.getPhase() == AbilityPhase.ACTIVE) { + flags |= PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT; + } + if (positionLocked) { + flags |= PlayerAbilityStatePacket.FLAG_POSITION_LOCKED; + } + return flags; + } + + /** + * Send ability state to client if flags changed since last sync. + */ + private void syncAbilityStateIfNeeded(EntityPlayer player) { + if (!(player instanceof EntityPlayerMP)) return; + byte flags = getAbilityStateFlags(); + if (flags != lastSyncedFlags) { + lastSyncedFlags = flags; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, flags, lockedYaw, lockedPitch); + } + } + + /** + * Send cleared (all-zero) state to client. Called on ability completion/interrupt. + */ + private void syncAbilityStateClear(EntityPlayer player) { + if (!(player instanceof EntityPlayerMP)) return; + if (lastSyncedFlags != 0) { + lastSyncedFlags = 0; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0); + } + } + // ═══════════════════════════════════════════════════════════════════ // TELEGRAPH // ═══════════════════════════════════════════════════════════════════ From 2a1a5643d3a1eb2537ae95f0b837f28b93b066d1 Mon Sep 17 00:00:00 2001 From: Kam Date: Fri, 13 Feb 2026 14:17:17 -0500 Subject: [PATCH 47/76] Potion Effect System + Manual and Remove Bulk --- .../controllers/data/ability/Ability.java | 60 ++++------- .../data/ability/AbilityEffect.java | 99 +++++++------------ .../data/ability/data/EnergyAnchorData.java | 8 +- .../data/ability/data/EnergyCombatData.java | 12 +-- .../data/ability/data/EnergyDisplayData.java | 12 +-- .../data/ability/data/EnergyHomingData.java | 8 +- .../data/ability/data/EnergyLifespanData.java | 4 +- .../ability/data/EnergyLightningData.java | 8 +- .../ability/data/EnergyTrajectoryData.java | 6 +- .../data/ability/data/ProjectileData.java | 4 +- .../data/ability/gui/AbilityFieldBuilder.java | 53 +++++++--- .../data/ability/type/AbilityBeam.java | 8 +- .../data/ability/type/AbilityCharge.java | 14 +-- .../data/ability/type/AbilityCutter.java | 16 +-- .../data/ability/type/AbilityDash.java | 4 +- .../data/ability/type/AbilityDisc.java | 14 +-- .../data/ability/type/AbilityGuard.java | 24 ++--- .../data/ability/type/AbilityHazard.java | 10 +- .../data/ability/type/AbilityHeal.java | 14 +-- .../data/ability/type/AbilityHeavyHit.java | 8 +- .../data/ability/type/AbilityLaserShot.java | 6 +- .../data/ability/type/AbilityOrb.java | 6 +- .../data/ability/type/AbilityProjectile.java | 16 +-- .../data/ability/type/AbilityShockwave.java | 8 +- .../data/ability/type/AbilitySlam.java | 10 +- .../data/ability/type/AbilitySweeper.java | 18 ++-- .../data/ability/type/AbilityTeleport.java | 28 +++--- .../data/ability/type/AbilityTrap.java | 16 +-- .../data/ability/type/AbilityVortex.java | 16 +-- .../data/ability/type/AbilityZone.java | 63 ++++++------ src/main/java/noppes/npcs/DataStats.java | 16 ++- .../client/gui/SubGuiNpcMeleeProperties.java | 27 +++-- .../npcs/client/gui/SubGuiNpcProjectiles.java | 24 +++-- .../npcs/client/gui/util/GuiNPCInterface.java | 3 +- .../noppes/npcs/constants/EnumPotionType.java | 80 ++++++++++++++- .../npcs/entity/EntityNPCInterface.java | 35 ++----- .../noppes/npcs/entity/EntityProjectile.java | 82 ++++++--------- .../assets/customnpcs/lang/en_US.lang | 2 + 38 files changed, 427 insertions(+), 415 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 f0b8ceb07..2a4f39b8f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -1181,61 +1181,37 @@ public abstract class Ability implements IAbility { maxRange = nbt.getFloat("maxRange"); cooldownTicks = nbt.getInteger("cooldown"); windUpTicks = nbt.getInteger("windUp"); - syncWindupWithAnimation = !nbt.hasKey("syncWindup") || nbt.getBoolean("syncWindup"); + syncWindupWithAnimation = nbt.getBoolean("syncWindup"); dazedTicks = nbt.getInteger("recovery"); interruptible = nbt.getBoolean("interruptible"); lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement")); - if (nbt.hasKey("rotationMode")) { - // Current format - rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); - rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); - } else if (nbt.hasKey("lockType")) { - // Legacy format migration: lockType was LockType enum (0=MOVEMENT, 1=ROTATION, 2=BOTH) - int oldLockType = nbt.getInteger("lockType"); - if (oldLockType == 0) { - // MOVEMENT only: movement locked, rotation was free - rotationMode = RotationMode.FREE; - } else if (oldLockType == 1) { - // ROTATION only: rotation locked same timing as old lockMovement, movement was free - rotationMode = RotationMode.LOCKED; - rotationPhase = lockMovement; - lockMovement = LockMovementType.NO; - } else { - // BOTH: both locked same timing - rotationMode = RotationMode.LOCKED; - rotationPhase = lockMovement; - } - } else { - rotationMode = RotationMode.FREE; - rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; - } + rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); + rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); windUpColor = nbt.getInteger("windUpColor"); activeColor = nbt.getInteger("activeColor"); windUpSound = nbt.getString("windUpSound"); activeSound = nbt.getString("activeSound"); - windUpAnimationId = nbt.hasKey("windUpAnimationId") ? nbt.getInteger("windUpAnimationId") : -1; - activeAnimationId = nbt.hasKey("activeAnimationId") ? nbt.getInteger("activeAnimationId") : -1; + windUpAnimationId = nbt.getInteger("windUpAnimationId"); + activeAnimationId = nbt.getInteger("activeAnimationId"); windUpAnimationName = nbt.getString("windUpAnimationName"); activeAnimationName = nbt.getString("activeAnimationName"); - showTelegraph = !nbt.hasKey("showTelegraph") || nbt.getBoolean("showTelegraph"); - if (nbt.hasKey("telegraphType")) { - try { - telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); - } catch (Exception e) { - telegraphType = TelegraphType.CIRCLE; - } + showTelegraph = nbt.getBoolean("showTelegraph"); + try { + telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); + } catch (Exception e) { + telegraphType = TelegraphType.CIRCLE; } - telegraphHeightOffset = nbt.hasKey("telegraphHeightOffset") ? nbt.getFloat("telegraphHeightOffset") : 0.1f; + telegraphHeightOffset = nbt.getFloat("telegraphHeightOffset"); customData = nbt.getCompoundTag("customData"); - allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH; - ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown"); + allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); + ignoreCooldown = nbt.getBoolean("ignoreCooldown"); // Burst - burstEnabled = nbt.hasKey("burstEnabled") && nbt.getBoolean("burstEnabled"); - burstAmount = nbt.hasKey("burstAmount") ? nbt.getInteger("burstAmount") : 0; - burstDelay = nbt.hasKey("burstDelay") ? nbt.getInteger("burstDelay") : 0; - burstReplayAnimations = !nbt.hasKey("burstReplayAnimations") || nbt.getBoolean("burstReplayAnimations"); - burstOverlap = nbt.hasKey("burstOverlap") && nbt.getBoolean("burstOverlap"); + burstEnabled = nbt.getBoolean("burstEnabled"); + burstAmount = nbt.getInteger("burstAmount"); + burstDelay = nbt.getInteger("burstDelay"); + burstReplayAnimations = nbt.getBoolean("burstReplayAnimations"); + burstOverlap = nbt.getBoolean("burstOverlap"); // Conditions conditions.clear(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java index 73f465049..e2c1da87d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java @@ -2,67 +2,24 @@ package kamkeel.npcs.controllers.data.ability; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; +import noppes.npcs.constants.EnumPotionType; /** * Represents a configurable potion effect that can be applied by abilities. - * Provides a unified system for managing debuffs like slowness, weakness, poison, etc. + * Uses the unified EnumPotionType enum shared across melee, ranged, and ability systems. */ public class AbilityEffect { - public enum EffectType { - NONE("gui.none", -1), - SLOWNESS("potion.moveSlowdown", Potion.moveSlowdown.id), - WEAKNESS("potion.weakness", Potion.weakness.id), - POISON("potion.poison", Potion.poison.id), - WITHER("potion.wither", Potion.wither.id), - BLINDNESS("potion.blindness", Potion.blindness.id), - NAUSEA("potion.confusion", Potion.confusion.id), - HUNGER("potion.hunger", Potion.hunger.id), - MINING_FATIGUE("potion.digSlowDown", Potion.digSlowdown.id), - BURN("ability.effect.burn", -1); - - private final String langKey; - private final int potionId; - - EffectType(String langKey, int potionId) { - this.langKey = langKey; - this.potionId = potionId; - } - - public String getLangKey() { - return langKey; - } - - public int getPotionId() { - return potionId; - } - - public static String[] getLangKeys() { - EffectType[] types = values(); - String[] keys = new String[types.length]; - for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; - return keys; - } - - public static EffectType fromOrdinal(int ordinal) { - EffectType[] values = values(); - if (ordinal >= 0 && ordinal < values.length) { - return values[ordinal]; - } - return NONE; - } - } - - private EffectType type = EffectType.NONE; + private EnumPotionType type = EnumPotionType.None; + private int manualPotionId = 0; private int durationTicks = 60; private int amplifier = 0; // 0-10 public AbilityEffect() { } - public AbilityEffect(EffectType type, int durationTicks, int amplifier) { + public AbilityEffect(EnumPotionType type, int durationTicks, int amplifier) { this.type = type; this.durationTicks = Math.max(1, durationTicks); this.amplifier = Math.max(0, Math.min(10, amplifier)); @@ -72,25 +29,27 @@ public class AbilityEffect { * Creates a copy of this effect. */ public AbilityEffect copy() { - return new AbilityEffect(type, durationTicks, amplifier); + AbilityEffect copy = new AbilityEffect(type, durationTicks, amplifier); + copy.manualPotionId = this.manualPotionId; + return copy; } /** * Applies this effect to the given entity. - * Does nothing if type is NONE. + * Does nothing if type is None. Validates potion IDs before applying. */ public void apply(EntityLivingBase entity) { - if (entity == null || type == EffectType.NONE) { + if (entity == null || type == EnumPotionType.None) { return; } - if (type == EffectType.BURN) { + if (type == EnumPotionType.Fire) { entity.setFire(Math.max(1, durationTicks / 20)); return; } - int potionId = type.getPotionId(); - if (potionId >= 0) { + int potionId = type.getResolvedPotionId(manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier)); } } @@ -100,9 +59,12 @@ public class AbilityEffect { */ public NBTTagCompound writeNBT() { NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("type", type.ordinal()); + nbt.setInteger("potionType", type.ordinal()); nbt.setInteger("duration", durationTicks); nbt.setInteger("amplifier", amplifier); + if (type == EnumPotionType.Manual) { + nbt.setInteger("manualPotionId", manualPotionId); + } return nbt; } @@ -110,9 +72,12 @@ public class AbilityEffect { * Reads this effect from NBT. */ public void readNBT(NBTTagCompound nbt) { - this.type = EffectType.fromOrdinal(nbt.getInteger("type")); - this.durationTicks = nbt.hasKey("duration") ? nbt.getInteger("duration") : 60; - this.amplifier = nbt.hasKey("amplifier") ? nbt.getInteger("amplifier") : 0; + this.type = EnumPotionType.fromOrdinal(nbt.getInteger("potionType")); + this.durationTicks = nbt.getInteger("duration"); + this.amplifier = nbt.getInteger("amplifier"); + if (type == EnumPotionType.Manual) { + this.manualPotionId = nbt.getInteger("manualPotionId"); + } } /** @@ -126,12 +91,20 @@ public class AbilityEffect { // Getters & Setters - public EffectType getType() { + public EnumPotionType getType() { return type; } - public void setType(EffectType type) { - this.type = type != null ? type : EffectType.NONE; + public void setType(EnumPotionType type) { + this.type = type != null ? type : EnumPotionType.None; + } + + public int getManualPotionId() { + return manualPotionId; + } + + public void setManualPotionId(int manualPotionId) { + this.manualPotionId = Math.max(0, manualPotionId); } public int getDurationTicks() { @@ -151,9 +124,9 @@ public class AbilityEffect { } /** - * Returns true if this effect is configured (not NONE). + * Returns true if this effect is configured (not None). */ public boolean isValid() { - return type != EffectType.NONE; + return type != EnumPotionType.None; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java index 2187802a5..99c51b23c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java @@ -91,10 +91,10 @@ public class EnergyAnchorData implements IEnergyAnchorData { } public void readNBT(NBTTagCompound nbt) { - this.anchorPoint = nbt.hasKey("anchorPoint") ? AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")) : AnchorPoint.FRONT; - this.anchorOffsetX = nbt.hasKey("anchorOffsetX") ? nbt.getFloat("anchorOffsetX") : 0; - this.anchorOffsetY = nbt.hasKey("anchorOffsetY") ? nbt.getFloat("anchorOffsetY") : 0; - this.anchorOffsetZ = nbt.hasKey("anchorOffsetZ") ? nbt.getFloat("anchorOffsetZ") : 0; + this.anchorPoint = AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")); + this.anchorOffsetX = nbt.getFloat("anchorOffsetX"); + this.anchorOffsetY = nbt.getFloat("anchorOffsetY"); + this.anchorOffsetZ = nbt.getFloat("anchorOffsetZ"); } public EnergyAnchorData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java index 52f5368f0..e6ccf15a1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java @@ -97,12 +97,12 @@ public class EnergyCombatData implements IEnergyCombatData { } public void readNBT(NBTTagCompound nbt) { - damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f; - knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.0f; - knockbackUp = nbt.hasKey("knockbackUp") ? nbt.getFloat("knockbackUp") : 0.1f; - explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive"); - explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 3.0f; - explosionDamageFalloff = nbt.hasKey("explosionDamageFalloff") ? nbt.getFloat("explosionDamageFalloff") : 0.5f; + damage = nbt.getFloat("damage"); + knockback = nbt.getFloat("knockback"); + knockbackUp = nbt.getFloat("knockbackUp"); + explosive = nbt.getBoolean("explosive"); + explosionRadius = nbt.getFloat("explosionRadius"); + explosionDamageFalloff = nbt.getFloat("explosionDamageFalloff"); } public EnergyCombatData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java index 0d91e1012..559be77f4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java @@ -102,12 +102,12 @@ public class EnergyDisplayData implements IEnergyDisplayData { } public void readNBT(NBTTagCompound nbt) { - innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF; - outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled"); - outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f; - outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; - rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; + innerColor = nbt.getInteger("innerColor"); + outerColor = nbt.getInteger("outerColor"); + outerColorEnabled = nbt.getBoolean("outerColorEnabled"); + outerColorWidth = nbt.getFloat("outerColorWidth"); + outerColorAlpha = nbt.getFloat("outerColorAlpha"); + rotationSpeed = nbt.getFloat("rotationSpeed"); } public EnergyDisplayData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java index 1e81882c7..d385c06e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java @@ -71,10 +71,10 @@ public class EnergyHomingData implements IEnergyHomingData { } public void readNBT(NBTTagCompound nbt) { - speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 0.5f; - homing = !nbt.hasKey("homing") || nbt.getBoolean("homing"); - homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.15f; - homingRange = nbt.hasKey("homingRange") ? nbt.getFloat("homingRange") : 20.0f; + speed = nbt.getFloat("speed"); + homing = nbt.getBoolean("homing"); + homingStrength = nbt.getFloat("homingStrength"); + homingRange = nbt.getFloat("homingRange"); } public EnergyHomingData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java index 9e017e2a5..f320acdb0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java @@ -44,8 +44,8 @@ public class EnergyLifespanData implements IEnergyLifespanData { } public void readNBT(NBTTagCompound nbt) { - maxDistance = nbt.hasKey("maxDistance") ? nbt.getFloat("maxDistance") : 30.0f; - maxLifetime = nbt.hasKey("maxLifetime") ? nbt.getInteger("maxLifetime") : 200; + maxDistance = nbt.getFloat("maxDistance"); + maxLifetime = nbt.getInteger("maxLifetime"); } public EnergyLifespanData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java index 00d0eaa96..66786a14a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java @@ -71,10 +71,10 @@ public class EnergyLightningData implements IEnergyLightningData { } public void readNBT(NBTTagCompound nbt) { - lightningEffect = nbt.hasKey("lightningEffect") && nbt.getBoolean("lightningEffect"); - lightningDensity = nbt.hasKey("lightningDensity") ? nbt.getFloat("lightningDensity") : 0.15f; - lightningRadius = nbt.hasKey("lightningRadius") ? nbt.getFloat("lightningRadius") : 0.5f; - lightningFadeTime = nbt.hasKey("lightningFadeTime") ? nbt.getInteger("lightningFadeTime") : 6; + lightningEffect = nbt.getBoolean("lightningEffect"); + lightningDensity = nbt.getFloat("lightningDensity"); + lightningRadius = nbt.getFloat("lightningRadius"); + lightningFadeTime = nbt.getInteger("lightningFadeTime"); } public EnergyLightningData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java index 7cc15a706..15adb3062 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java @@ -184,7 +184,7 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { } public void readNBT(NBTTagCompound nbt) { - this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0; + this.currentPath = nbt.getInteger("currentPath"); int i = 0; while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) { @@ -275,8 +275,8 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { } public void readNBT(NBTTagCompound nbt) { - this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0; - this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded"); + this.delayTicks = nbt.getInteger("delay"); + this.concluded = nbt.getBoolean("concluded"); double x = nbt.getDouble("X"); double y = nbt.getDouble("Y"); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java index 49ee50f7e..94850470f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -44,8 +44,8 @@ public class ProjectileData { anchor.readNBT(nbt); colorOverride = nbt.getBoolean("colorOverride"); if (colorOverride) { - innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF; + innerColor = nbt.getInteger("overrideInnerColor"); + outerColor = nbt.getInteger("overrideOuterColor"); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java index 5edd0a718..219479614 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java @@ -12,6 +12,7 @@ import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.constants.EnumPotionType; import java.util.ArrayList; import java.util.HashMap; @@ -26,7 +27,7 @@ import java.util.Map; public class AbilityFieldBuilder extends GuiFieldBuilder { // Effects list metadata: widgetId -> [effectIndex, action] - // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add + // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text) private final Map effectWidgetMeta = new HashMap<>(); public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { @@ -57,15 +58,15 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { List effects = (List) def.getValue(); if (effects == null) effects = new ArrayList<>(); - String[] typeNames = AbilityEffect.EffectType.getLangKeys(); + String[] typeNames = EnumPotionType.getLangKeysNoNone(); String[] ampValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; for (int e = 0; e < effects.size() && e < 5; e++) { AbilityEffect effect = effects.get(e); - // Type selector button - int typeIdx = effect.getType().ordinal(); - GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx); + // Type selector button (index offset by -1 since None is excluded) + int typeIdx = effect.getType().ordinal() - 1; + GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, Math.max(0, typeIdx)); sw.addButton(typeBtn); buttonFieldMap.put(widgetId, def); effectWidgetMeta.put(widgetId, new int[]{e, 0}); @@ -81,12 +82,16 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { effectWidgetMeta.put(widgetId, new int[]{e, 1}); widgetId++; - // Amplifier selector (0-10) - GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); - sw.addButton(ampBtn); - buttonFieldMap.put(widgetId, def); - effectWidgetMeta.put(widgetId, new int[]{e, 2}); - widgetId++; + if (effect.getType() != EnumPotionType.Fire) { + // Amplifier selector (0-10) — not applicable to Fire + GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); + sw.addButton(ampBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 2}); + widgetId++; + } else { + widgetId++; // keep widgetId in sync + } // Delete button GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); @@ -96,6 +101,20 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { clearId++; y += rowHeight; + + // Manual potion ID field (shown on next row when type is Manual) + if (effect.getType() == EnumPotionType.Manual) { + sw.addLabel(new GuiNpcLabel(labelId++, "effect.potionid", colLLabel, y + 5, 0xFFFFFF)); + GuiNpcTextField idField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 80, y, 50, 20, String.valueOf(effect.getManualPotionId())); + idField.setIntegersOnly(); + idField.setMinMaxDefault(0, Integer.MAX_VALUE, 0); + sw.addTextField(idField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 5}); + widgetId++; + y += rowHeight; + } } // Add button (if < 5 effects) @@ -133,7 +152,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { switch (action) { case 0: // Type changed if (effectIdx < effects.size()) { - effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue())); + effects.get(effectIdx).setType(EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue())); } return true; case 2: // Amp changed @@ -148,7 +167,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { return true; case 4: // Add if (effects.size() < 5) { - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0)); + effects.add(new AbilityEffect(EnumPotionType.Slowness, 60, 0)); } return true; } @@ -162,12 +181,16 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @SuppressWarnings("unchecked") public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { int[] meta = effectWidgetMeta.get(textFieldId); - if (meta != null && meta[1] == 1) { // duration field + if (meta != null) { FieldDef def = textFieldMap.get(textFieldId); if (def != null && def.getType() == FieldType.EFFECTS_LIST) { List effects = (List) def.getValue(); if (effects != null && meta[0] < effects.size()) { - effects.get(meta[0]).setDurationTicks(field.getInteger()); + if (meta[1] == 1) { // duration field + effects.get(meta[0]).setDurationTicks(field.getInteger()); + } else if (meta[1] == 5) { // manual potion ID field + effects.get(meta[0]).setManualPotionId(field.getInteger()); + } } return true; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 8bf2341f5..d02c19bdd 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -356,13 +356,13 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; + this.beamWidth = nbt.getFloat("beamWidth"); + this.headSize = nbt.getFloat("headSize"); - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + int count = nbt.getInteger("projectileCount"); initProjectiles(count); - this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; + this.fireDelay = nbt.getInteger("fireDelay"); combatData.readNBT(nbt); homingData.readNBT(nbt); 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 d9fd9b598..7cfb44428 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 @@ -359,16 +359,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.chargeSpeed = nbt.hasKey("chargeSpeed") ? nbt.getFloat("chargeSpeed") : 0.8f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 3.0f; - if (nbt.hasKey("hitWidth")) { - this.hitWidth = nbt.getFloat("hitWidth"); - } else if (nbt.hasKey("hitRadius")) { - this.hitWidth = nbt.getFloat("hitRadius"); - } else { - this.hitWidth = 1.5f; - } + this.chargeSpeed = nbt.getFloat("chargeSpeed"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.hitWidth = nbt.getFloat("hitWidth"); } // Getters & Setters 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 900ae6080..110bda19f 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 @@ -326,19 +326,19 @@ public class AbilityCutter extends Ability implements IAbilityCutter { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.arcAngle = nbt.hasKey("arcAngle") ? nbt.getFloat("arcAngle") : 90.0f; - this.range = nbt.hasKey("range") ? nbt.getFloat("range") : 6.0f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.5f; + this.arcAngle = nbt.getFloat("arcAngle"); + this.range = nbt.getFloat("range"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); try { this.sweepMode = SweepMode.valueOf(nbt.getString("sweepMode")); } catch (Exception e) { this.sweepMode = SweepMode.SWIPE; } - this.sweepSpeed = nbt.hasKey("sweepSpeed") ? nbt.getFloat("sweepSpeed") : 6.0f; - this.spinDurationTicks = nbt.hasKey("spinDurationTicks") ? nbt.getInteger("spinDurationTicks") : 60; - this.piercing = !nbt.hasKey("piercing") || nbt.getBoolean("piercing"); - this.innerRadius = nbt.hasKey("innerRadius") ? nbt.getFloat("innerRadius") : 0.0f; + this.sweepSpeed = nbt.getFloat("sweepSpeed"); + this.spinDurationTicks = nbt.getInteger("spinDurationTicks"); + this.piercing = nbt.getBoolean("piercing"); + this.innerRadius = nbt.getFloat("innerRadius"); } // Getters & Setters 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 b15f1f822..6070342d7 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 @@ -310,8 +310,8 @@ public class AbilityDash extends Ability implements IAbilityDash { } catch (Exception e) { this.dashMode = DashMode.DEFENSIVE; } - this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; - this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 0.5f; + this.dashDistance = nbt.getFloat("dashDistance"); + this.dashSpeed = nbt.getFloat("dashSpeed"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 886a269e2..2448642e0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -368,16 +368,16 @@ public class AbilityDisc extends Ability implements IAbilityDisc { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; - this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; - this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); - this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); - this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; + this.discRadius = nbt.getFloat("discRadius"); + this.discThickness = nbt.getFloat("discThickness"); + this.vertical = nbt.getBoolean("vertical"); + this.boomerang = nbt.getBoolean("boomerang"); + this.boomerangDelay = nbt.getInteger("boomerangDelay"); - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + int count = nbt.getInteger("projectileCount"); initProjectiles(count); - this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; + this.fireDelay = nbt.getInteger("fireDelay"); // Shared combat/movement data combatData.readNBT(nbt); 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 461fef2bd..87fd21a7f 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 @@ -238,27 +238,19 @@ public class AbilityGuard extends Ability implements IAbilityGuard { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; - this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f; - this.canCounter = nbt.hasKey("canCounter") && nbt.getBoolean("canCounter"); - this.counterWindow = nbt.hasKey("counterWindow") ? nbt.getInteger("counterWindow") : 10; + this.durationTicks = nbt.getInteger("durationTicks"); + this.damageReduction = nbt.getFloat("damageReduction"); + this.canCounter = nbt.getBoolean("canCounter"); + this.counterWindow = nbt.getInteger("counterWindow"); try { this.counterType = CounterType.valueOf(nbt.getString("counterType")); } catch (Exception e) { this.counterType = CounterType.FLAT; } - if (nbt.hasKey("counterValue")) { - this.counterValue = nbt.getFloat("counterValue"); - } else if (nbt.hasKey("counterDamage")) { - this.counterValue = nbt.getFloat("counterDamage"); - } else { - this.counterValue = 6.0f; - } - this.counterSound = nbt.hasKey("counterSound") ? nbt.getString("counterSound") : "random.wood_click"; - this.counterAnimationId = nbt.hasKey("counterAnimationId") ? nbt.getInteger("counterAnimationId") : -1; - this.counterAnimationName = nbt.hasKey("counterAnimationName") ? - nbt.getString("counterAnimationName") : - "Ability_Guard_Counter"; + this.counterValue = nbt.getFloat("counterValue"); + this.counterSound = nbt.getString("counterSound"); + this.counterAnimationId = nbt.getInteger("counterAnimationId"); + this.counterAnimationName = nbt.getString("counterAnimationName"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index a8bbafc1a..e5dfde01e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -115,11 +115,11 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { @Override public void readTypeNBT(NBTTagCompound nbt) { readZoneNBT(nbt, 300); - this.radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 2.0f; - this.damagePerSecond = nbt.hasKey("damagePerSecond") ? nbt.getFloat("damagePerSecond") : 1.0f; - this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 20; - this.ignoreInvulnFrames = nbt.hasKey("ignoreInvulnFrames") && nbt.getBoolean("ignoreInvulnFrames"); - this.affectsCaster = nbt.hasKey("affectsCaster") && nbt.getBoolean("affectsCaster"); + this.radius = nbt.getFloat("radius"); + this.damagePerSecond = nbt.getFloat("damagePerSecond"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.ignoreInvulnFrames = nbt.getBoolean("ignoreInvulnFrames"); + this.affectsCaster = nbt.getBoolean("affectsCaster"); } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index d913fe586..d2714ddd2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -227,13 +227,13 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; - this.healAmount = nbt.hasKey("healAmount") ? nbt.getFloat("healAmount") : 10.0f; - this.healPercent = nbt.hasKey("healPercent") ? nbt.getFloat("healPercent") : 0.0f; - this.healSelf = !nbt.hasKey("healSelf") || nbt.getBoolean("healSelf"); - this.healAllies = nbt.hasKey("healAllies") && nbt.getBoolean("healAllies"); - this.healRadius = nbt.hasKey("healRadius") ? nbt.getFloat("healRadius") : 0.0f; - this.instantHeal = !nbt.hasKey("instantHeal") || nbt.getBoolean("instantHeal"); + this.durationTicks = nbt.getInteger("durationTicks"); + this.healAmount = nbt.getFloat("healAmount"); + this.healPercent = nbt.getFloat("healPercent"); + this.healSelf = nbt.getBoolean("healSelf"); + this.healAllies = nbt.getBoolean("healAllies"); + this.healRadius = nbt.getFloat("healRadius"); + this.instantHeal = nbt.getBoolean("instantHeal"); } // Getters & Setters 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 dd5d5fc09..cf49cade6 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 @@ -135,10 +135,10 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 2.0f; - this.hitLength = nbt.hasKey("hitLength") ? nbt.getFloat("hitLength") : 4.0f; - this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 3.0f; + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.hitLength = nbt.getFloat("hitLength"); + this.hitWidth = nbt.getFloat("hitWidth"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index afffa9c13..a726e4c25 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -190,9 +190,9 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.laserWidth = nbt.hasKey("laserWidth") ? nbt.getFloat("laserWidth") : 0.3f; - this.expansionSpeed = nbt.hasKey("expansionSpeed") ? nbt.getFloat("expansionSpeed") : 3.0f; - this.lingerTicks = nbt.hasKey("lingerTicks") ? nbt.getInteger("lingerTicks") : 8; + this.laserWidth = nbt.getFloat("laserWidth"); + this.expansionSpeed = nbt.getFloat("expansionSpeed"); + this.lingerTicks = nbt.getInteger("lingerTicks"); anchorData.readNBT(nbt); colorData.readNBT(nbt); combatData.readNBT(nbt); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 8b4783f7c..5dbf58424 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -364,12 +364,12 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; + this.orbSize = nbt.getFloat("orbSize"); - int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + int count = nbt.getInteger("projectileCount"); initProjectiles(count); - this.fireDelay = nbt.hasKey("fireDelay") ? nbt.getInteger("fireDelay") : 0; + this.fireDelay = nbt.getInteger("fireDelay"); // Shared combat/movement data combatData.readNBT(nbt); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index 8abd5d01e..d79f783d1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -273,14 +273,14 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 6.0f; - this.speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 1.5f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; - this.projectileType = nbt.hasKey("projectileType") ? nbt.getString("projectileType") : "fireball"; - this.explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive"); - this.explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 0.0f; - this.homing = nbt.hasKey("homing") && nbt.getBoolean("homing"); - this.homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.1f; + this.damage = nbt.getFloat("damage"); + this.speed = nbt.getFloat("speed"); + this.knockback = nbt.getFloat("knockback"); + this.projectileType = nbt.getString("projectileType"); + this.explosive = nbt.getBoolean("explosive"); + this.explosionRadius = nbt.getFloat("explosionRadius"); + this.homing = nbt.getBoolean("homing"); + this.homingStrength = nbt.getFloat("homingStrength"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 0ef0dc50f..17fdecceb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -127,10 +127,10 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.pushRadius = nbt.hasKey("pushRadius") ? nbt.getFloat("pushRadius") : 8.0f; - this.pushStrength = nbt.hasKey("pushStrength") ? nbt.getFloat("pushStrength") : 1.5f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.maxTargets = nbt.hasKey("maxTargets") ? nbt.getInteger("maxTargets") : 10; + this.pushRadius = nbt.getFloat("pushRadius"); + this.pushStrength = nbt.getFloat("pushStrength"); + this.damage = nbt.getFloat("damage"); + this.maxTargets = nbt.getInteger("maxTargets"); } // Getters & Setters 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 fc9a6b5be..22fd99416 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 @@ -509,11 +509,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void readTypeNBT(NBTTagCompound nbt) { - damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 10.0f; - radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 5.0f; - knockbackStrength = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.5f; - leapSpeed = nbt.hasKey("leapSpeed") ? nbt.getFloat("leapSpeed") : 1.0f; - leapHeight = nbt.hasKey("leapHeight") ? nbt.getFloat("leapHeight") : 4.0f; + damage = nbt.getFloat("damage"); + radius = nbt.getFloat("radius"); + knockbackStrength = nbt.getFloat("knockback"); + leapSpeed = nbt.getFloat("leapSpeed"); + leapHeight = nbt.getFloat("leapHeight"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 8638dd2a4..43a152f7a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -172,15 +172,15 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.beamLength = nbt.hasKey("beamLength") ? nbt.getFloat("beamLength") : 10.0f; - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.3f; - this.beamHeight = nbt.hasKey("beamHeight") ? nbt.getFloat("beamHeight") : 0.5f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 5.0f; - this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 5; - this.piercing = !nbt.hasKey("piercing") || nbt.getBoolean("piercing"); - this.sweepSpeed = nbt.hasKey("sweepSpeed") ? nbt.getFloat("sweepSpeed") : 3.0f; - this.numberOfRotations = nbt.hasKey("numberOfRotations") ? nbt.getInteger("numberOfRotations") : 2; - this.lockOnTarget = nbt.hasKey("lockOnTarget") && nbt.getBoolean("lockOnTarget"); + this.beamLength = nbt.getFloat("beamLength"); + this.beamWidth = nbt.getFloat("beamWidth"); + this.beamHeight = nbt.getFloat("beamHeight"); + this.damage = nbt.getFloat("damage"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.piercing = nbt.getBoolean("piercing"); + this.sweepSpeed = nbt.getFloat("sweepSpeed"); + this.numberOfRotations = nbt.getInteger("numberOfRotations"); + this.lockOnTarget = nbt.getBoolean("lockOnTarget"); colorData.readNBT(nbt); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index 29eb73832..d9e05c382 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -430,24 +430,20 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { @Override public void readTypeNBT(NBTTagCompound nbt) { - if (nbt.hasKey("mode")) { - try { - this.mode = TeleportMode.valueOf(nbt.getString("mode")); - } catch (Exception e) { - this.mode = TeleportMode.BLINK; - } - } else { + try { + this.mode = TeleportMode.valueOf(nbt.getString("mode")); + } catch (Exception e) { this.mode = TeleportMode.BLINK; } - this.blinkCount = nbt.hasKey("blinkCount") ? nbt.getInteger("blinkCount") : 3; - this.blinkDelayTicks = nbt.hasKey("blinkDelayTicks") ? nbt.getInteger("blinkDelayTicks") : 10; - this.blinkRadius = nbt.hasKey("blinkRadius") ? nbt.getFloat("blinkRadius") : 8.0f; - this.behindDistance = nbt.hasKey("behindDistance") ? nbt.getFloat("behindDistance") : 2.0f; - this.requireLineOfSight = !nbt.hasKey("requireLineOfSight") || nbt.getBoolean("requireLineOfSight"); - this.damageAtStart = nbt.hasKey("damageAtStart") && nbt.getBoolean("damageAtStart"); - this.damageAtEnd = nbt.hasKey("damageAtEnd") && nbt.getBoolean("damageAtEnd"); - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 5.0f; - this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 2.0f; + this.blinkCount = nbt.getInteger("blinkCount"); + this.blinkDelayTicks = nbt.getInteger("blinkDelayTicks"); + this.blinkRadius = nbt.getFloat("blinkRadius"); + this.behindDistance = nbt.getFloat("behindDistance"); + this.requireLineOfSight = nbt.getBoolean("requireLineOfSight"); + this.damageAtStart = nbt.getBoolean("damageAtStart"); + this.damageAtEnd = nbt.getBoolean("damageAtEnd"); + this.damage = nbt.getFloat("damage"); + this.damageRadius = nbt.getFloat("damageRadius"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index b35891d9a..84bafc726 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -119,14 +119,14 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { @Override public void readTypeNBT(NBTTagCompound nbt) { readZoneNBT(nbt, 300); - this.triggerRadius = nbt.hasKey("triggerRadius") ? nbt.getFloat("triggerRadius") : 2.0f; - this.armTime = nbt.hasKey("armTime") ? nbt.getInteger("armTime") : 20; - this.maxTriggers = nbt.hasKey("maxTriggers") ? nbt.getInteger("maxTriggers") : 1; - this.triggerCooldown = nbt.hasKey("triggerCooldown") ? nbt.getInteger("triggerCooldown") : 20; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 6.0f; - this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 0.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; - this.visible = !nbt.hasKey("visible") || nbt.getBoolean("visible"); + this.triggerRadius = nbt.getFloat("triggerRadius"); + this.armTime = nbt.getInteger("armTime"); + 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"); } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index 90aaf054b..d9d253d29 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -236,14 +236,14 @@ public class AbilityVortex extends Ability implements IAbilityVortex { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.pullRadius = nbt.hasKey("pullRadius") ? nbt.getFloat("pullRadius") : 8.0f; - this.pullStrength = nbt.hasKey("pullStrength") ? nbt.getFloat("pullStrength") : 0.8f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 0.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.0f; - this.aoe = nbt.hasKey("aoe") && nbt.getBoolean("aoe"); - this.maxTargets = nbt.hasKey("maxTargets") ? nbt.getInteger("maxTargets") : 5; - this.damageOnPull = nbt.hasKey("damageOnPull") && nbt.getBoolean("damageOnPull"); - this.pullDamage = nbt.hasKey("pullDamage") ? nbt.getFloat("pullDamage") : 0.0f; + this.pullRadius = nbt.getFloat("pullRadius"); + this.pullStrength = nbt.getFloat("pullStrength"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.aoe = nbt.getBoolean("aoe"); + this.maxTargets = nbt.getInteger("maxTargets"); + this.damageOnPull = nbt.getBoolean("damageOnPull"); + this.pullDamage = nbt.getFloat("pullDamage"); } // Getters & Setters 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 8a15c2ce5..9a296e836 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 @@ -15,6 +15,7 @@ import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion; import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumPotionType; import net.minecraft.util.DamageSource; import net.minecraft.world.World; @@ -255,7 +256,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 1; particleGlow = true; particleDir = "mc:mobSpell"; colorData.innerColor = 0x44DD44; colorData.outerColor = 0x116611; windUpColor = 0x6044DD44; activeColor = 0xC044FF44; - effects.add(new AbilityEffect(AbilityEffect.EffectType.POISON, 100, 0)); + effects.add(new AbilityEffect(EnumPotionType.Poison, 100, 0)); break; case "INFERNO": groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; @@ -264,7 +265,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 0; particleGlow = true; particleDir = "mc:flame"; colorData.innerColor = 0xFF6611; colorData.outerColor = 0xCC2200; windUpColor = 0x60FF6611; activeColor = 0xC0FF4400; - effects.add(new AbilityEffect(AbilityEffect.EffectType.BURN, 60, 0)); + effects.add(new AbilityEffect(EnumPotionType.Fire, 60, 0)); break; case "ARCANE": groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; @@ -273,7 +274,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 1; particleGlow = true; particleDir = "mc:portal"; colorData.innerColor = 0xAA44FF; colorData.outerColor = 0x6622BB; windUpColor = 0x60AA44FF; activeColor = 0xC0CC66FF; - effects.add(new AbilityEffect(AbilityEffect.EffectType.WEAKNESS, 100, 0)); + effects.add(new AbilityEffect(EnumPotionType.Weakness, 100, 0)); break; case "ELECTRIC": groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; @@ -282,7 +283,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 2; particleGlow = true; particleDir = "mc:enchantmenttable"; colorData.innerColor = 0x4488FF; colorData.outerColor = 0x2244BB; windUpColor = 0x604488FF; activeColor = 0xC066AAFF; - effects.add(new AbilityEffect(AbilityEffect.EffectType.MINING_FATIGUE, 80, 1)); + effects.add(new AbilityEffect(EnumPotionType.MiningFatigue, 80, 1)); break; case "FROST": groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; @@ -291,7 +292,7 @@ public abstract class AbilityZone extends Ability { particleMotion = 1; particleGlow = true; particleDir = "mc:snowshovel"; colorData.innerColor = 0x88CCFF; colorData.outerColor = 0x4488CC; windUpColor = 0x6088CCFF; activeColor = 0xC0AADDFF; - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 100, 1)); + effects.add(new AbilityEffect(EnumPotionType.Slowness, 100, 1)); break; case "DEFAULT": groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; @@ -354,37 +355,33 @@ public abstract class AbilityZone extends Ability { } protected void readZoneNBT(NBTTagCompound nbt, int defaultDuration) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : defaultDuration; - if (nbt.hasKey("zoneShape")) { - try { this.zoneShape = ZoneShape.valueOf(nbt.getString("zoneShape")); } - catch (Exception e) { this.zoneShape = ZoneShape.CIRCLE; } - } else { - this.zoneShape = ZoneShape.CIRCLE; - } - this.spawnRadius = nbt.hasKey("spawnRadius") ? nbt.getFloat("spawnRadius") : 10.0f; - this.zoneCount = nbt.hasKey("zoneCount") ? nbt.getInteger("zoneCount") : 3; - 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.durationTicks = nbt.getInteger("durationTicks"); + try { this.zoneShape = ZoneShape.valueOf(nbt.getString("zoneShape")); } + catch (Exception e) { this.zoneShape = ZoneShape.CIRCLE; } + this.spawnRadius = nbt.getFloat("spawnRadius"); + this.zoneCount = nbt.getInteger("zoneCount"); + this.zoneHeight = nbt.getFloat("zoneHeight"); + this.particleDensity = nbt.getFloat("particleDensity"); + this.particleScale = nbt.getFloat("particleScale"); + this.animSpeed = nbt.getFloat("animSpeed"); + this.lightningDensity = nbt.getFloat("lightningDensity"); colorData.readNBT(nbt); // Visual layer fields - this.groundFill = !nbt.hasKey("groundFill") || nbt.getBoolean("groundFill"); - this.groundAlpha = nbt.hasKey("groundAlpha") ? nbt.getFloat("groundAlpha") : 0.25f; - this.rings = !nbt.hasKey("rings") || nbt.getBoolean("rings"); - this.ringCount = nbt.hasKey("ringCount") ? nbt.getInteger("ringCount") : 3; - this.border = !nbt.hasKey("border") || nbt.getBoolean("border"); - this.borderSpeed = nbt.hasKey("borderSpeed") ? nbt.getFloat("borderSpeed") : 1.0f; - this.accents = !nbt.hasKey("accents") || nbt.getBoolean("accents"); - this.accentStyle = nbt.hasKey("accentStyle") ? nbt.getInteger("accentStyle") : 0; - this.lightning = nbt.hasKey("lightning") && nbt.getBoolean("lightning"); - this.particles = !nbt.hasKey("particles") || nbt.getBoolean("particles"); - this.particleMotion = nbt.hasKey("particleMotion") ? nbt.getInteger("particleMotion") : 0; - this.particleDir = nbt.hasKey("particleDir") ? nbt.getString("particleDir") : ""; - this.particleSize = nbt.hasKey("particleSize") ? nbt.getInteger("particleSize") : 32; - this.particleGlow = !nbt.hasKey("particleGlow") || nbt.getBoolean("particleGlow"); + 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"); } // ═════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/DataStats.java b/src/main/java/noppes/npcs/DataStats.java index 0d085d823..7db32bc66 100644 --- a/src/main/java/noppes/npcs/DataStats.java +++ b/src/main/java/noppes/npcs/DataStats.java @@ -20,6 +20,7 @@ public class DataStats { public EnumPotionType potionType = EnumPotionType.None; public int potionDuration = 5; //20 = 1 second public int potionAmp = 0; + public int potionManualId = 0; public double maxHealth = 20; public int respawnTime = 20; @@ -45,6 +46,7 @@ public class DataStats { public boolean pPhysics = true, pXlr8 = false, pGlows = false, pExplode = false; public boolean pRender3D = false, pSpin = false, pStick = false, pBurnItem = false; public EnumPotionType pEffect = EnumPotionType.None; + public int pManualId = 0; public EnumParticleType pTrail = EnumParticleType.None; public ScriptParticle pCustom = new ScriptParticle(""); public int pEffAmp = 0; @@ -88,6 +90,8 @@ public class DataStats { compound.setInteger("PotionEffect", potionType.ordinal()); compound.setInteger("PotionDuration", potionDuration); compound.setInteger("PotionAmp", potionAmp); + if (potionType == EnumPotionType.Manual) + compound.setInteger("PotionManualId", potionManualId); compound.setInteger("MaxFiringRange", rangedRange); compound.setInteger("FireRate", fireRate); @@ -122,6 +126,8 @@ public class DataStats { compound.setTag("pCustom", pCustom.writeToNBT()); if (pEffect == EnumPotionType.Fire) compound.setBoolean("pBurnItem", pBurnItem); + if (pEffect == EnumPotionType.Manual) + compound.setInteger("pManualId", pManualId); compound.setBoolean("ImmuneToFire", immuneToFire); compound.setBoolean("PotionImmune", potionImmune); @@ -145,7 +151,7 @@ public class DataStats { aggroRange = compound.getInteger("AggroRange"); respawnTime = compound.getInteger("RespawnTime"); spawnCycle = compound.getInteger("SpawnCycle"); - creatureType = EnumCreatureAttribute.values()[compound.getInteger("CreatureType") % EnumPotionType.values().length]; + creatureType = EnumCreatureAttribute.values()[compound.getInteger("CreatureType") % EnumCreatureAttribute.values().length]; ignoreCobweb = compound.getBoolean("IgnoreCobweb"); healthRegen = compound.getFloat("HealthRegen"); combatRegen = compound.getFloat("CombatRegen"); @@ -155,9 +161,11 @@ public class DataStats { swingWarmUp = ValueUtil.clamp(compound.getInteger("SwingWarmup"), 0, 1000); attackRange = compound.getInteger("AttackRange"); knockback = compound.getInteger("KnockBack"); - potionType = EnumPotionType.values()[compound.getInteger("PotionEffect") % EnumPotionType.values().length]; + potionType = EnumPotionType.fromOrdinal(compound.getInteger("PotionEffect")); potionDuration = compound.getInteger("PotionDuration"); potionAmp = compound.getInteger("PotionAmp"); + if (potionType == EnumPotionType.Manual) + potionManualId = compound.getInteger("PotionManualId"); rangedRange = compound.getInteger("MaxFiringRange"); fireRate = compound.getInteger("FireRate"); @@ -180,7 +188,7 @@ public class DataStats { pRender3D = compound.getBoolean("pRender3D"); pSpin = compound.getBoolean("pSpin"); pStick = compound.getBoolean("pStick"); - pEffect = EnumPotionType.values()[compound.getInteger("pEffect") % EnumPotionType.values().length]; + pEffect = EnumPotionType.fromOrdinal(compound.getInteger("pEffect")); pTrail = EnumParticleType.values()[compound.getInteger("pTrail") % EnumParticleType.values().length]; pEffAmp = compound.getInteger("pEffAmp"); fireSound = compound.getString("FiringSound"); @@ -195,6 +203,8 @@ public class DataStats { pCustom = ScriptParticle.fromNBT(compound.getCompoundTag("pCustom")); if (pEffect == EnumPotionType.Fire) pBurnItem = compound.getBoolean("pBurnItem"); + if (pEffect == EnumPotionType.Manual) + pManualId = compound.getInteger("pManualId"); immuneToFire = compound.getBoolean("ImmuneToFire"); potionImmune = compound.getBoolean("PotionImmune"); diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java index a128d3760..36cbfff37 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java @@ -12,7 +12,6 @@ import noppes.npcs.constants.EnumPotionType; public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfieldListener { private DataStats stats; - private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"}; public SubGuiNpcMeleeProperties(DataStats stats) { this.stats = stats; @@ -42,18 +41,28 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi getTextField(4).integersOnly = true; getTextField(4).setMinMaxDefault(0, Integer.MAX_VALUE, 0); addLabel(new GuiNpcLabel(5, "stats.meleeeffect", guiLeft + 5, guiTop + 135)); - addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, potionNames, stats.potionType.ordinal())); + addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, EnumPotionType.getLangKeys(), stats.potionType.ordinal())); + if (stats.potionType == EnumPotionType.Manual) { + addLabel(new GuiNpcLabel(8, "effect.potionid", guiLeft + 198, guiTop + 119)); + addTextField(new GuiNpcTextField(8, this, fontRendererObj, guiLeft + 200, guiTop + 132, 40, 18, stats.potionManualId + "")); + getTextField(8).integersOnly = true; + getTextField(8).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + } + + int y = guiTop + 160; if (stats.potionType != EnumPotionType.None) { - addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, guiTop + 165)); - addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, guiTop + 160, 40, 18, stats.potionDuration + "")); + addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, y + 5)); + addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, y, 40, 18, stats.potionDuration + "")); getTextField(6).integersOnly = true; getTextField(6).setMinMaxDefault(1, Integer.MAX_VALUE, 5); if (stats.potionType != EnumPotionType.Fire) { - addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, guiTop + 195)); - addButton(new GuiButtonBiDirectional(7, guiLeft + 85, guiTop + 190, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp)); + y += 30; + addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, y + 5)); + addButton(new GuiButtonBiDirectional(7, guiLeft + 85, y, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp)); } } - addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + 190, 60, 20, "gui.done")); + + addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + ySize - 26, 60, 20, "gui.done")); } public void unFocused(GuiNpcTextField textfield) { @@ -67,13 +76,15 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi stats.knockback = textfield.getInteger(); } else if (textfield.id == 6) { stats.potionDuration = textfield.getInteger(); + } else if (textfield.id == 8) { + stats.potionManualId = textfield.getInteger(); } } protected void actionPerformed(GuiButton guibutton) { GuiNpcButton button = (GuiNpcButton) guibutton; if (button.id == 5) { - stats.potionType = EnumPotionType.values()[button.getValue()]; + stats.potionType = EnumPotionType.fromOrdinal(button.getValue()); initGui(); } if (button.id == 7) { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java index 8acb8fc8c..e0806a538 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java @@ -15,7 +15,6 @@ import noppes.npcs.constants.EnumPotionType; public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { private DataStats stats; - private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"}; private String[] trailNames = new String[]{"gui.none", "trail.smoke", "trail.portal", "trail.redstone", "trail.lightning", "trail.largesmoke", "trail.magic", "trail.enchant", "trail.crit", "trail.explode", "trail.music", "trail.flame", "trail.lava", "trail.splash", @@ -76,22 +75,29 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL } addLabel(new GuiNpcLabel(7, "stats.rangedeffect", guiLeft + 210, y + 5)); - addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, potionNames, stats.pEffect.ordinal())); + addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, EnumPotionType.getLangKeys(), stats.pEffect.ordinal())); if (stats.pEffect != EnumPotionType.None) { int internalY = y + 30; + if (stats.pEffect == EnumPotionType.Manual) { + addLabel(new GuiNpcLabel(110, "effect.potionid", guiLeft + 210, internalY + 5)); + addTextField(new GuiNpcTextField(11, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pManualId + "")); + getTextField(11).integersOnly = true; + getTextField(11).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + internalY += 30; + } addLabel(new GuiNpcLabel(50, "gui.time", guiLeft + 210, internalY + 5)); addTextField(new GuiNpcTextField(5, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pDur + "")); getTextField(5).integersOnly = true; getTextField(5).setMinMaxDefault(1, Integer.MAX_VALUE, 5); - if (stats.pEffect != EnumPotionType.Fire) { - internalY += 30; - addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5)); - addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp)); - } else { + if (stats.pEffect == EnumPotionType.Fire) { internalY += 30; addLabel(new GuiNpcLabel(100, "stats.burnItem", guiLeft + 210, internalY + 5)); addButton(new GuiNpcButtonYesNo(100, guiLeft + 330, internalY, 52, 20, stats.pBurnItem)); + } else { + internalY += 30; + addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5)); + addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp)); } } @@ -126,6 +132,8 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pSpeed = textfield.getInteger(); } else if (textfield.id == 5) { stats.pDur = textfield.getInteger(); + } else if (textfield.id == 11) { + stats.pManualId = textfield.getInteger(); } } @@ -146,7 +154,7 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pArea = button.getValue(); } if (button.id == 4) { - stats.pEffect = EnumPotionType.values()[button.getValue()]; + stats.pEffect = EnumPotionType.fromOrdinal(button.getValue()); initGui(); } if (button.id == 5) { diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java index cf9143c66..f8cddbf72 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -440,8 +440,7 @@ public abstract class GuiNPCInterface extends GuiScreen { int bottomHeight = 0; int bottomTextureV = 0; if (ySize < bgTextureHeight) { - // Keep bottom border from texture bottom (last 6 pixels of actual content) - bottomHeight = 6; + bottomHeight = -1; topHeight = ySize - bottomHeight; bottomTextureV = bgTextureHeight - bottomHeight; } diff --git a/src/main/java/noppes/npcs/constants/EnumPotionType.java b/src/main/java/noppes/npcs/constants/EnumPotionType.java index f6d5ad111..4cf6bc8f8 100644 --- a/src/main/java/noppes/npcs/constants/EnumPotionType.java +++ b/src/main/java/noppes/npcs/constants/EnumPotionType.java @@ -1,5 +1,83 @@ package noppes.npcs.constants; +import net.minecraft.potion.Potion; + public enum EnumPotionType { - None, Fire, Poison, Hunger, Weakness, Slowness, Nausea, Blindness, Wither; + None("gui.none", -1), + Fire("tile.fire.name", -1), + Poison("potion.poison", Potion.poison.id), + Hunger("potion.hunger", Potion.hunger.id), + Weakness("potion.weakness", Potion.weakness.id), + Slowness("potion.moveSlowdown", Potion.moveSlowdown.id), + Nausea("potion.confusion", Potion.confusion.id), + Blindness("potion.blindness", Potion.blindness.id), + Wither("potion.wither", Potion.wither.id), + MiningFatigue("potion.digSlowDown", Potion.digSlowdown.id), + Manual("effect.manual", -1); + + private final String langKey; + private final int potionId; + + EnumPotionType(String langKey, int potionId) { + this.langKey = langKey; + this.potionId = potionId; + } + + public String getLangKey() { + return langKey; + } + + public int getPotionId() { + return potionId; + } + + /** + * Returns the actual potion ID to apply. + * For Manual type, returns the provided manualId. + * For all others, returns the mapped potionId. + */ + public int getResolvedPotionId(int manualId) { + if (this == Manual) return manualId; + return potionId; + } + + public static String[] getLangKeys() { + EnumPotionType[] types = values(); + String[] keys = new String[types.length]; + for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; + return keys; + } + + /** + * Returns lang keys excluding None. For use in effect lists where None is not a valid choice. + */ + public static String[] getLangKeysNoNone() { + EnumPotionType[] types = values(); + String[] keys = new String[types.length - 1]; + for (int i = 1; i < types.length; i++) keys[i - 1] = types[i].langKey; + return keys; + } + + /** + * Maps a 0-based index (excluding None) back to the corresponding EnumPotionType. + * Index 0 = Fire, 1 = Poison, etc. + */ + public static EnumPotionType fromIndexNoNone(int index) { + return fromOrdinal(index + 1); + } + + public static EnumPotionType fromOrdinal(int ordinal) { + EnumPotionType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return None; + } + + /** + * Checks if the given potion ID is valid and registered in the Minecraft potion registry. + */ + public static boolean isValidPotionId(int id) { + return id >= 0 && id < Potion.potionTypes.length && Potion.potionTypes[id] != null; + } } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 6e4b40884..187ce583d 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -384,11 +384,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti } } - if (stats.potionType != EnumPotionType.None) { - if (stats.potionType != EnumPotionType.Fire) - ((EntityLivingBase) receiver).addPotionEffect(new PotionEffect(this.getPotionEffect(stats.potionType), stats.potionDuration * 20, stats.potionAmp)); - else - receiver.setFire(stats.potionDuration); + if (stats.potionType == EnumPotionType.Fire) { + receiver.setFire(stats.potionDuration); + } else if (stats.potionType != EnumPotionType.None) { + int potionId = stats.potionType.getResolvedPotionId(stats.potionManualId); + if (EnumPotionType.isValidPotionId(potionId)) { + ((EntityLivingBase) receiver).addPotionEffect(new PotionEffect(potionId, stats.potionDuration * 20, stats.potionAmp)); + } } return didAttack; } @@ -1043,29 +1045,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti return weight; } - /* - * Used for getting the applied potion effect from dataStats. - */ - private int getPotionEffect(EnumPotionType p) { - switch (p) { - case Poison: - return Potion.poison.id; - case Hunger: - return Potion.hunger.id; - case Weakness: - return Potion.weakness.id; - case Slowness: - return Potion.moveSlowdown.id; - case Nausea: - return Potion.confusion.id; - case Blindness: - return Potion.blindness.id; - case Wither: - return Potion.wither.id; - default: - return 0; - } - } @Override public void setAir(int air) { diff --git a/src/main/java/noppes/npcs/entity/EntityProjectile.java b/src/main/java/noppes/npcs/entity/EntityProjectile.java index e25a66083..5d322ade8 100644 --- a/src/main/java/noppes/npcs/entity/EntityProjectile.java +++ b/src/main/java/noppes/npcs/entity/EntityProjectile.java @@ -94,6 +94,7 @@ public class EntityProjectile extends EntityThrowable { public boolean destroyTerrain = true; public int explosiveRadius = 0; public EnumPotionType effect = EnumPotionType.None; + public int manualPotionId = 0; public boolean burnItem = true; public int duration = 5; public int amplify = 0; @@ -508,12 +509,12 @@ public class EntityProjectile extends EntityThrowable { } } - if (this.effect != EnumPotionType.None && entityliving != null) { - if (this.effect != EnumPotionType.Fire) { - int p = this.getPotionEffect(effect); - entityliving.addPotionEffect(new PotionEffect(p, this.duration * 20, this.amplify)); - } else { - movingobjectposition.entityHit.setFire(duration); + if (this.effect == EnumPotionType.Fire && entityliving != null) { + movingobjectposition.entityHit.setFire(duration); + } else if (this.effect != EnumPotionType.None && entityliving != null) { + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { + entityliving.addPotionEffect(new PotionEffect(potionId, this.duration * 20, this.amplify)); } } } else if (this.hasGravity() && (this.isArrow() || this.sticksToWalls())) { @@ -637,21 +638,23 @@ public class EntityProjectile extends EntityThrowable { d1 = 1.0D; } - int i = this.getPotionEffect(effect); + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); - if (Potion.potionTypes[i].isInstant()) { - Potion.potionTypes[i].affectEntity(this.getThrower(), entitylivingbase, this.amplify, d1); - } else { - int j = (int) (d1 * (double) this.duration + 0.5D); + if (EnumPotionType.isValidPotionId(potionId)) { + if (Potion.potionTypes[potionId].isInstant()) { + Potion.potionTypes[potionId].affectEntity(this.getThrower(), entitylivingbase, this.amplify, d1); + } else { + int j = (int) (d1 * (double) this.duration + 0.5D); - if (j > 20) { - entitylivingbase.addPotionEffect(new PotionEffect(i, j, this.amplify)); + if (j > 20) { + entitylivingbase.addPotionEffect(new PotionEffect(potionId, j, this.amplify)); + } } } } } } - this.worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), this.getPotionColor(this.effect)); + this.worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), this.getPotionColor()); } } @@ -693,6 +696,8 @@ public class EntityProjectile extends EntityThrowable { par1NBTTagCompound.setBoolean("explosive", explosive); par1NBTTagCompound.setInteger("accuracy", accuracy); par1NBTTagCompound.setInteger("PotionEffect", effect.ordinal()); + if (effect == EnumPotionType.Manual) + par1NBTTagCompound.setInteger("PotionManualId", manualPotionId); par1NBTTagCompound.setString("trail", this.dataWatcher.getWatchableObjectString(22)); par1NBTTagCompound.setByte("Render3D", this.dataWatcher.getWatchableObjectByte(28)); par1NBTTagCompound.setByte("Spins", this.dataWatcher.getWatchableObjectByte(29)); @@ -723,7 +728,9 @@ public class EntityProjectile extends EntityThrowable { this.accelerate = par1NBTTagCompound.getBoolean("accelerate"); this.explosive = par1NBTTagCompound.getBoolean("explosive"); this.accuracy = par1NBTTagCompound.getInteger("accuracy"); - this.effect = EnumPotionType.values()[par1NBTTagCompound.getInteger("PotionEffect") % EnumPotionType.values().length]; + this.effect = EnumPotionType.fromOrdinal(par1NBTTagCompound.getInteger("PotionEffect")); + if (effect == EnumPotionType.Manual) + this.manualPotionId = par1NBTTagCompound.getInteger("PotionManualId"); this.dataWatcher.updateObject(22, par1NBTTagCompound.getString("trail")); this.dataWatcher.updateObject(23, Integer.valueOf(par1NBTTagCompound.getInteger("size"))); this.dataWatcher.updateObject(24, Byte.valueOf((byte) (par1NBTTagCompound.getBoolean("glows") ? 1 : 0))); @@ -774,46 +781,12 @@ public class EntityProjectile extends EntityThrowable { return this.thrower; } - private int getPotionEffect(EnumPotionType p) { - switch (p) { - case Poison: - return Potion.poison.id; - case Hunger: - return Potion.hunger.id; - case Weakness: - return Potion.weakness.id; - case Slowness: - return Potion.moveSlowdown.id; - case Nausea: - return Potion.confusion.id; - case Blindness: - return Potion.blindness.id; - case Wither: - return Potion.wither.id; - default: - return 0; - } - } - - private int getPotionColor(EnumPotionType p) { - switch (p) { - case Poison: - return 32660; - case Hunger: - return 32660; - case Weakness: - return 32696; - case Slowness: - return 32698; - case Nausea: - return 32732; - case Blindness: - return Potion.blindness.id; - case Wither: - return 32732; - default: - return 0; + private int getPotionColor() { + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { + return Potion.potionTypes[potionId].getLiquidColor(); } + return 0; } public void getStatProperties(DataStats stats) { @@ -823,6 +796,7 @@ public class EntityProjectile extends EntityThrowable { this.explosive = stats.pExplode; this.explosiveRadius = stats.pArea; this.effect = stats.pEffect; + this.manualPotionId = stats.pManualId; this.burnItem = stats.pBurnItem; this.duration = stats.pDur; this.amplify = stats.pEffAmp; diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 3e8fa323a..a29759c31 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2007,6 +2007,8 @@ condition.hover.threshold=Health percentage threshold (1-99%) effect.hover.type=Potion effect type to apply to targets effect.hover.duration=Effect duration in ticks (20 ticks = 1 second) effect.hover.amplifier=Effect strength level (higher = stronger) +effect.manual=Manual +effect.potionid=Potion ID # ========================================= # Auction House From 41d336120903dc64a6dee17c63bef72f3c052b1c Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 14 Feb 2026 11:26:02 -0300 Subject: [PATCH 48/76] Added dazed animation --- .../animations/Ability_Generic_Dazed.json | 770 ++++++++++++++++++ 1 file changed, 770 insertions(+) create mode 100644 src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json b/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json new file mode 100644 index 000000000..38e42bd1e --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json @@ -0,0 +1,770 @@ +{ + "Loop": 11, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 20 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 8 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 11, + "Smooth": 0b, + "ID": 100, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Generic_Dazed", + "WhileStanding": 1b +} From e1eda3ce194fd0bf90aaca042380eaff8c0c2a1f Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 14 Feb 2026 16:22:53 -0300 Subject: [PATCH 49/76] Added an option to register multiple animations under one common name --- src/main/java/kamkeel/npcs/util/Register.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index 5a64fca6a..e1cbfaf79 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -103,6 +103,16 @@ public class Register { return super.register(factoryName, factory); } + public Animation[] registerBundle(String factoryName, Supplier factory, String... appendixes) { + List animations = new ArrayList<>(); + for (String appendix : appendixes) { + entries.put(registryKey + "." + namespace + "." + factoryName + "_" + appendix, factory); + animations.add(factory.get()); + } + + return animations.toArray(new Animation[0]); + } + public void register() { try { String path = "/assets/" + namespace + "/" + animationsPath; From da4ee2e20d14c88069ac8f6d0c7bdff42fc678c0 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 14 Feb 2026 14:43:25 -0500 Subject: [PATCH 50/76] Refactor ability management: enhance deep copy functionality, streamline custom ability handling, and update versioning logic --- .../controllers/data/ability/Ability.java | 6 +- .../data/ability/AbilityController.java | 550 +++++++----------- .../controllers/data/ability/AbilitySlot.java | 2 +- 3 files changed, 211 insertions(+), 347 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 2a4f39b8f..f8f620474 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -1139,7 +1139,7 @@ public abstract class Ability implements IAbility { nbt.setBoolean("showTelegraph", showTelegraph); nbt.setString("telegraphType", telegraphType.name()); nbt.setFloat("telegraphHeightOffset", telegraphHeightOffset); - nbt.setTag("customData", customData); + nbt.setTag("customData", (NBTTagCompound) customData.copy()); nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); @@ -1264,6 +1264,10 @@ public abstract class Ability implements IAbility { return false; } + public Ability deepCopy() { + return AbilityController.Instance.fromNBT(this.writeNBT()); + } + public boolean isNpcInlineEdit() { return npcInlineEdit; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 01ddb7b58..b65276211 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -12,43 +12,21 @@ import java.io.File; import java.util.*; import java.util.function.Supplier; -/** - * Central controller for ability types and presets. - *

- * Three maps: - *

    - *
  • {@code typeFactories} — keyed by typeId (lang key), creates new instances of each ability type
  • - *
  • {@code abilities} — built-in pre-configured abilities, keyed by unique name
  • - *
  • {@code customAbilities} — user-created presets, keyed by UUID
  • - *
- */ public class AbilityController implements IAbilityHandler { public static AbilityController Instance = new AbilityController(); - /** Type factories keyed by typeId (lang key, e.g. "ability.cnpc.slam"). */ - private final Map> typeFactories = new LinkedHashMap<>(); - - /** Built-in pre-configured abilities keyed by unique name. */ - private final Map abilities = new LinkedHashMap<>(); - - /** User-created custom ability presets keyed by UUID. */ + // ── Core Registries ────────────────────────────────────────────────────── + private final Map> abilityTypes = new LinkedHashMap<>(); + private final Map builtAbilities = new LinkedHashMap<>(); private final Map customAbilities = new LinkedHashMap<>(); - /** Version counter — incremented on any custom ability add/modify/delete. - * Used by AbilitySlot for cache invalidation. */ - private int version = 0; - - /** External damage handler (e.g., DBC Addon). */ + // ── Extension Points ───────────────────────────────────────────────────── + private final Map> externalVariants = new LinkedHashMap<>(); + private final List fieldProviders = new ArrayList<>(); private IAbilityDamageHandler damageHandler = null; - /** External field providers for ability GUI (e.g., DBC Addon). Client-side only. */ - private final List fieldProviders = new ArrayList<>(); - - /** External variant definitions registered by addons, keyed by typeId. */ - private final Map> externalVariants = new LinkedHashMap<>(); - - /** TypeIds that produce BuiltInAbility instances (non-editable in GUI). */ + // ── Derived State ──────────────────────────────────────────────────────── private final Set builtInTypeIds = new HashSet<>(); public AbilityController() { @@ -56,54 +34,135 @@ public class AbilityController implements IAbilityHandler { } // ═══════════════════════════════════════════════════════════════════════════ - // LOADING / SAVING CUSTOM ABILITIES + // TYPE REGISTRATION // ═══════════════════════════════════════════════════════════════════════════ - /** - * Load custom ability presets from world directory. - * Called when world loads. Files are named {@code .json}. - */ - public void load() { - customAbilities.clear(); - File dir = getDir(); - if (!dir.exists()) { - return; + public void registerType(String factoryKey, Supplier factory) { + Ability temp = factory.get(); + String typeId = temp.getTypeId(); + if (abilityTypes.containsKey(typeId)) { + LogWriter.info("AbilityController: Overwriting type: " + typeId); + } + abilityTypes.put(typeId, factory); + if (temp.isBuiltIn()) { + builtInTypeIds.add(typeId); + } + } + + public Ability create(String typeId) { + Supplier factory = abilityTypes.get(typeId); + return factory != null ? factory.get() : null; + } + + public Ability fromNBT(NBTTagCompound nbt) { + if (nbt == null || !nbt.hasKey("typeId")) { + return null; } - File[] files = dir.listFiles(); - if (files == null) return; + String typeId = nbt.getString("typeId"); + Supplier factory = abilityTypes.get(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown ability type: " + typeId); + return null; + } - for (File file : files) { - if (!file.isFile() || !file.getName().endsWith(".json")) continue; - try { - String filename = file.getName(); - String uuid = filename.substring(0, filename.length() - 5); // strip .json + Ability ability = factory.get(); + ability.readNBT(nbt); + return ability; + } - NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); - Ability ability = fromNBT(nbt); - if (ability != null) { - ability.setId(uuid); - customAbilities.put(uuid, ability); - } - } catch (Exception e) { - LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e); + private void registerBuiltinTypes() { + registerType("cnpc:slam", AbilitySlam::new); + registerType("cnpc:heavy_hit", AbilityHeavyHit::new); + registerType("cnpc:cutter", AbilityCutter::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:charge", AbilityCharge::new); + registerType("cnpc:dash", AbilityDash::new); + registerType("cnpc:teleport", AbilityTeleport::new); + registerType("cnpc:vortex", AbilityVortex::new); + registerType("cnpc:shockwave", AbilityShockwave::new); + + registerType("cnpc:guard", AbilityGuard::new); + registerType("cnpc:heal", AbilityHeal::new); + + registerType("cnpc:hazard", AbilityHazard::new); + registerType("cnpc:trap", AbilityTrap::new); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // BUILT-IN ABILITIES + // ═══════════════════════════════════════════════════════════════════════════ + + public void registerAbility(String name, Ability ability) { + if (builtAbilities.containsKey(name)) { + LogWriter.info("AbilityController: Overwriting built-in ability: " + name); + } + if (!ability.isBuiltIn()) { + ability.setName(name); + } + builtAbilities.put(name, ability); + LogWriter.info("Registered ability: " + name); + } + + public Ability getAbility(String name) { + return builtAbilities.get(name); + } + + public Ability getAbilityByDisplayName(String displayName) { + for (Ability ability : builtAbilities.values()) { + if (ability.getName().equals(displayName)) { + return ability; } } + return null; + } + + public Set getAbilityNames() { + return new LinkedHashSet<>(builtAbilities.keySet()); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CUSTOM ABILITIES + // ═══════════════════════════════════════════════════════════════════════════ + + // Incremented on any custom ability change; used by AbilitySlot for cache invalidation + private int customAbilityRevision = 0; + + public void load() { + customAbilities.clear(); + + File dir = getDir(); + File[] files = dir.exists() ? dir.listFiles() : null; + if (files != null) { + for (File file : files) { + if (!file.isFile() || !file.getName().endsWith(".json")) continue; + try { + String filename = file.getName(); + String uuid = filename.substring(0, filename.length() - 5); + + NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); + Ability ability = fromNBT(nbt); + if (ability != null) { + ability.setId(uuid); + customAbilities.put(uuid, ability); + } + } catch (Exception e) { + LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e); + } + } + } + + customAbilityRevision++; LogWriter.info("Loaded " + customAbilities.size() + " custom abilities"); } - private File getDir() { - File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities"); - if (!dir.exists()) { - dir.mkdirs(); - } - return dir; - } - - /** - * Save a custom ability preset. If the ability has no id, generates a UUID. - * Stores in customAbilities map and writes to disk. - */ public boolean saveCustomAbility(Ability ability) { if (ability == null) return false; @@ -130,7 +189,7 @@ public class AbilityController implements IAbilityHandler { } customAbilities.put(uuid, ability); - version++; + customAbilityRevision++; LogWriter.info("Saved custom ability: " + ability.getName() + " [" + uuid + "]"); SyncController.syncAllCustomAbilities(); return true; @@ -140,9 +199,6 @@ public class AbilityController implements IAbilityHandler { } } - /** - * Delete a custom ability preset by UUID. - */ public boolean deleteCustomAbility(String uuid) { if (uuid == null || uuid.isEmpty()) return false; @@ -155,110 +211,105 @@ public class AbilityController implements IAbilityHandler { file.delete(); } - version++; + customAbilityRevision++; LogWriter.info("Deleted custom ability: " + uuid); SyncController.syncAllCustomAbilities(); return true; } - // ═══════════════════════════════════════════════════════════════════════════ - // BUILT-IN ABILITY REGISTRY - // ═══════════════════════════════════════════════════════════════════════════ + public Ability getCustomAbility(String uuid) { + return customAbilities.get(uuid); + } - /** - * Register a pre-configured built-in ability by name. - * These are looked up by name in {@link #resolveAbility(String)}. - * - * @param name Unique name (e.g., "Jump Attack", "Ki Blast") - * @param ability Pre-configured ability instance - */ - public void registerAbility(String name, Ability ability) { - if (abilities.containsKey(name)) { - LogWriter.info("AbilityController: Overwriting built-in ability: " + name); + public boolean hasCustomAbility(String uuid) { + return customAbilities.containsKey(uuid); + } + + public Set getCustomAbilityIds() { + return new LinkedHashSet<>(customAbilities.keySet()); + } + + public String getCustomAbilityName(String uuid) { + Ability a = customAbilities.get(uuid); + return a != null ? a.getName() : null; + } + + public Map getCustomAbilities() { + return customAbilities; + } + + public void setCustomAbilities(Map synced) { + customAbilities.clear(); + customAbilities.putAll(synced); + customAbilityRevision++; + } + + public int getCustomAbilityRevision() { + return customAbilityRevision; + } + + private File getDir() { + File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities"); + if (!dir.exists()) { + dir.mkdirs(); } - if (!ability.isBuiltIn()) { - ability.setName(name); - } - abilities.put(name, ability); - LogWriter.info("Registered ability: " + name); + return dir; } // ═══════════════════════════════════════════════════════════════════════════ - // RESOLUTION (used by AbilitySlot, PlayerAbilityData, etc.) + // RESOLUTION // ═══════════════════════════════════════════════════════════════════════════ - /** - * Resolve an ability by key. Checks built-in abilities first (by name or registry key), - * then custom abilities (by UUID or name). Returns a copy safe to modify for - * custom abilities, or the singleton instance for built-in abilities. - * - * @param key The ability name, registry key (built-in) or UUID (custom) - * @return The resolved ability, or null if not found - */ public Ability resolveAbility(String key) { if (key == null || key.isEmpty()) return null; - // Check built-in abilities first (exact match by name) - Ability builtIn = abilities.get(key); - if (builtIn != null) { - return builtIn; - } + // Built-in: exact name + Ability builtIn = builtAbilities.get(key); + if (builtIn != null) return builtIn.deepCopy(); - // Check built-in abilities by name (case-insensitive) - for (Map.Entry entry : abilities.entrySet()) { + // Built-in: case-insensitive name + for (Map.Entry entry : builtAbilities.entrySet()) { if (entry.getKey().equalsIgnoreCase(key)) { - return entry.getValue(); + return entry.getValue().deepCopy(); } } - // Check built-in abilities by registry key / ID - for (Ability ability : abilities.values()) { + // Built-in: registry key / ID + for (Ability ability : builtAbilities.values()) { if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) { - return ability; + return ability.deepCopy(); } } - // Check custom abilities (exact UUID match) + // Custom: exact UUID Ability custom = customAbilities.get(key); - if (custom != null) { - return fromNBT(custom.writeNBT()); - } + if (custom != null) return custom.deepCopy(); - // Check custom abilities by name (case-insensitive) + // Custom: case-insensitive name for (Ability ability : customAbilities.values()) { if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { - return fromNBT(ability.writeNBT()); + return ability.deepCopy(); } } return null; } - /** - * Get all keys that can be used to look up abilities (for tab completion). - * Returns registry keys for built-in abilities (no spaces) and UUIDs for custom. - */ public Set getAbilityKeys() { Set keys = new LinkedHashSet<>(); - // Built-in abilities - use the ID (registry key for BuiltInAbility) - for (Ability ability : abilities.values()) { + for (Ability ability : builtAbilities.values()) { String id = ability.getId(); if (id != null && !id.isEmpty()) { keys.add(id); } } - // Custom abilities - use UUID keys.addAll(customAbilities.keySet()); return keys; } - /** - * Get keys for player-usable abilities only (for tab completion). - */ public Set getPlayerAbilityKeys() { Set keys = new LinkedHashSet<>(); - // Built-in abilities - use the ID (registry key for BuiltInAbility) - for (Ability ability : abilities.values()) { + for (Ability ability : builtAbilities.values()) { if (ability.getAllowedBy().allowsPlayer()) { String id = ability.getId(); if (id != null && !id.isEmpty()) { @@ -266,7 +317,6 @@ public class AbilityController implements IAbilityHandler { } } } - // Custom abilities - use UUID (if player-usable) for (Map.Entry entry : customAbilities.entrySet()) { if (entry.getValue().getAllowedBy().allowsPlayer()) { keys.add(entry.getKey()); @@ -275,82 +325,54 @@ public class AbilityController implements IAbilityHandler { return keys; } - /** - * Check if an ability key exists (either built-in or custom). - */ public boolean hasAbility(String key) { - return abilities.containsKey(key) || customAbilities.containsKey(key); + return builtAbilities.containsKey(key) || customAbilities.containsKey(key); } // ═══════════════════════════════════════════════════════════════════════════ - // ACCESSORS + // EXTENSION POINTS // ═══════════════════════════════════════════════════════════════════════════ - /** Get a built-in ability by map key. Returns the stored instance (not a copy). */ - public Ability getAbility(String name) { - return abilities.get(name); + public void registerVariant(String typeId, AbilityVariant variant) { + externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant); } - /** Get a built-in ability by its display name (ability.getName()). */ - public Ability getAbilityByDisplayName(String displayName) { - for (Ability ability : abilities.values()) { - if (ability.getName().equals(displayName)) { - return ability; - } + public List getVariantsForType(String typeId) { + List result = new ArrayList<>(); + Ability temp = create(typeId); + if (temp != null) { + result.addAll(temp.getVariants()); } - return null; + List ext = externalVariants.get(typeId); + if (ext != null) { + result.addAll(ext); + } + return result; } - /** Get all built-in ability map keys. */ - public Set getAbilityNames() { - return new LinkedHashSet<>(abilities.keySet()); + public void registerDamageHandler(IAbilityDamageHandler handler) { + this.damageHandler = handler; } - /** Get a custom ability by UUID. Returns the stored instance (not a copy). */ - public Ability getCustomAbility(String uuid) { - return customAbilities.get(uuid); + public IAbilityDamageHandler getDamageHandler() { + return damageHandler; } - /** Check if a custom ability exists by UUID. */ - public boolean hasCustomAbility(String uuid) { - return customAbilities.containsKey(uuid); + public void registerFieldProvider(IAbilityFieldProvider provider) { + fieldProviders.add(provider); } - /** Get all custom ability UUIDs. */ - public Set getCustomAbilityIds() { - return new LinkedHashSet<>(customAbilities.keySet()); - } - - /** Get the display name for a custom ability by UUID. */ - public String getCustomAbilityName(String uuid) { - Ability a = customAbilities.get(uuid); - return a != null ? a.getName() : null; - } - - /** Get the custom abilities map (used by SyncController). */ - public Map getCustomAbilities() { - return customAbilities; - } - - /** Replace the custom abilities map (used by client-side sync). */ - public void setCustomAbilities(Map synced) { - customAbilities.clear(); - customAbilities.putAll(synced); - version++; - } - - /** Get the version counter (incremented on custom ability changes). */ - public int getVersion() { - return version; + public List getFieldProviders() { + return fieldProviders; } // ═══════════════════════════════════════════════════════════════════════════ - // IAbilityHandler INTERFACE IMPLEMENTATION + // IAbilityHandler // ═══════════════════════════════════════════════════════════════════════════ @Override public String[] getTypes() { - return typeFactories.keySet().toArray(new String[0]); + return abilityTypes.keySet().toArray(new String[0]); } public boolean isBuiltInType(String typeId) { @@ -359,17 +381,17 @@ public class AbilityController implements IAbilityHandler { @Override public boolean hasType(String typeId) { - return typeFactories.containsKey(typeId); + return abilityTypes.containsKey(typeId); } @Override public String[] getAbilityNameArray() { - return abilities.keySet().toArray(new String[0]); + return builtAbilities.keySet().toArray(new String[0]); } @Override public boolean hasAbilityName(String name) { - return abilities.containsKey(name); + return builtAbilities.containsKey(name); } @Override @@ -386,166 +408,4 @@ public class AbilityController implements IAbilityHandler { public boolean deleteCustomAbilityById(String uuid) { return deleteCustomAbility(uuid); } - - // ═══════════════════════════════════════════════════════════════════════════ - // TYPE REGISTRATION - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register a new ability type. - * Extracts the typeId from a temporary instance and stores in typeFactories. - * - * @param factoryKey Unused legacy key — the typeId from the created instance is used - * @param factory Factory lambda that creates a new instance - */ - public void registerType(String factoryKey, Supplier factory) { - Ability temp = factory.get(); - String typeId = temp.getTypeId(); - if (typeFactories.containsKey(typeId)) { - LogWriter.info("AbilityController: Overwriting type: " + typeId); - } - typeFactories.put(typeId, factory); - if (temp.isBuiltIn()) { - builtInTypeIds.add(typeId); - } - } - - /** - * Create an ability from NBT data. - * Uses the "typeId" field to look up in typeFactories. - */ - public Ability fromNBT(NBTTagCompound nbt) { - if (nbt == null || !nbt.hasKey("typeId")) { - return null; - } - - String typeId = nbt.getString("typeId"); - Supplier factory = typeFactories.get(typeId); - if (factory == null) { - LogWriter.info("AbilityController: Unknown ability type: " + typeId); - return null; - } - - Ability ability = factory.get(); - ability.readNBT(nbt); - return ability; - } - - /** - * Create a new empty ability of the given type. - * - * @param typeId The ability typeId (e.g., "ability.cnpc.slam") - */ - public Ability create(String typeId) { - Supplier factory = typeFactories.get(typeId); - if (factory == null) { - return null; - } - return factory.get(); - } - - /** - * Register built-in ability types. - */ - private void registerBuiltinTypes() { - // Melee/AOE damage abilities - registerType("cnpc:slam", AbilitySlam::new); - registerType("cnpc:heavy_hit", AbilityHeavyHit::new); - registerType("cnpc:cutter", AbilityCutter::new); - - // Ranged/Projectile abilities - 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); - - // Movement abilities - 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); - - // Defensive abilities - registerType("cnpc:guard", AbilityGuard::new); - registerType("cnpc:heal", AbilityHeal::new); - - // Zone/Trap abilities - registerType("cnpc:hazard", AbilityHazard::new); - registerType("cnpc:trap", AbilityTrap::new); - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EXTERNAL DAMAGE HANDLER - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register an external damage handler for abilities. - * When set, the handler is called before default damage application. - * If the handler returns true, default damage is skipped. - */ - public void registerDamageHandler(IAbilityDamageHandler handler) { - this.damageHandler = handler; - } - - /** Get the registered damage handler, or null if none. */ - public IAbilityDamageHandler getDamageHandler() { - return damageHandler; - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EXTERNAL FIELD PROVIDERS - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register an external field provider for ability GUIs. - * Providers are called during getAllDefinitions() to inject custom tabs/fields. - */ - public void registerFieldProvider(IAbilityFieldProvider provider) { - fieldProviders.add(provider); - } - - /** Get all registered field providers. */ - public List getFieldProviders() { - return fieldProviders; - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EXTERNAL VARIANT REGISTRY - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register an external variant for an ability type. - * External mods can call this to add variant presets that appear - * alongside built-in variants in the variant selection SubGui. - * - * @param typeId The ability typeId (e.g., "ability.cnpc.beam") - * @param variant The variant to register - */ - public void registerVariant(String typeId, AbilityVariant variant) { - externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant); - } - - /** - * Get all variants for a given ability type (built-in + external). - * Returns the combined list of variants from the ability's getVariants() - * and any externally registered variants. - * - * @param typeId The ability typeId - * @return Combined list of variants, empty if none - */ - public List getVariantsForType(String typeId) { - List result = new ArrayList<>(); - Ability temp = create(typeId); - if (temp != null) { - result.addAll(temp.getVariants()); - } - List ext = externalVariants.get(typeId); - if (ext != null) { - result.addAll(ext); - } - return result; - } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java index ca4e7471e..5fde66586 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java @@ -61,7 +61,7 @@ public class AbilitySlot { AbilityController controller = AbilityController.Instance; if (controller == null) return null; - int currentVersion = controller.getVersion(); + int currentVersion = controller.getCustomAbilityRevision(); if (cachedAbility != null && cachedVersion == currentVersion) { return cachedAbility; } From 19fb0ff5b74411d1ae7a24ac18b401245d4ac871 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 14 Feb 2026 17:03:59 -0300 Subject: [PATCH 51/76] Changed how float text fields handle negative values --- src/main/java/noppes/npcs/client/gui/builder/FieldDef.java | 6 +++--- .../java/noppes/npcs/client/gui/util/GuiNpcTextField.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java index 5319d16e4..aec4b766a 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -32,8 +32,8 @@ public class FieldDef { private String hoverText = null; // Numeric range - private float min = Float.MIN_VALUE; - private float max = Float.MAX_VALUE; + private float min = 0; + private float max = Float.POSITIVE_INFINITY; // Enum support private Class> enumClass; @@ -272,7 +272,7 @@ public class FieldDef { public String getHoverText() { return hoverText; } public float getMin() { return min; } public float getMax() { return max; } - public boolean hasRange() { return min != Float.MIN_VALUE || max != Float.MAX_VALUE; } + public boolean hasRange() { return min != Float.NEGATIVE_INFINITY || max != Float.POSITIVE_INFINITY; } public Class> getEnumClass() { return enumClass; } public String[] getStringEnumValues() { return stringEnumValues; } public Supplier getSubGuiFactory() { return subGuiFactory; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java index 436b47bb5..0a15e8c7c 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java @@ -23,7 +23,7 @@ public class GuiNpcTextField extends GuiTextField { public int id; public int min = 0, max = Integer.MAX_VALUE, def = 0; public double minDouble = 0, maxDouble = Double.MAX_VALUE, defDouble = 0; - public float minFloat = 0, maxFloat = Float.MAX_VALUE, defFloat = 0; + public float minFloat = Float.NEGATIVE_INFINITY, maxFloat = Float.POSITIVE_INFINITY, defFloat = 0; protected static GuiNpcTextField activeTextfield = null; public boolean canEdit = true; public String hoverableText = ""; From a1f3f5184b5e02e6d58992ea887b0dd6f1b43455 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 14 Feb 2026 17:05:17 -0300 Subject: [PATCH 52/76] Changed anchor offsets min values --- .../controllers/data/ability/type/AbilityBeam.java | 11 +++++++---- .../controllers/data/ability/type/AbilityDisc.java | 11 +++++++---- .../data/ability/type/AbilityLaserShot.java | 6 ++++-- .../controllers/data/ability/type/AbilityOrb.java | 11 +++++++---- 4 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index d02c19bdd..215b3a137 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -591,11 +591,14 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, + v -> projectiles[idx].anchor.anchorOffsetX = v).min(Float.NEGATIVE_INFINITY), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, + v -> projectiles[idx].anchor.anchorOffsetY = v).min(Float.NEGATIVE_INFINITY) ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, + v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); // Color override (only when multiple projectiles) defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 2448642e0..c04f2e414 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -621,11 +621,14 @@ public class AbilityDisc extends Ability implements IAbilityDisc { () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, + v -> projectiles[idx].anchor.anchorOffsetX = v).min(Float.NEGATIVE_INFINITY), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, + v -> projectiles[idx].anchor.anchorOffsetY = v).min(Float.NEGATIVE_INFINITY) ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, + v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); // Color override (only when multiple projectiles) defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index a726e4c25..2bca3d681 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -295,11 +295,13 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) .tab("ability.tab.visual"), FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX) + .min(Float.NEGATIVE_INFINITY), FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + .min(Float.NEGATIVE_INFINITY) ).tab("ability.tab.visual"), FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .tab("ability.tab.visual"), + .min(Float.NEGATIVE_INFINITY).tab("ability.tab.visual"), FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 5dbf58424..7bc4bd8ef 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -592,11 +592,14 @@ public class AbilityOrb extends Ability implements IAbilityOrb { () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, + v -> projectiles[idx].anchor.anchorOffsetX = v).min(Float.NEGATIVE_INFINITY), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, + v -> projectiles[idx].anchor.anchorOffsetY = v).min(Float.NEGATIVE_INFINITY) ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, + v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); // Color override (only when multiple projectiles) defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) From a23b199e7e8ec810e2f37a55845b145c3e54083b Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 14 Feb 2026 15:21:56 -0500 Subject: [PATCH 53/76] Refactoring for Code Cleanup and Projectile Abstract Class Handling --- src/api | 2 +- .../controllers/data/ability/Ability.java | 76 ++- .../data/ability/type/AbilityBeam.java | 535 ++-------------- .../data/ability/type/AbilityCharge.java | 46 +- .../data/ability/type/AbilityCutter.java | 16 +- .../data/ability/type/AbilityDash.java | 37 +- .../data/ability/type/AbilityDisc.java | 545 ++-------------- .../data/ability/type/AbilityGuard.java | 8 +- .../data/ability/type/AbilityHazard.java | 13 +- .../data/ability/type/AbilityHeal.java | 18 +- .../data/ability/type/AbilityHeavyHit.java | 26 +- .../data/ability/type/AbilityLaserShot.java | 306 +++------ .../data/ability/type/AbilityOrb.java | 531 ++-------------- .../data/ability/type/AbilityProjectile.java | 10 +- .../data/ability/type/AbilityShockwave.java | 21 +- .../data/ability/type/AbilitySlam.java | 10 +- .../data/ability/type/AbilitySweeper.java | 15 +- .../data/ability/type/AbilityTeleport.java | 6 +- .../data/ability/type/AbilityTrap.java | 13 +- .../data/ability/type/AbilityVortex.java | 12 +- .../data/ability/type/AbilityZone.java | 4 +- .../type/AbstractEnergyProjectileAbility.java | 590 ++++++++++++++++++ .../npcs/entity/EntityAbilityBeam.java | 96 +-- .../npcs/entity/EntityAbilityDisc.java | 144 +---- .../npcs/entity/EntityAbilityLaser.java | 110 +--- .../kamkeel/npcs/entity/EntityAbilityOrb.java | 176 +----- .../npcs/entity/EntityAbilityProjectile.java | 215 +++++-- src/main/java/noppes/npcs/DataAbilities.java | 13 +- .../gui/util/AbilityPreviewExecutor.java | 6 +- .../controllers/data/PlayerAbilityData.java | 21 +- 30 files changed, 1226 insertions(+), 2395 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java diff --git a/src/api b/src/api index 456bb2cbf..2b95d3ca4 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 456bb2cbfa7456d114bfc22caf49020353282e07 +Subproject commit 2b95d3ca47558e804a09e4f7b7f45aeb69fa7861 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 f8f620474..1878337b8 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,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.AxisAlignedBB; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.DamageSource; @@ -141,14 +142,17 @@ public abstract class Ability implements IAbility { // ═══════════════════════════════════════════════════════════════════ /** - * Called first tick of ACTIVE phase + * Called first tick of ACTIVE phase. + * For burst without replay (burstReplayAnimations=false), this is called directly + * after BURST_DELAY without a preceding windup. Check isBurstRefire() or null-check + * entity state to detect and handle the burst refire case. */ - public abstract void onExecute(EntityLivingBase caster, EntityLivingBase target, World world); + public abstract void onExecute(EntityLivingBase caster, EntityLivingBase target); /** * Called every tick of ACTIVE phase */ - public abstract void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick); + public abstract void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick); /** * Write type-specific config to NBT @@ -208,17 +212,15 @@ public abstract class Ability implements IAbility { return true; } - /** - * Called when burst re-fires without replay animations (burstReplayAnimations=false). - * Entity-spawning abilities should override to spawn and fire entities in one step, - * since onWindUpTick was not called (windup was skipped). - * Default: does nothing (ability goes directly to onExecute with existing state). - */ - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - // Override in entity-spawning abilities (Orb, Beam, Disc, LaserShot) + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { } - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + /** + * Whether this execution is a burst refire (not the first execution). + * Useful in onExecute() to detect when windup was skipped and entities need fresh creation. + */ + public boolean isBurstRefire() { + return burstEnabled && burstIndex > 0; } public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { @@ -1051,11 +1053,11 @@ public abstract class Ability implements IAbility { * Spawn an entity during ability execution. * In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld(). */ - protected void spawnAbilityEntity(World world, Entity entity) { + protected void spawnAbilityEntity(Entity entity) { if (previewMode && previewEntityHandler != null) { previewEntityHandler.onEntitySpawned(entity); } else { - world.spawnEntityInWorld(entity); + entity.worldObj.spawnEntityInWorld(entity); } if (burstEnabled && burstOverlap) { burstEntities.add(entity); @@ -1800,6 +1802,52 @@ public abstract class Ability implements IAbility { return totalDuration; } + // ═══════════════════════════════════════════════════════════════════ + // MOVEMENT COLLISION UTILITY + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if a caster's movement in a given direction is blocked by walls/blocks. + * Used by Charge and Dash abilities to detect wall collision. + * + * @param caster The entity moving + * @param dirX X component of normalized movement direction + * @param dirZ Z component of normalized movement direction + * @param speed Movement speed (blocks per tick) + * @return true if movement is blocked + */ + protected static boolean isMovementBlocked(EntityLivingBase caster, double dirX, double dirZ, double speed) { + double nextX = dirX * speed; + double nextZ = dirZ * speed; + AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); + double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); + + int x1 = (int) Math.floor(nextBox.minX); + int x2 = (int) Math.floor(nextBox.maxX + 1.0); + int y1 = (int) Math.floor(nextBox.minY) - 1; + int y2 = (int) Math.floor(nextBox.maxY + 1.0); + int z1 = (int) Math.floor(nextBox.minZ); + int z2 = (int) Math.floor(nextBox.maxZ + 1.0); + + java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); + for (int bx = x1; bx < x2; bx++) { + for (int bz = z1; bz < z2; bz++) { + for (int by = y1; by < y2; by++) { + Block block = caster.worldObj.getBlock(bx, by, bz); + if (!block.getMaterial().blocksMovement()) continue; + collisionBoxes.clear(); + block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); + for (AxisAlignedBB box : collisionBoxes) { + if (box.maxY > stepThreshold) { + return true; + } + } + } + } + } + return false; + } + // ═══════════════════════════════════════════════════════════════════ // IAbility API METHODS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 215b3a137..45772eedb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -2,62 +2,41 @@ package kamkeel.npcs.controllers.data.ability.type; 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.AbilityVariant; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityEnergyBeam; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** * Energy Beam ability: A homing head with a trailing path. * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ -public class AbilityBeam extends Ability implements IAbilityEnergyBeam { +public class AbilityBeam extends AbstractEnergyProjectileAbility implements IAbilityEnergyBeam { - private static final int MAX_PROJECTILES = 8; - - // Beam shape properties (shared) private float beamWidth = 0.4f; private float headSize = 0.6f; - // Projectile count and fire stagger - private int projectileCount = 1; - private int fireDelay = 0; - - // Shared visual data (all projectiles use these) - private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Shared combat/movement data - private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - - // Per-projectile data (anchor + optional color override) - private ProjectileData[] projectiles; - - // Transient entity state - private transient EntityAbilityBeam[] beamEntities; - public AbilityBeam() { + super( + new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f), + new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f), + new EnergyHomingData(0.4f, true, 0.1f, 15.0f), + new EnergyLifespanData(25.0f, 200) + ); this.typeId = "ability.cnpc.beam"; this.name = "Beam"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -72,56 +51,57 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { this.showTelegraph = true; this.windUpAnimationName = "Ability_Beam_Windup"; this.activeAnimationName = "Ability_Beam_Active"; - initProjectiles(1); } - private void initProjectiles(int count) { - this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - this.projectiles = new ProjectileData[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityBeam createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityBeam( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + beamWidth, headSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + lockMovement.locksActive()); + } + + @Override + protected void fireEntity(EntityAbilityBeam beam, EntityLivingBase target) { + if (isPreview()) { + beam.startPreviewFiring(); + } else { + beam.startFiring(target); } } - private AnchorPoint getDefaultAnchor(int index) { - switch (index) { - case 0: return AnchorPoint.RIGHT_HAND; - case 1: return AnchorPoint.LEFT_HAND; - default: return AnchorPoint.FRONT; - } + @Override + protected void setupEntityCharging(EntityAbilityBeam beam, ProjectileData projData, int index) { + beam.setupCharging(projData.anchor, windUpTicks, 1.0f); } - public void setProjectileCount(int count) { - int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - if (newCount == projectileCount) return; - - ProjectileData[] oldProjectiles = projectiles; - initProjectiles(newCount); - - if (oldProjectiles != null) { - int copyCount = Math.min(oldProjectiles.length, newCount); - for (int i = 0; i < copyCount; i++) { - if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; - } - } + @Override + protected void setupEntityPreview(EntityAbilityBeam beam, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + beam.setupPreview(caster, beamWidth, headSize, resolved, lightningData, projData.anchor, windUpTicks, 1.0f); } - public int getProjectileCount() { - return projectileCount; + @Override + protected EntityAbilityBeam[] createEntityArray(int size) { + return new EntityAbilityBeam[size]; } - public int getFireDelay() { - return fireDelay; + @Override + protected float getProjectileTelegraphRadius() { + return headSize * 2.0f; } - public void setFireDelay(int delay) { - this.fireDelay = Math.max(0, delay); + @Override + protected Vec3 getSpawnPosition(EntityLivingBase caster, int index) { + return AnchorPointHelper.calculateAnchorPosition(caster, projectiles[index].anchor, 1.0f); } - /** @deprecated Use {@link #getFireDelay()} */ - public int getDualFireDelay() { return fireDelay; } - /** @deprecated Use {@link #setFireDelay(int)} */ - public void setDualFireDelay(int delay) { setFireDelay(delay); } + // ==================== VARIANTS ==================== @Override public List getVariants() { @@ -134,7 +114,6 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { a.setName("Dual Beam"); beam.setProjectileCount(2); beam.setFireDelay(0); - // Set color override for second beam beam.projectiles[1].colorOverride = true; beam.projectiles[1].innerColor = 0xFFFFFF; beam.projectiles[1].outerColor = 0xFF0000; @@ -145,244 +124,24 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { ); } - @Override - public boolean allowOverlap() { - return true; - } + // ==================== TYPE-SPECIFIC NBT ==================== @Override - public boolean isReadyForBurstCompletion(int activeTick) { - return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - /** - * Create beam entities. - * NPC: target is the aggro target — beams will home toward it. - * Player: target is null — beams fire in caster's look direction. - */ - private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) { - EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount]; - float offsetDist = 1.0f; - for (int i = 0; i < projectileCount; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor, offsetDist); - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - entities[i] = new EntityAbilityBeam( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - beamWidth, headSize, - resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, - lockMovement.locksActive()); - entities[i].setEffects(this.effects); - entities[i].setSourceAbility(this); - } - if (projectileCount == 2 && entities[0] != null && entities[1] != null) { - entities[0].setSiblingEntityId(entities[1].getEntityId()); - entities[1].setSiblingEntityId(entities[0].getEntityId()); - } - return entities; - } - - private void fireBeamEntity(EntityAbilityBeam beam, EntityLivingBase target) { - if (beam == null || beam.isDead) return; - if (isPreview()) { - beam.startPreviewFiring(); - } else { - beam.startFiring(target); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - beamEntities = createBeamEntities(caster, target, world); - float offsetDist = 1.0f; - for (int i = 0; i < projectileCount; i++) { - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - if (isPreview()) { - beamEntities[i].setupPreview(caster, beamWidth, headSize, resolved, lightningData, projectiles[i].anchor, windUpTicks, offsetDist); - } else { - beamEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, offsetDist); - } - spawnAbilityEntity(world, beamEntities[i]); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - beamEntities = createBeamEntities(caster, target, world); - for (EntityAbilityBeam beam : beamEntities) { - spawnAbilityEntity(world, beam); - } - - // Fire first projectile immediately, let onActiveTick handle the rest with fireDelay - fireBeamEntity(beamEntities[0], target); - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireBeamEntity(beamEntities[i], target); - } - } - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (beamEntities == null) return; - - fireBeamEntity(beamEntities[0], target); - - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireBeamEntity(beamEntities[i], target); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (beamEntities == null) { - signalCompletion(); - return; - } - - if (fireDelay > 0) { - for (int i = 1; i < projectileCount; i++) { - if (tick == fireDelay * i) { - fireBeamEntity(beamEntities[i], target); - } - } - } - - boolean allDead = true; - for (EntityAbilityBeam beam : beamEntities) { - if (beam != null && !beam.isDead) { - allDead = false; - break; - } - } - if (allDead) { - signalCompletion(); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - if (beamEntities != null) { - for (int i = 0; i < beamEntities.length; i++) { - if (beamEntities[i] != null && !beamEntities[i].isDead) { - beamEntities[i].setDead(); - } - beamEntities[i] = null; - } - } - beamEntities = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - // NPC: telegraph on aggro target position - // Player: no telegraph (beam fires in look direction, no fixed position to mark) - if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { - return null; - } - - Telegraph telegraph = Telegraph.circle(headSize * 2.0f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return headSize * 2.0f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("beamWidth", beamWidth); nbt.setFloat("headSize", headSize); - nbt.setInteger("projectileCount", projectileCount); - nbt.setInteger("fireDelay", fireDelay); - - // Shared visual data - displayData.writeNBT(nbt); - lightningData.writeNBT(nbt); - - // Shared combat/movement data - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - // Per-projectile data - for (int i = 0; i < projectileCount; i++) { - NBTTagCompound projNbt = new NBTTagCompound(); - projectiles[i].writeNBT(projNbt); - nbt.setTag("Projectile_" + i, projNbt); - } } @Override - public void readTypeNBT(NBTTagCompound nbt) { + protected void readTypeSpecificNBT(NBTTagCompound nbt) { this.beamWidth = nbt.getFloat("beamWidth"); this.headSize = nbt.getFloat("headSize"); - - int count = nbt.getInteger("projectileCount"); - initProjectiles(count); - - this.fireDelay = nbt.getInteger("fireDelay"); - - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - // Shared visual data - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - - // Per-projectile data - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } } - // ═══════════════════════════════════════════════════════════════════ - // API GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ + // ==================== TYPE-SPECIFIC GETTERS ==================== + + public float getSpeed() { return homingData.speed; } + public void setSpeed(float speed) { homingData.speed = speed; } public float getBeamWidth() { return beamWidth; } public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } @@ -390,142 +149,16 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { public float getHeadSize() { return headSize; } public void setHeadSize(float headSize) { this.headSize = headSize; } - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { this.homingData.speed = speed; } - - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { this.homingData.homing = homing; } - - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } - - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } - - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - - // Shared display data (primary colors) - public int getInnerColor() { return displayData.innerColor; } - public void setInnerColor(int innerColor) { displayData.innerColor = innerColor; } - - public int getOuterColor() { return displayData.outerColor; } - public void setOuterColor(int outerColor) { displayData.outerColor = outerColor; } - - public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { displayData.outerColorEnabled = outerColorEnabled; } - - public float getOuterColorWidth() { return displayData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { displayData.outerColorWidth = outerColorWidth; } - - public float getOuterColorAlpha() { return displayData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { displayData.outerColorAlpha = outerColorAlpha; } - - public float getRotationSpeed() { return displayData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { displayData.rotationSpeed = rotationSpeed; } - - // Shared lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; } - - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; } - - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; } - - public int getLightningFadeTime() { return lightningData.lightningFadeTime; } - public void setLightningFadeTime(int lightningFadeTime) { lightningData.lightningFadeTime = lightningFadeTime; } - - // Anchor - default to projectile 0 - public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { projectiles[0].anchor.anchorPoint = anchorPoint; } - - public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } - public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } - - public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } - public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } - - public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } - public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } - - @Override - public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } - - @Override - public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - - // Indexed API methods - public int getInnerColor(int index) { - ProjectileData p = projectiles[clampIndex(index)]; - return p.colorOverride ? p.innerColor : displayData.innerColor; - } - public void setInnerColor(int index, int color) { - ProjectileData p = projectiles[clampIndex(index)]; - p.colorOverride = true; - p.innerColor = color; - } - - public int getOuterColor(int index) { - ProjectileData p = projectiles[clampIndex(index)]; - return p.colorOverride ? p.outerColor : displayData.outerColor; - } - public void setOuterColor(int index, int color) { - ProjectileData p = projectiles[clampIndex(index)]; - p.colorOverride = true; - p.outerColor = color; - } - - public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } - public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } - public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } - public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } - - private int clampIndex(int index) { - return Math.max(0, Math.min(index, projectileCount - 1)); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { + protected void addTypeDefinitions(List defs) { defs.add(FieldDef.row( FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) .range(0, 200).visibleWhen(() -> projectileCount > 1) )); - defs.add(FieldDef.row( FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) @@ -550,63 +183,5 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); - - // Visual tab - shared primary colors - defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); - defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual")); - defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual")); - defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual")); - - // Visual tab - shared effects - defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); - defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual")); - defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual")); - defs.add(FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual")); - - // Visual tab - per-projectile sections - for (int i = 0; i < MAX_PROJECTILES; i++) { - final int idx = i; - String sectionKey = "ability.section.projectile" + (i + 1); - - defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") - .visibleWhen(() -> idx < projectileCount)); - - defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, - v -> projectiles[idx].anchor.anchorOffsetX = v).min(Float.NEGATIVE_INFINITY), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, - v -> projectiles[idx].anchor.anchorOffsetY = v).min(Float.NEGATIVE_INFINITY) - ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, - v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); - - // Color override (only when multiple projectiles) - defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); - defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); - defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); - } } } 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 7cfb44428..871249885 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 @@ -13,7 +13,6 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.Vec3; -import net.minecraft.world.World; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; @@ -81,7 +80,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { * Called on the first tick of windup - lock direction here so it matches telegraph. */ @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (tick == 1) { // Lock direction on first windup tick (same time telegraph is created) lockChargeDirection(caster, target); @@ -116,7 +115,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { // Initialize charge - direction was already locked during windup startX = caster.posX; startY = caster.posY; @@ -146,7 +145,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Safety timeout or missing state: force-complete to prevent stuck NPC if (!isPreview() && (chargeDirection == null || tick > maxActiveTicks)) { stopMomentum(caster); @@ -206,11 +205,11 @@ public class AbilityCharge extends Ability implements IAbilityCharge { } // Server-side collision damage (skip in preview) - if (!world.isRemote && !isPreview()) { + if (!caster.worldObj.isRemote && !isPreview()) { AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth); @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); for (Entity entity : entities) { if (!(entity instanceof EntityLivingBase)) continue; @@ -226,9 +225,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { boolean wasHit = applyAbilityDamageWithDirection(caster, livingEntity, damage, knockback, chargeDirection.xCoord, chargeDirection.zCoord); - // Play impact sound if hit wasn't cancelled + // Apply effects and play impact sound if hit wasn't cancelled if (wasHit) { - world.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f); + applyEffects(livingEntity); + caster.worldObj.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f); } } } @@ -255,35 +255,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { } private boolean isChargeBlocked(EntityLivingBase caster) { - double nextX = chargeDirection.xCoord * chargeSpeed; - double nextZ = chargeDirection.zCoord * chargeSpeed; - AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); - double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); - - int x1 = (int) Math.floor(nextBox.minX); - int x2 = (int) Math.floor(nextBox.maxX + 1.0); - int y1 = (int) Math.floor(nextBox.minY) - 1; - int y2 = (int) Math.floor(nextBox.maxY + 1.0); - int z1 = (int) Math.floor(nextBox.minZ); - int z2 = (int) Math.floor(nextBox.maxZ + 1.0); - - java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); - for (int bx = x1; bx < x2; bx++) { - for (int bz = z1; bz < z2; bz++) { - for (int by = y1; by < y2; by++) { - net.minecraft.block.Block block = caster.worldObj.getBlock(bx, by, bz); - if (!block.getMaterial().blocksMovement()) continue; - collisionBoxes.clear(); - block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); - for (AxisAlignedBB box : collisionBoxes) { - if (box.maxY > stepThreshold) { - return true; - } - } - } - } - } - return false; + return isMovementBlocked(caster, chargeDirection.xCoord, chargeDirection.zCoord, chargeSpeed); } @Override 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 110bda19f..58c92009f 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 @@ -154,7 +154,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { hitEntities.clear(); currentRotation = -arcAngle / 2.0f; activeSoundPlayed = false; @@ -175,8 +175,8 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (caster.worldObj.isRemote && !isPreview()) return; switch (sweepMode) { case SWIPE: @@ -185,25 +185,25 @@ public class AbilityCutter extends Ability implements IAbilityCutter { // Play active sound when sweep reaches center (where target typically stands) if (!activeSoundPlayed && currentRotation >= 0) { - playActiveSound(caster, world); + playActiveSound(caster, caster.worldObj); } if (currentRotation > arcAngle / 2.0f) { if (!isPreview()) { - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevRotation, arcAngle / 2.0f); } signalCompletion(); return; } if (!isPreview()) { - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevRotation, currentRotation); } break; case SPIN: // Play active sound at spin start if (!activeSoundPlayed) { - playActiveSound(caster, world); + playActiveSound(caster, caster.worldObj); } if (tick >= spinDurationTicks) { @@ -214,7 +214,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { currentRotation = (currentRotation + sweepSpeed) % 360.0f; if (!isPreview()) { hitEntities.clear(); - performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevSpin, currentRotation); } break; } 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 6070342d7..8dbd13c92 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 @@ -11,7 +11,6 @@ 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.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; @@ -133,7 +132,7 @@ public class AbilityDash extends Ability implements IAbilityDash { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { startX = caster.posX; startY = caster.posY; startZ = caster.posZ; @@ -175,7 +174,7 @@ public class AbilityDash extends Ability implements IAbilityDash { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Safety timeout or missing state: force-complete to prevent stuck NPC if (!isPreview() && (dashDirection == null || tick > maxActiveTicks)) { stopDash(caster); @@ -224,7 +223,7 @@ public class AbilityDash extends Ability implements IAbilityDash { caster.velocityChanged = true; // Trail particles - world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + caster.worldObj.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); } } @@ -255,35 +254,7 @@ public class AbilityDash extends Ability implements IAbilityDash { private boolean isDashBlocked(EntityLivingBase caster) { if (dashDirection == null) return true; - double nextX = dashDirection.xCoord * dashSpeed; - double nextZ = dashDirection.zCoord * dashSpeed; - AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); - double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); - - int x1 = (int) Math.floor(nextBox.minX); - int x2 = (int) Math.floor(nextBox.maxX + 1.0); - int y1 = (int) Math.floor(nextBox.minY) - 1; - int y2 = (int) Math.floor(nextBox.maxY + 1.0); - int z1 = (int) Math.floor(nextBox.minZ); - int z2 = (int) Math.floor(nextBox.maxZ + 1.0); - - java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); - for (int bx = x1; bx < x2; bx++) { - for (int bz = z1; bz < z2; bz++) { - for (int by = y1; by < y2; by++) { - net.minecraft.block.Block block = caster.worldObj.getBlock(bx, by, bz); - if (!block.getMaterial().blocksMovement()) continue; - collisionBoxes.clear(); - block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); - for (AxisAlignedBB box : collisionBoxes) { - if (box.maxY > stepThreshold) { - return true; - } - } - } - } - } - return false; + return isMovementBlocked(caster, dashDirection.xCoord, dashDirection.zCoord, dashSpeed); } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index c04f2e414..5a542ce7d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -2,67 +2,42 @@ package kamkeel.npcs.controllers.data.ability.type; 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.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityDisc; -import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityDisc; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** * Disc ability: Spawns a flat spinning disc projectile. * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. * Has optional boomerang behavior to return to owner. */ -public class AbilityDisc extends Ability implements IAbilityDisc { +public class AbilityDisc extends AbstractEnergyProjectileAbility implements IAbilityDisc { - private static final int MAX_PROJECTILES = 8; - - // Disc geometry (shared) private float discRadius = 1.0f; private float discThickness = 0.2f; - private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) - - // Boomerang properties (shared) + private boolean vertical = false; private boolean boomerang = false; private int boomerangDelay = 40; - // Projectile count and fire stagger - private int projectileCount = 1; - private int fireDelay = 0; - - // Shared visual data (all projectiles use these) - private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Shared combat/movement data - private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - - // Per-projectile data (anchor + optional color override) - private ProjectileData[] projectiles; - - // Transient entity state - private transient EntityAbilityDisc[] discEntities; - public AbilityDisc() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f), + new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f), + new EnergyHomingData(0.6f, true, 0.12f, 18.0f), + new EnergyLifespanData(35.0f, 200) + ); this.typeId = "ability.cnpc.disc"; this.name = "Disc"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -75,59 +50,52 @@ public class AbilityDisc extends Ability implements IAbilityDisc { this.showTelegraph = true; this.windUpAnimationName = "Ability_Disc_Windup"; this.activeAnimationName = "Ability_Disc_Active"; - initProjectiles(1); } - private void initProjectiles(int count) { - this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - this.projectiles = new ProjectileData[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityDisc createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityDisc( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + discRadius, discThickness, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + boomerang, boomerangDelay); + } + + @Override + protected void fireEntity(EntityAbilityDisc disc, EntityLivingBase target) { + if (isPreview()) { + disc.startPreviewFiring(); + } else { + disc.startMoving(target); } } - /** - * Disc anchor order is REVERSED from Orb/Beam: [0]=LEFT_HAND, [1]=RIGHT_HAND - */ - private AnchorPoint getDefaultAnchor(int index) { - switch (index) { - case 0: return AnchorPoint.RIGHT_HAND; - case 1: return AnchorPoint.LEFT_HAND; - default: return AnchorPoint.FRONT; - } + @Override + protected void setupEntityCharging(EntityAbilityDisc disc, ProjectileData projData, int index) { + disc.setupCharging(projData.anchor, windUpTicks, vertical); } - public void setProjectileCount(int count) { - int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - if (newCount == projectileCount) return; - - ProjectileData[] oldProjectiles = projectiles; - initProjectiles(newCount); - - if (oldProjectiles != null) { - int copyCount = Math.min(oldProjectiles.length, newCount); - for (int i = 0; i < copyCount; i++) { - if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; - } - } + @Override + protected void setupEntityPreview(EntityAbilityDisc disc, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + disc.setupPreview(caster, discRadius, discThickness, resolved, lightningData, projData.anchor, windUpTicks, vertical); } - public int getProjectileCount() { - return projectileCount; + @Override + protected EntityAbilityDisc[] createEntityArray(int size) { + return new EntityAbilityDisc[size]; } - public int getFireDelay() { - return fireDelay; + @Override + protected float getProjectileTelegraphRadius() { + return discRadius * 1.5f; } - public void setFireDelay(int delay) { - this.fireDelay = Math.max(0, delay); - } - - /** @deprecated Use {@link #getFireDelay()} */ - public int getDualFireDelay() { return fireDelay; } - /** @deprecated Use {@link #setFireDelay(int)} */ - public void setDualFireDelay(int delay) { setFireDelay(delay); } + // ==================== VARIANTS ==================== @Override public List getVariants() { @@ -140,7 +108,6 @@ public class AbilityDisc extends Ability implements IAbilityDisc { a.setName("Dual Disc"); disc.setProjectileCount(2); disc.setFireDelay(5); - // Set color override for second disc disc.projectiles[1].colorOverride = true; disc.projectiles[1].innerColor = 0xFFFFFF; disc.projectiles[1].outerColor = 0x8800FF; @@ -150,255 +117,27 @@ public class AbilityDisc extends Ability implements IAbilityDisc { ); } - @Override - public boolean allowOverlap() { - return true; - } + // ==================== TYPE-SPECIFIC NBT ==================== @Override - public boolean isReadyForBurstCompletion(int activeTick) { - return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - /** - * Create disc entities. - * NPC: target is the aggro target — discs will home toward it. - * Player: target is null — discs fire in caster's look direction. - */ - private EntityAbilityDisc[] createDiscEntities(EntityLivingBase caster, EntityLivingBase target, World world) { - EntityAbilityDisc[] entities = new EntityAbilityDisc[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - entities[i] = new EntityAbilityDisc( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - discRadius, discThickness, - resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, - boomerang, boomerangDelay); - entities[i].setEffects(this.effects); - entities[i].setSourceAbility(this); - } - if (projectileCount == 2 && entities[0] != null && entities[1] != null) { - entities[0].setSiblingEntityId(entities[1].getEntityId()); - entities[1].setSiblingEntityId(entities[0].getEntityId()); - } - return entities; - } - - private void fireDiscEntity(EntityAbilityDisc disc, EntityLivingBase target) { - if (disc == null || disc.isDead) return; - if (isPreview()) { - disc.startPreviewFiring(); - } else { - disc.startMoving(target); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - discEntities = createDiscEntities(caster, target, world); - for (int i = 0; i < projectileCount; i++) { - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - if (isPreview()) { - discEntities[i].setupPreview(caster, discRadius, discThickness, resolved, lightningData, projectiles[i].anchor, windUpTicks, vertical); - } else { - discEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, vertical); - } - spawnAbilityEntity(world, discEntities[i]); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - discEntities = createDiscEntities(caster, target, world); - for (EntityAbilityDisc disc : discEntities) { - spawnAbilityEntity(world, disc); - } - - // Fire first projectile immediately, let onActiveTick handle the rest with fireDelay - fireDiscEntity(discEntities[0], target); - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireDiscEntity(discEntities[i], target); - } - } - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (discEntities == null) return; - - // Fire first projectile immediately - fireDiscEntity(discEntities[0], target); - - // Fire remaining projectiles if no delay - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireDiscEntity(discEntities[i], target); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (discEntities == null) { - signalCompletion(); - return; - } - - // Fire staggered projectiles - if (fireDelay > 0) { - for (int i = 1; i < projectileCount; i++) { - if (tick == fireDelay * i) { - fireDiscEntity(discEntities[i], target); - } - } - } - - // Check if all entities are dead - boolean allDead = true; - for (EntityAbilityDisc disc : discEntities) { - if (disc != null && !disc.isDead) { - allDead = false; - break; - } - } - if (allDead) { - signalCompletion(); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - if (discEntities != null) { - for (int i = 0; i < discEntities.length; i++) { - if (discEntities[i] != null && !discEntities[i].isDead) { - discEntities[i].setDead(); - } - discEntities[i] = null; - } - } - discEntities = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - // NPC: telegraph on aggro target position - // Player: no telegraph (discs fire in look direction, no fixed position to mark) - if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(discRadius * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return discRadius * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("discRadius", discRadius); nbt.setFloat("discThickness", discThickness); nbt.setBoolean("vertical", vertical); nbt.setBoolean("boomerang", boomerang); nbt.setInteger("boomerangDelay", boomerangDelay); - nbt.setInteger("projectileCount", projectileCount); - nbt.setInteger("fireDelay", fireDelay); - - // Shared visual data - displayData.writeNBT(nbt); - lightningData.writeNBT(nbt); - - // Shared combat/movement data - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - // Per-projectile data - for (int i = 0; i < projectileCount; i++) { - NBTTagCompound projNbt = new NBTTagCompound(); - projectiles[i].writeNBT(projNbt); - nbt.setTag("Projectile_" + i, projNbt); - } } @Override - public void readTypeNBT(NBTTagCompound nbt) { + protected void readTypeSpecificNBT(NBTTagCompound nbt) { this.discRadius = nbt.getFloat("discRadius"); this.discThickness = nbt.getFloat("discThickness"); this.vertical = nbt.getBoolean("vertical"); this.boomerang = nbt.getBoolean("boomerang"); this.boomerangDelay = nbt.getInteger("boomerangDelay"); - - int count = nbt.getInteger("projectileCount"); - initProjectiles(count); - - this.fireDelay = nbt.getInteger("fireDelay"); - - // Shared combat/movement data - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - // Shared visual data - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - - // Per-projectile data - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } } - // ═══════════════════════════════════════════════════════════════════ - // API GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ + // ==================== TYPE-SPECIFIC GETTERS ==================== public float getSpeed() { return homingData.speed; } public void setSpeed(float speed) { homingData.speed = speed; } @@ -418,141 +157,16 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public int getBoomerangDelay() { return boomerangDelay; } public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float d) { lifespanData.maxDistance = d; } - - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } - - public float getDamage() { return combatData.damage; } - public void setDamage(float d) { combatData.damage = d; } - - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float k) { combatData.knockback = k; } - - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float k) { combatData.knockbackUp = k; } - - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean h) { homingData.homing = h; } - - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float s) { homingData.homingStrength = s; } - - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float r) { homingData.homingRange = r; } - - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean e) { combatData.explosive = e; } - - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float r) { combatData.explosionRadius = r; } - - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } - - // Shared display data (primary colors) - public int getInnerColor() { return displayData.innerColor; } - public void setInnerColor(int c) { displayData.innerColor = c; } - - public int getOuterColor() { return displayData.outerColor; } - public void setOuterColor(int c) { displayData.outerColor = c; } - - public float getOuterColorWidth() { return displayData.outerColorWidth; } - public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } - - public float getOuterColorAlpha() { return displayData.outerColorAlpha; } - public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } - - public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } - public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } - - public float getRotationSpeed() { return displayData.rotationSpeed; } - public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } - - // Shared lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } - - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float d) { lightningData.lightningDensity = d; } - - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float r) { lightningData.lightningRadius = r; } - - public int getLightningFadeTime() { return lightningData.lightningFadeTime; } - public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } - - // Anchor - default to projectile 0 - public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } - public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } - - public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } - public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } - - public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } - public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } - - public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } - public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } - - @Override - public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } - - @Override - public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - - // Indexed API methods - public int getInnerColor(int index) { - ProjectileData p = projectiles[clampIndex(index)]; - return p.colorOverride ? p.innerColor : displayData.innerColor; - } - public void setInnerColor(int index, int color) { - ProjectileData p = projectiles[clampIndex(index)]; - p.colorOverride = true; - p.innerColor = color; - } - - public int getOuterColor(int index) { - ProjectileData p = projectiles[clampIndex(index)]; - return p.colorOverride ? p.outerColor : displayData.outerColor; - } - public void setOuterColor(int index, int color) { - ProjectileData p = projectiles[clampIndex(index)]; - p.colorOverride = true; - p.outerColor = color; - } - - public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } - public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } - public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } - public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } - - private int clampIndex(int index) { - return Math.max(0, Math.min(index, projectileCount - 1)); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - // Type tab - projectile count and fire delay + protected void addTypeDefinitions(List defs) { defs.add(FieldDef.row( FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) .range(0, 200).visibleWhen(() -> projectileCount > 1) )); - - // Type tab - disc properties defs.add(FieldDef.row( FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) @@ -579,64 +193,5 @@ public class AbilityDisc extends Ability implements IAbilityDisc { defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); - - // Visual tab - shared primary colors - defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); - defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual")); - defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual")); - defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual")); - - // Visual tab - shared effects - defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); - defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual")); - defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual")); - defs.add(FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual")); - - // Visual tab - per-projectile sections - for (int i = 0; i < MAX_PROJECTILES; i++) { - final int idx = i; - String sectionKey = "ability.section.projectile" + (i + 1); - - defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") - .visibleWhen(() -> idx < projectileCount)); - - // Anchor point - defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, - v -> projectiles[idx].anchor.anchorOffsetX = v).min(Float.NEGATIVE_INFINITY), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, - v -> projectiles[idx].anchor.anchorOffsetY = v).min(Float.NEGATIVE_INFINITY) - ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, - v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); - - // Color override (only when multiple projectiles) - defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); - defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); - defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); - } } } 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 87fd21a7f..dc1b075e7 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 @@ -95,7 +95,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { lastAttacker = null; counterTriggered = false; lastDamageTaken = 0.0f; @@ -103,9 +103,9 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !world.isRemote) { - performCounter(caster, world); + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !caster.worldObj.isRemote) { + performCounter(caster, caster.worldObj); } if (tick > counterWindow && counterEligible) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index e5dfde01e..26409d5fe 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -5,7 +5,7 @@ import kamkeel.npcs.entity.EntityAbilityZone; import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; + import noppes.npcs.api.ability.type.IAbilityHazard; @@ -48,12 +48,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { activeEntities.clear(); // Use pre-calculated positions from telegraph phase, or generate new ones @@ -75,7 +70,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { for (int i = 0; i < zoneCount; i++) { double[] pos = positions.get(i); - EntityAbilityZone entity = EntityAbilityZone.createHazard(world, caster, + EntityAbilityZone entity = EntityAbilityZone.createHazard(caster.worldObj, caster, pos[0], caster.posY, pos[1], zoneShape, radius, @@ -93,7 +88,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { entity.setupPreview(caster); } - spawnAbilityEntity(world, entity); + spawnAbilityEntity(entity); activeEntities.add(entity); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index d2714ddd2..6119e1340 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -79,27 +79,27 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) return; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) return; if (!isPreview()) { getHealedAllies().clear(); // Always find allies if we're healing them (needed for both instant and HoT) if (healAllies && healRadius > 0) { - findAlliesInRadius(caster, world); + findAlliesInRadius(caster, caster.worldObj); } if (instantHeal) { // Instant heal - apply all healing now if (healSelf) { healEntity(caster); - spawnHealParticles(world, caster); + spawnHealParticles(caster.worldObj, caster); } for (EntityLivingBase ally : getHealedAllies()) { healEntity(ally); - spawnHealParticles(world, ally); + spawnHealParticles(caster.worldObj, ally); } } } @@ -112,8 +112,8 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if ((world.isRemote && !isPreview()) || instantHeal) return; + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if ((caster.worldObj.isRemote && !isPreview()) || instantHeal) return; // Heal over time - distribute heal across duration ticks if (tick % 10 == 0) { @@ -128,7 +128,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } caster.heal(selfTickHeal); if (tick % 20 == 0) { - spawnHealParticles(world, caster); + spawnHealParticles(caster.worldObj, caster); } } @@ -142,7 +142,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } ally.heal(allyTickHeal); if (tick % 20 == 0) { - spawnHealParticles(world, ally); + spawnHealParticles(caster.worldObj, ally); } } } 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 cf49cade6..367b534c7 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 @@ -9,7 +9,6 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityHeavyHit; @@ -28,6 +27,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { private float knockback = 2.0f; private float hitLength = 4.0f; // How far in front of the caster the hit reaches private float hitWidth = 3.0f; // How wide to each side (total width = hitWidth * 2) + private int activeDisplayTicks = 10; // How long active animation plays before completing public AbilityHeavyHit() { this.typeId = "ability.cnpc.heavy_hit"; @@ -67,8 +67,8 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) { signalCompletion(); return; } @@ -84,7 +84,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { // Search area: AABB that encompasses the rectangle float searchDist = Math.max(hitLength, hitWidth) + 1.0f; @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity( + List entities = caster.worldObj.getEntitiesWithinAABBExcludingEntity( caster, caster.boundingBox.expand(searchDist, 2, searchDist)); boolean anyHit = false; @@ -113,15 +113,14 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { // Play hit sound even if nothing was hit (the attack still happens) if (!anyHit) { - world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + caster.worldObj.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); } } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Just enough delay to see the active animation - if (tick == 10) + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (tick >= activeDisplayTicks) signalCompletion(); } @@ -131,6 +130,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { nbt.setFloat("knockback", knockback); nbt.setFloat("hitLength", hitLength); nbt.setFloat("hitWidth", hitWidth); + nbt.setInteger("activeDisplayTicks", activeDisplayTicks); } @Override @@ -139,6 +139,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.knockback = nbt.getFloat("knockback"); this.hitLength = nbt.getFloat("hitLength"); this.hitWidth = nbt.getFloat("hitWidth"); + this.activeDisplayTicks = nbt.hasKey("activeDisplayTicks") ? nbt.getInteger("activeDisplayTicks") : 10; } // Getters & Setters @@ -174,6 +175,14 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.hitWidth = hitWidth; } + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { @@ -187,6 +196,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { FieldDef.floatField("ability.hitLength", this::getHitLength, this::setHitLength), FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) ), + FieldDef.intField("ability.activeDisplayTicks", this::getActiveDisplayTicks, this::setActiveDisplayTicks).range(1, 200), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index 2bca3d681..3ce1e33fb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -2,50 +2,42 @@ package kamkeel.npcs.controllers.data.ability.type; 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.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +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.EntityAbilityLaser; -import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; import net.minecraft.util.Vec3; -import net.minecraft.world.World; import noppes.npcs.api.ability.type.IAbilityLaserShot; +import noppes.npcs.client.gui.builder.FieldDef; -import java.util.Arrays; import java.util.List; /** * Laser Shot ability: Fast expanding thin line that pierces through targets. * Travels in a straight line from origin, damaging all entities it passes through. + * Single-projectile only (always projectileCount=1). */ -public class AbilityLaserShot extends Ability implements IAbilityLaserShot { +public class AbilityLaserShot extends AbstractEnergyProjectileAbility implements IAbilityLaserShot { - // Laser properties private float laserWidth = 0.3f; private float expansionSpeed = 3.0f; private int lingerTicks = 8; - // Data classes - private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); - private final EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Transient state for laser entity (used for movement locking) - private transient EntityAbilityLaser laserEntity = null; - public AbilityLaserShot() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f), + new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f), + new EnergyHomingData(), + new EnergyLifespanData(40.0f, 100) + ); this.typeId = "ability.cnpc.laser_shot"; this.name = "Laser Shot"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -58,14 +50,15 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { this.rotationPhase = LockMovementType.WINDUP; this.telegraphType = TelegraphType.LINE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Laser_Windup"; this.activeAnimationName = "Ability_Laser_Active"; } + // ==================== OVERRIDES ==================== + @Override - public boolean allowOverlap() { - return true; + protected AnchorPoint getDefaultAnchor(int index) { + return AnchorPoint.FRONT; } @Override @@ -74,8 +67,34 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { } @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + public int getMaxPreviewDuration() { + return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; + } + + /** + * LINE telegraph: positioned at caster, aimed toward target. + * Overrides the circle telegraph from AbstractEnergyProjectileAbility. + */ + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster)) { + return null; + } + + Telegraph telegraph = Telegraph.line(getTelegraphLength(), getTelegraphWidth()); + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, caster.posY, caster.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(caster.getEntityId()); + if (target != null) { + instance.setTargetEntityId(target.getEntityId()); + } + return instance; } @Override @@ -85,242 +104,99 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { @Override public float getTelegraphWidth() { - return laserWidth * 2.0f; // Make telegraph slightly wider for visibility + return laserWidth * 2.0f; } - /** - * Spawn laser entity. - * NPC: target is the aggro target — laser expands toward it. - * Player: target is null — laser expands in caster's look direction. - */ - private EntityAbilityLaser spawnLaserEntity(EntityLivingBase caster, EntityLivingBase target, World world) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - EntityAbilityLaser entity = new EntityAbilityLaser( - world, caster, target, + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityLaser createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityLaser( + caster.worldObj, caster, target, spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, laserWidth, - colorData, combatData, lightningData, lifespanData, trajectoryData, - expansionSpeed, lingerTicks - ); - entity.setEffects(this.effects); - entity.setSourceAbility(this); - spawnAbilityEntity(world, entity); - return entity; + resolved, combatData, lightningData, lifespanData, trajectoryData, + expansionSpeed, lingerTicks); } - private void fireLaserEntity(EntityAbilityLaser laser, EntityLivingBase target) { - if (laser == null || laser.isDead) return; + @Override + protected void fireEntity(EntityAbilityLaser laser, EntityLivingBase target) { laser.setLockVerticalDirection(true); laser.startMoving(target); } @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - laserEntity = spawnLaserEntity(caster, target, world); - if (isPreview()) { - laserEntity.setupPreview(caster, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); - } else { - laserEntity.setupCharging(anchorData, windUpTicks); - } - } + protected void setupEntityCharging(EntityAbilityLaser laser, ProjectileData projData, int index) { + laser.setupCharging(projData.anchor, windUpTicks); } @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - laserEntity = spawnLaserEntity(caster, target, world); - fireLaserEntity(laserEntity, target); + protected void setupEntityPreview(EntityAbilityLaser laser, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + laser.setupPreview(caster, laserWidth, resolved, lightningData, expansionSpeed, lifespanData.maxDistance); } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (laserEntity == null) { - signalCompletion(); - return; - } - - fireLaserEntity(laserEntity, target); + protected EntityAbilityLaser[] createEntityArray(int size) { + return new EntityAbilityLaser[size]; } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (laserEntity == null || laserEntity.isDead) { - laserEntity = null; - signalCompletion(); - } + protected float getProjectileTelegraphRadius() { + return laserWidth * 2.0f; } - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } + // ==================== TYPE-SPECIFIC NBT ==================== @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn laser entity if still alive - if (laserEntity != null && !laserEntity.isDead) { - laserEntity.setDead(); - } - laserEntity = null; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("laserWidth", laserWidth); nbt.setFloat("expansionSpeed", expansionSpeed); nbt.setInteger("lingerTicks", lingerTicks); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); } @Override - public void readTypeNBT(NBTTagCompound nbt) { + protected void readTypeSpecificNBT(NBTTagCompound nbt) { this.laserWidth = nbt.getFloat("laserWidth"); this.expansionSpeed = nbt.getFloat("expansionSpeed"); this.lingerTicks = nbt.getInteger("lingerTicks"); - anchorData.readNBT(nbt); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); } - // Getters & Setters - Standalone fields + // ==================== TYPE-SPECIFIC GETTERS ==================== + public float getLaserWidth() { return laserWidth; } public void setLaserWidth(float laserWidth) { this.laserWidth = laserWidth; } + public float getExpansionSpeed() { return expansionSpeed; } public void setExpansionSpeed(float expansionSpeed) { this.expansionSpeed = expansionSpeed; } + public int getLingerTicks() { return lingerTicks; } public void setLingerTicks(int lingerTicks) { this.lingerTicks = lingerTicks; } - // Getters & Setters - Lifespan data - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - // Getters & Setters - Color data - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { this.colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { this.colorData.outerColor = outerColor; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { this.colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { this.colorData.outerColorAlpha = outerColorAlpha; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { this.colorData.outerColorEnabled = outerColorEnabled; } - - // Getters & Setters - Lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { this.lightningData.lightningEffect = lightningEffect; } - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { this.lightningData.lightningDensity = lightningDensity; } - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; } - - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - public int getAnchorPoint() { - return anchorData.anchorPoint.ordinal(); - } - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; - } + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.row( - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.floatField("ability.knockbackUp", this::getKnockbackUp, this::setKnockbackUp) - ), - FieldDef.section("ability.section.beam"), - FieldDef.row( - FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth), - FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed) - ), - FieldDef.row( - FieldDef.intField("ability.lingerTicks", this::getLingerTicks, this::setLingerTicks), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX) - .min(Float.NEGATIVE_INFINITY), - FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) - .min(Float.NEGATIVE_INFINITY) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) - .min(Float.NEGATIVE_INFINITY).tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + protected void addTypeDefinitions(List defs) { + defs.add(FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.floatField("ability.knockbackUp", this::getKnockbackUp, this::setKnockbackUp) )); + defs.add(FieldDef.section("ability.section.beam")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth), + FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed) + )); + defs.add(FieldDef.row( + FieldDef.intField("ability.lingerTicks", this::getLingerTicks, this::setLingerTicks), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 7bc4bd8ef..42f24757e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -2,60 +2,37 @@ package kamkeel.npcs.controllers.data.ability.type; 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.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityOrb; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** * Orb ability: Spawns homing projectile sphere(s) that track target. * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ -public class AbilityOrb extends Ability implements IAbilityOrb { +public class AbilityOrb extends AbstractEnergyProjectileAbility implements IAbilityOrb { - private static final int MAX_PROJECTILES = 8; - - // Orb properties private float orbSize = 1.0f; - // Projectile count and fire stagger - private int projectileCount = 1; - private int fireDelay = 0; - - // Shared visual data (all projectiles use these) - private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Shared combat/movement data - private final EnergyCombatData combatData = new EnergyCombatData(); - private final EnergyHomingData homingData = new EnergyHomingData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(); - - // Per-projectile data (anchor + optional color override) - private ProjectileData[] projectiles; - - // Transient entity state - private transient EntityAbilityOrb[] orbEntities; - public AbilityOrb() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f), + new EnergyCombatData(), + new EnergyHomingData(), + new EnergyLifespanData() + ); this.typeId = "ability.cnpc.orb"; this.name = "Orb"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -68,57 +45,50 @@ public class AbilityOrb extends Ability implements IAbilityOrb { this.showTelegraph = true; this.windUpAnimationName = "Ability_Orb_Windup"; this.activeAnimationName = "Ability_Orb_Active"; - initProjectiles(1); } - private void initProjectiles(int count) { - this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - this.projectiles = new ProjectileData[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityOrb createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityOrb( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData); + } + + @Override + protected void fireEntity(EntityAbilityOrb orb, EntityLivingBase target) { + if (isPreview()) { + orb.startPreviewFiring(); + } else { + orb.startMoving(target); } } - private AnchorPoint getDefaultAnchor(int index) { - switch (index) { - case 0: return AnchorPoint.RIGHT_HAND; - case 1: return AnchorPoint.LEFT_HAND; - default: return AnchorPoint.FRONT; - } + @Override + protected void setupEntityCharging(EntityAbilityOrb orb, ProjectileData projData, int index) { + orb.setupCharging(projData.anchor, windUpTicks); } - public void setProjectileCount(int count) { - int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); - if (newCount == projectileCount) return; - - ProjectileData[] oldProjectiles = projectiles; - initProjectiles(newCount); - - // Preserve existing projectile data - if (oldProjectiles != null) { - int copyCount = Math.min(oldProjectiles.length, newCount); - for (int i = 0; i < copyCount; i++) { - if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; - } - } + @Override + protected void setupEntityPreview(EntityAbilityOrb orb, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + orb.setupPreview(caster, orbSize, resolved, lightningData, projData.anchor, windUpTicks); } - public int getProjectileCount() { - return projectileCount; + @Override + protected EntityAbilityOrb[] createEntityArray(int size) { + return new EntityAbilityOrb[size]; } - public int getFireDelay() { - return fireDelay; + @Override + protected float getProjectileTelegraphRadius() { + return orbSize * 1.5f; } - public void setFireDelay(int delay) { - this.fireDelay = Math.max(0, delay); - } - - /** @deprecated Use {@link #getFireDelay()} */ - public int getDualFireDelay() { return fireDelay; } - /** @deprecated Use {@link #setFireDelay(int)} */ - public void setDualFireDelay(int delay) { setFireDelay(delay); } + // ==================== VARIANTS ==================== @Override public List getVariants() { @@ -153,244 +123,19 @@ public class AbilityOrb extends Ability implements IAbilityOrb { ); } - @Override - public boolean allowOverlap() { - return true; - } + // ==================== TYPE-SPECIFIC NBT ==================== @Override - public boolean isReadyForBurstCompletion(int activeTick) { - return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - /** - * Create orb entities. - * NPC: target is the aggro target — orbs will home toward it. - * Player: target is null — orbs fire in caster's look direction. - */ - private EntityAbilityOrb[] createOrbEntities(EntityLivingBase caster, EntityLivingBase target, World world) { - EntityAbilityOrb[] entities = new EntityAbilityOrb[projectileCount]; - for (int i = 0; i < projectileCount; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - entities[i] = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - resolved, combatData, homingData, lightningData, lifespanData, trajectoryData); - entities[i].setEffects(this.effects); - entities[i].setSourceAbility(this); - } - if (projectileCount == 2 && entities[0] != null && entities[1] != null) { - entities[0].setSiblingEntityId(entities[1].getEntityId()); - entities[1].setSiblingEntityId(entities[0].getEntityId()); - } - return entities; - } - - private void fireOrbEntity(EntityAbilityOrb orb, EntityLivingBase target) { - if (orb == null || orb.isDead) return; - if (isPreview()) { - orb.startPreviewFiring(); - } else { - orb.startMoving(target); - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote && !isPreview()) return; - - if (tick == 1) { - orbEntities = createOrbEntities(caster, target, world); - for (int i = 0; i < projectileCount; i++) { - EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); - if (isPreview()) { - orbEntities[i].setupPreview(caster, orbSize, resolved, lightningData, projectiles[i].anchor, windUpTicks); - } else { - orbEntities[i].setupCharging(projectiles[i].anchor, windUpTicks); - } - spawnAbilityEntity(world, orbEntities[i]); - } - } - } - - @Override - public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { - orbEntities = createOrbEntities(caster, target, world); - for (EntityAbilityOrb orb : orbEntities) { - spawnAbilityEntity(world, orb); - } - - // Fire first projectile immediately, let onActiveTick handle the rest with fireDelay - fireOrbEntity(orbEntities[0], target); - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireOrbEntity(orbEntities[i], target); - } - } - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - - if (orbEntities == null) return; - - // Fire first projectile immediately - fireOrbEntity(orbEntities[0], target); - - // Fire remaining projectiles if no delay - if (fireDelay <= 0) { - for (int i = 1; i < projectileCount; i++) { - fireOrbEntity(orbEntities[i], target); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (orbEntities == null) { - signalCompletion(); - return; - } - - // Fire staggered projectiles - if (fireDelay > 0) { - for (int i = 1; i < projectileCount; i++) { - if (tick == fireDelay * i) { - fireOrbEntity(orbEntities[i], target); - } - } - } - - // Check if all entities are dead - boolean allDead = true; - for (EntityAbilityOrb orb : orbEntities) { - if (orb != null && !orb.isDead) { - allDead = false; - break; - } - } - if (allDead) { - signalCompletion(); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - if (orbEntities != null) { - for (int i = 0; i < orbEntities.length; i++) { - if (orbEntities[i] != null && !orbEntities[i].isDead) { - orbEntities[i].setDead(); - } - orbEntities[i] = null; - } - } - orbEntities = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - // NPC: telegraph on aggro target position - // Player: no telegraph (orbs fire in look direction, no fixed position to mark) - if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { - return null; - } - - Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return orbSize * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("orbSize", orbSize); - nbt.setInteger("projectileCount", projectileCount); - nbt.setInteger("fireDelay", fireDelay); - - // Shared visual data - displayData.writeNBT(nbt); - lightningData.writeNBT(nbt); - - // Shared combat/movement data - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - // Per-projectile data - for (int i = 0; i < projectileCount; i++) { - NBTTagCompound projNbt = new NBTTagCompound(); - projectiles[i].writeNBT(projNbt); - nbt.setTag("Projectile_" + i, projNbt); - } - } @Override - public void readTypeNBT(NBTTagCompound nbt) { + protected void readTypeSpecificNBT(NBTTagCompound nbt) { this.orbSize = nbt.getFloat("orbSize"); - - int count = nbt.getInteger("projectileCount"); - initProjectiles(count); - - this.fireDelay = nbt.getInteger("fireDelay"); - - // Shared combat/movement data - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - // Shared visual data - displayData.readNBT(nbt); - lightningData.readNBT(nbt); - - // Per-projectile data - for (int i = 0; i < projectileCount; i++) { - if (nbt.hasKey("Projectile_" + i)) { - projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); - } - } } - // ═══════════════════════════════════════════════════════════════════ - // API GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ + // ==================== TYPE-SPECIFIC GETTERS ==================== public float getOrbSpeed() { return homingData.speed; } public void setOrbSpeed(float speed) { homingData.speed = speed; } @@ -398,139 +143,16 @@ public class AbilityOrb extends Ability implements IAbilityOrb { public float getOrbSize() { return orbSize; } public void setOrbSize(float size) { this.orbSize = size; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float d) { lifespanData.maxDistance = d; } - - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } - - public float getDamage() { return combatData.damage; } - public void setDamage(float d) { combatData.damage = d; } - - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float k) { combatData.knockback = k; } - - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float k) { combatData.knockbackUp = k; } - - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean h) { homingData.homing = h; } - - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float s) { homingData.homingStrength = s; } - - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float r) { homingData.homingRange = r; } - - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean e) { combatData.explosive = e; } - - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float r) { combatData.explosionRadius = r; } - - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } - - // Shared display data (primary colors) - public int getInnerColor() { return displayData.innerColor; } - public void setInnerColor(int c) { displayData.innerColor = c; } - - public int getOuterColor() { return displayData.outerColor; } - public void setOuterColor(int c) { displayData.outerColor = c; } - - public float getOuterColorWidth() { return displayData.outerColorWidth; } - public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } - - public float getOuterColorAlpha() { return displayData.outerColorAlpha; } - public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } - - public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } - public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } - - public float getRotationSpeed() { return displayData.rotationSpeed; } - public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } - - // Shared lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } - - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float d) { lightningData.lightningDensity = d; } - - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float r) { lightningData.lightningRadius = r; } - - public int getLightningFadeTime() { return lightningData.lightningFadeTime; } - public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } - - // Anchor - default to projectile 0 - public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } - public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } - - public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } - public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } - - public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } - public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } - - public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } - public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } - - public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } - @Override - public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - - // Indexed API methods - public int getInnerColor(int index) { - ProjectileData p = projectiles[clampIndex(index)]; - return p.colorOverride ? p.innerColor : displayData.innerColor; - } - public void setInnerColor(int index, int color) { - ProjectileData p = projectiles[clampIndex(index)]; - p.colorOverride = true; - p.innerColor = color; - } - - public int getOuterColor(int index) { - ProjectileData p = projectiles[clampIndex(index)]; - return p.colorOverride ? p.outerColor : displayData.outerColor; - } - public void setOuterColor(int index, int color) { - ProjectileData p = projectiles[clampIndex(index)]; - p.colorOverride = true; - p.outerColor = color; - } - - public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } - public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } - public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } - public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } - - private int clampIndex(int index) { - return Math.max(0, Math.min(index, projectileCount - 1)); - } - - @Override - public int getMaxPreviewDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - // Type tab - projectile count and fire delay + protected void addTypeDefinitions(List defs) { defs.add(FieldDef.row( FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) .range(0, 200).visibleWhen(() -> projectileCount > 1) )); - - // Type tab - orb properties defs.add(FieldDef.row( FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) @@ -550,64 +172,5 @@ public class AbilityOrb extends Ability implements IAbilityOrb { defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); - - // Visual tab - shared primary colors - defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); - defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual")); - defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual")); - defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual")); - - // Visual tab - shared effects - defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); - defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual")); - defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual")); - defs.add(FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual")); - - // Visual tab - per-projectile sections - for (int i = 0; i < MAX_PROJECTILES; i++) { - final int idx = i; - String sectionKey = "ability.section.projectile" + (i + 1); - - defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") - .visibleWhen(() -> idx < projectileCount)); - - // Anchor point - defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, - v -> projectiles[idx].anchor.anchorOffsetX = v).min(Float.NEGATIVE_INFINITY), - FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, - v -> projectiles[idx].anchor.anchorOffsetY = v).min(Float.NEGATIVE_INFINITY) - ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); - defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, - v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); - - // Color override (only when multiple projectiles) - defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); - defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); - defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); - } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index d79f783d1..46242fc71 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -67,18 +67,18 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) { signalCompletion(); return; } if (isPlayerCaster(caster)) { // Player: instant hit-scan in look direction - executePlayerProjectile(caster, world); + executePlayerProjectile(caster, caster.worldObj); } else if (target != null) { // NPC: instant hit-scan on aggro target - executeNpcProjectile(caster, target, world); + executeNpcProjectile(caster, target, caster.worldObj); } signalCompletion(); @@ -250,7 +250,7 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Projectile is instant, nothing to do per-tick } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 17fdecceb..1eebdab99 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -10,7 +10,6 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; -import net.minecraft.world.World; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; @@ -30,6 +29,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { private float pushStrength = 1.5f; private float damage = 8.0f; private int maxTargets = 10; + private int activeDisplayTicks = 10; public AbilityShockwave() { this.typeId = "ability.cnpc.shockwave"; @@ -62,14 +62,14 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { if (!isPreview()) { // Shockwave is instant - apply effect immediately after windup // Get all entities in radius AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); int count = 0; for (EntityLivingBase entity : entities) { @@ -112,8 +112,8 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (tick == 10) + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (tick >= activeDisplayTicks) signalCompletion(); } @@ -123,6 +123,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { nbt.setFloat("pushStrength", pushStrength); nbt.setFloat("damage", damage); nbt.setInteger("maxTargets", maxTargets); + nbt.setInteger("activeDisplayTicks", activeDisplayTicks); } @Override @@ -131,6 +132,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.pushStrength = nbt.getFloat("pushStrength"); this.damage = nbt.getFloat("damage"); this.maxTargets = nbt.getInteger("maxTargets"); + this.activeDisplayTicks = nbt.hasKey("activeDisplayTicks") ? nbt.getInteger("activeDisplayTicks") : 10; } // Getters & Setters @@ -166,6 +168,14 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.maxTargets = maxTargets; } + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { @@ -177,6 +187,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { FieldDef.floatField("gui.strength", this::getPushStrength, this::setPushStrength) ), FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets), + FieldDef.intField("ability.activeDisplayTicks", this::getActiveDisplayTicks, this::setActiveDisplayTicks).range(1, 200), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); } 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 22fd99416..f8a6559ca 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 @@ -84,7 +84,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (isPlayerCaster(caster)) { // Player: update target along look direction during windup if (targetingMode == TargetingMode.AOE_SELF) { @@ -115,7 +115,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { hasLaunched = false; hasLanded = false; airTicks = 0; @@ -286,7 +286,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (!hasLaunched) return; if (hasLanded) return; @@ -300,14 +300,14 @@ public class AbilitySlam extends Ability implements IAbilitySlam { // Check for landing: hit the ground or hit a wall mid-flight if (airTicks > 3) { if (caster.onGround || caster.isCollidedHorizontally) { - onLanding(caster, world); + onLanding(caster, caster.worldObj); return; } } // Timeout protection - force landing after max air time if (airTicks >= maxAirTicks) { - onLanding(caster, world); + onLanding(caster, caster.worldObj); return; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 43a152f7a..c7cc9a1fa 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -14,7 +14,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilitySweeper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; + import noppes.npcs.api.ability.type.IAbilitySweeper; import java.util.Arrays; @@ -77,16 +77,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { // Spawn the sweeper entity that handles BOTH visuals AND damage. // NPC: target is the aggro target — lockOnTarget tracks it during sweep. // Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect. - activeEntity = new EntityAbilitySweeper(world, caster, target, + activeEntity = new EntityAbilitySweeper(caster.worldObj, caster, target, beamLength, beamWidth, beamHeight, colorData, sweepSpeed, numberOfRotations, @@ -97,14 +92,14 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { activeEntity.setupPreview(caster); } - spawnAbilityEntity(world, activeEntity); + spawnAbilityEntity(activeEntity); // Ability stays active until entity dies (prevents firing another while projectile is alive) // Movement locking is handled separately by the base class } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Signal completion when entity dies if (activeEntity == null || activeEntity.isDead) { activeEntity = null; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index d9e05c382..70228652e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -97,13 +97,13 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { currentBlink = 0; ticksSinceLastBlink = blinkDelayTicks; // Trigger first blink immediately } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; if (currentBlink >= blinkLimit) { signalCompletion(); @@ -113,7 +113,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { ticksSinceLastBlink++; if (ticksSinceLastBlink >= blinkDelayTicks) { - performBlink(caster, target, world); + performBlink(caster, target, caster.worldObj); currentBlink++; ticksSinceLastBlink = 0; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 84bafc726..7766c3d45 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -5,7 +5,7 @@ import kamkeel.npcs.entity.EntityAbilityZone; import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; + import noppes.npcs.api.ability.type.IAbilityTrap; @@ -51,12 +51,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote && !isPreview()) { - signalCompletion(); - return; - } - + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { activeEntities.clear(); // Use pre-calculated positions from telegraph phase, or generate new ones @@ -78,7 +73,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { for (int i = 0; i < zoneCount; i++) { double[] pos = positions.get(i); - EntityAbilityZone entity = EntityAbilityZone.createTrap(world, caster, + EntityAbilityZone entity = EntityAbilityZone.createTrap(caster.worldObj, caster, pos[0], caster.posY, pos[1], zoneShape, triggerRadius, armTime, maxTriggers, triggerCooldown, @@ -94,7 +89,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { entity.setupPreview(caster); } - spawnAbilityEntity(world, entity); + spawnAbilityEntity(entity); activeEntities.add(entity); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index d9d253d29..f969c27cd 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -79,7 +79,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { getPulledEntities().clear(); pullComplete = false; ticksSincePullDamage = 0; @@ -88,7 +88,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { if (aoe) { AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); int count = 0; for (EntityLivingBase entity : entities) { @@ -116,7 +116,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (isPreview()) { // No entities to pull in preview, just run animation for a duration if (tick >= 60) signalCompletion(); @@ -136,7 +136,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { ticksSincePullDamage++; for (UUID uuid : new HashSet<>(getPulledEntities())) { - EntityLivingBase entity = findEntity(caster, world, uuid); + EntityLivingBase entity = findEntity(caster, caster.worldObj, uuid); if (entity == null || entity.isDead) { getPulledEntities().remove(uuid); continue; @@ -149,7 +149,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { if (dist <= 1.5f) { getPulledEntities().remove(uuid); - onTargetArrived(caster, entity, world); + onTargetArrived(caster, entity, caster.worldObj); continue; } @@ -164,7 +164,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double nextZ = dz * factor; AxisAlignedBB nextBox = entity.boundingBox.copy().offset(nextX, nextY, nextZ); - if (!world.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) { + if (!caster.worldObj.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) { getPulledEntities().remove(uuid); continue; } 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 9a296e836..438fd11d4 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 @@ -17,7 +17,7 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.constants.EnumPotionType; import net.minecraft.util.DamageSource; -import net.minecraft.world.World; + import noppes.npcs.client.gui.SubGuiZonePresetSelector; import noppes.npcs.client.gui.builder.FieldDef; @@ -151,7 +151,7 @@ public abstract class AbilityZone extends Ability { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Remove dead entities Iterator it = activeEntities.iterator(); while (it.hasNext()) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java new file mode 100644 index 000000000..da48a2d97 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java @@ -0,0 +1,590 @@ +package kamkeel.npcs.controllers.data.ability.type; + +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.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +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.EntityAbilityProjectile; +import kamkeel.npcs.util.AnchorPointHelper; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; +import noppes.npcs.api.ability.type.IAbilityEnergyProjectile; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for energy projectile abilities (Orb, Disc, Beam, LaserShot). + * Handles shared lifecycle (windup → execute → active → completion), multi-projectile + * support with staggered firing, telegraph creation, NBT persistence, and GUI definitions. + * + * Subclasses provide entity creation/firing/charging logic and type-specific fields. + * + * @param The entity type this ability spawns + */ +public abstract class AbstractEnergyProjectileAbility + extends Ability implements IAbilityEnergyProjectile { + + protected static final int MAX_PROJECTILES = 8; + + // Multi-projectile support + protected int projectileCount = 1; + protected int fireDelay = 0; + + // Shared visual data + protected EnergyDisplayData displayData; + protected EnergyLightningData lightningData; + protected EnergyTrajectoryData trajectoryData; + + // Shared combat/movement data + protected final EnergyCombatData combatData; + protected final EnergyHomingData homingData; + protected final EnergyLifespanData lifespanData; + + // Per-projectile data (anchor + optional color override) + protected ProjectileData[] projectiles; + + // Transient entity state + protected transient E[] entities; + + // ==================== CONSTRUCTOR ==================== + + protected AbstractEnergyProjectileAbility( + EnergyDisplayData displayData, + EnergyCombatData combatData, + EnergyHomingData homingData, + EnergyLifespanData lifespanData + ) { + this.displayData = displayData; + this.combatData = combatData; + this.homingData = homingData; + this.lifespanData = lifespanData; + this.lightningData = new EnergyLightningData(); + this.trajectoryData = new EnergyTrajectoryData(); + initProjectiles(1); + } + + // ==================== ABSTRACT METHODS ==================== + + /** + * Create a single entity for the given projectile index. + * Called during windup (tick 1) and burst refire (onExecute when entities are null). + */ + protected abstract E createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index); + + /** + * Fire an entity (start moving toward target). Entity is guaranteed non-null and alive. + */ + protected abstract void fireEntity(E entity, EntityLivingBase target); + + /** + * Setup entity for charging animation during windup (non-preview). + */ + protected abstract void setupEntityCharging(E entity, ProjectileData projData, int index); + + /** + * Setup entity for preview mode during windup. + */ + protected abstract void setupEntityPreview(E entity, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index); + + /** + * Create typed array (Java generics can't create generic arrays). + */ + protected abstract E[] createEntityArray(int size); + + /** + * Get the telegraph radius for this projectile type. + */ + protected abstract float getProjectileTelegraphRadius(); + + /** + * Add type-specific GUI field definitions (Type tab). + * Called before shared visual tab definitions. + */ + @SideOnly(Side.CLIENT) + protected abstract void addTypeDefinitions(List defs); + + /** + * Write type-specific fields to NBT (e.g., orbSize, discRadius). + * Shared data classes are written by the base class. + */ + protected abstract void writeTypeSpecificNBT(NBTTagCompound nbt); + + /** + * Read type-specific fields from NBT. + * Shared data classes are read by the base class. + */ + protected abstract void readTypeSpecificNBT(NBTTagCompound nbt); + + // ==================== OVERRIDABLE HOOKS ==================== + + /** + * Get the default anchor point for a projectile index. + * Override for types with different anchor defaults. + */ + protected AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + /** + * Get the spawn position for a projectile. Override for types that need + * an offset distance (e.g., Beam uses offsetDist=1.0). + */ + protected Vec3 getSpawnPosition(EntityLivingBase caster, int index) { + return AnchorPointHelper.calculateAnchorPosition(caster, projectiles[index].anchor); + } + + // ==================== PROJECTILE MANAGEMENT ==================== + + protected void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { return projectileCount; } + + public int getFireDelay() { return fireDelay; } + public void setFireDelay(int delay) { this.fireDelay = Math.max(0, delay); } + + /** @deprecated Use {@link #getFireDelay()} */ + public int getDualFireDelay() { return fireDelay; } + /** @deprecated Use {@link #setFireDelay(int)} */ + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + protected int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); + } + + // ==================== ENTITY CREATION ==================== + + /** + * Create all entities for this ability. + * Sets effects, source ability, and sibling links. + */ + protected E[] createAllEntities(EntityLivingBase caster, EntityLivingBase target) { + E[] newEntities = createEntityArray(projectileCount); + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = getSpawnPosition(caster, i); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + newEntities[i] = createEntity(caster, target, spawnPos, resolved, i); + newEntities[i].setEffects(this.effects); + newEntities[i].setSourceAbility(this); + } + return newEntities; + } + + /** + * Fire an entity if it's valid. + */ + protected void fireEntitySafe(E entity, EntityLivingBase target) { + if (entity != null && !entity.isDead) { + fireEntity(entity, target); + } + } + + // ==================== LIFECYCLE ==================== + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (caster.worldObj.isRemote && !isPreview()) return; + + if (tick == 1) { + entities = createAllEntities(caster, target); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + setupEntityPreview(entities[i], caster, resolved, projectiles[i], i); + } else { + setupEntityCharging(entities[i], projectiles[i], i); + } + spawnAbilityEntity(entities[i]); + } + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // Burst refire: entities not created during windup (it was skipped) + if (entities == null) { + entities = createAllEntities(caster, target); + for (E entity : entities) { + spawnAbilityEntity(entity); + } + } + + // Fire first projectile immediately + fireEntitySafe(entities[0], target); + + // Fire remaining projectiles if no delay + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireEntitySafe(entities[i], target); + } + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (entities == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireEntitySafe(entities[i], target); + } + } + } + + // Check if all entities are dead + boolean allDead = true; + for (E entity : entities) { + if (entity != null && !entity.isDead) { + allDead = false; + break; + } + } + if (allDead) { + signalCompletion(); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + if (entities != null) { + for (int i = 0; i < entities.length; i++) { + if (entities[i] != null && !entities[i].isDead) { + entities[i].setDead(); + } + entities[i] = null; + } + } + entities = null; + } + + // ==================== TELEGRAPH ==================== + + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { + return null; + } + + Telegraph telegraph = Telegraph.circle(getProjectileTelegraphRadius()); + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(target.getEntityId()); + + return instance; + } + + @Override + public float getTelegraphRadius() { + return getProjectileTelegraphRadius(); + } + + // ==================== NBT ==================== + + @Override + public final void writeTypeNBT(NBTTagCompound nbt) { + // Type-specific fields + writeTypeSpecificNBT(nbt); + + // Shared fields + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared data classes + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + combatData.writeNBT(nbt); + homingData.writeNBT(nbt); + lifespanData.writeNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } + } + + @Override + public final void readTypeNBT(NBTTagCompound nbt) { + // Type-specific fields + readTypeSpecificNBT(nbt); + + // Shared fields + int count = nbt.getInteger("projectileCount"); + initProjectiles(count); + this.fireDelay = nbt.getInteger("fireDelay"); + + // Shared data classes + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + combatData.readNBT(nbt); + homingData.readNBT(nbt); + lifespanData.readNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } + + // ==================== PREVIEW ==================== + + @Override + public int getMaxPreviewDuration() { + return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; + } + + // ==================== API GETTERS & SETTERS ==================== + + // Combat data + @Override public float getDamage() { return combatData.damage; } + @Override public void setDamage(float damage) { combatData.damage = damage; } + + @Override public float getKnockback() { return combatData.knockback; } + @Override public void setKnockback(float knockback) { combatData.knockback = knockback; } + + @Override public float getKnockbackUp() { return combatData.knockbackUp; } + @Override public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } + + @Override public boolean isExplosive() { return combatData.explosive; } + @Override public void setExplosive(boolean explosive) { combatData.explosive = explosive; } + + @Override public float getExplosionRadius() { return combatData.explosionRadius; } + @Override public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } + + @Override public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + @Override public void setExplosionDamageFalloff(float falloff) { combatData.explosionDamageFalloff = falloff; } + + // Lifespan data + @Override public float getMaxDistance() { return lifespanData.maxDistance; } + @Override public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } + + @Override public int getMaxLifetime() { return lifespanData.maxLifetime; } + @Override public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } + + // Homing data + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean homing) { homingData.homing = homing; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float strength) { homingData.homingStrength = strength; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float range) { homingData.homingRange = range; } + + // Display data - primary colors + @Override public int getInnerColor() { return displayData.innerColor; } + @Override public void setInnerColor(int color) { displayData.innerColor = color; } + + @Override public int getOuterColor() { return displayData.outerColor; } + @Override public void setOuterColor(int color) { displayData.outerColor = color; } + + @Override public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + @Override public void setOuterColorEnabled(boolean enabled) { displayData.outerColorEnabled = enabled; } + + @Override public float getOuterColorWidth() { return displayData.outerColorWidth; } + @Override public void setOuterColorWidth(float width) { displayData.outerColorWidth = width; } + + @Override public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + @Override public void setOuterColorAlpha(float alpha) { displayData.outerColorAlpha = alpha; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float speed) { displayData.rotationSpeed = speed; } + + // Lightning data + @Override public boolean hasLightningEffect() { return lightningData.lightningEffect; } + @Override public void setLightningEffect(boolean enabled) { lightningData.lightningEffect = enabled; } + + @Override public float getLightningDensity() { return lightningData.lightningDensity; } + @Override public void setLightningDensity(float density) { lightningData.lightningDensity = density; } + + @Override public float getLightningRadius() { return lightningData.lightningRadius; } + @Override public void setLightningRadius(float radius) { lightningData.lightningRadius = radius; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int fadeTime) { lightningData.lightningFadeTime = fadeTime; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint point) { projectiles[0].anchor.anchorPoint = point; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } + + @Override public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } + @Override public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } + + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } + + // ==================== GUI FIELD DEFINITIONS ==================== + + @SideOnly(Side.CLIENT) + @Override + public final void getAbilityDefinitions(List defs) { + // Type-specific fields first + addTypeDefinitions(defs); + + // Shared visual tab - primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Shared visual tab - effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Shared visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 488dfa39e..0fb58bcfe 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -45,10 +45,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Whether to render tail orb (only when anchored) private boolean renderTailOrb = true; - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; + // Charging state (beam-specific) private float chargeOffsetDistance = 1.0f; // Trail fading for non-anchored beams (comet effect) @@ -56,9 +53,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { private int trailFadeTime = 20; // Ticks for trail to fully fade private List trailPointAges = new ArrayList<>(); - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - // Debug logging private static final boolean DEBUG_LOGGING = false; @@ -66,34 +60,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if beam is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor with all parameters using data classes. * @param anchoredMode If true, origin follows owner and tail orb is rendered. @@ -137,23 +103,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { } // Calculate initial velocity toward target - if (target != null) { - double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; - double dz = target.posZ - z; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.motionX = (dx / len) * getSpeed(); - this.motionY = (dy / len) * getSpeed(); - this.motionZ = (dz / len) * getSpeed(); - } - } else { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - this.motionY = -Math.sin(pitch) * getSpeed(); - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } + calculateInitialVelocity(owner, target, x, y, z); } public void setupCharging(EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { @@ -218,8 +168,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - setCharging(false); // Origin (tail) stays at the charged position @@ -270,8 +218,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * For non-anchored beams: origin fixed at charged position, head starts there */ public void startFiring(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); // For player casters, snap to look vector for crosshair-aligned launch @@ -433,8 +379,10 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { /** * Update during charging state - follow owner based on anchor point. + * Beam-specific: positions based on chargeOffsetDistance and updates startX/Y/Z. */ - private void updateCharging() { + @Override + protected void updateCharging() { chargeTick++; Entity owner = getOwnerEntity(); @@ -548,7 +496,8 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { addTrailPoint(); } - private void updateHoming() { + @Override + protected void updateHoming() { if (!isHoming()) return; Entity target = getTargetEntity(); @@ -704,24 +653,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { return attachedToOwner; } - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - /** - * Get interpolated charge progress for smooth rendering. - */ - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - /** * Whether trail should fade (comet effect for non-anchored beams). */ @@ -757,12 +688,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { this.prevHeadOffsetZ = this.headOffsetZ; this.attachedToOwner = !nbt.hasKey("AttachedToOwner") || nbt.getBoolean("AttachedToOwner"); this.renderTailOrb = !nbt.hasKey("RenderTailOrb") || nbt.getBoolean("RenderTailOrb"); - // Read charging state and sync to data watcher - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + readChargingNBT(nbt); this.chargeOffsetDistance = nbt.hasKey("ChargeOffsetDistance") ? nbt.getFloat("ChargeOffsetDistance") : 1.0f; this.fadeTrail = nbt.hasKey("FadeTrail") && nbt.getBoolean("FadeTrail"); this.trailFadeTime = nbt.hasKey("TrailFadeTime") ? nbt.getInteger("TrailFadeTime") : 20; @@ -792,15 +718,11 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { nbt.setDouble("HeadOffsetZ", headOffsetZ); nbt.setBoolean("AttachedToOwner", attachedToOwner); nbt.setBoolean("RenderTailOrb", renderTailOrb); - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); + writeChargingNBT(nbt); nbt.setFloat("ChargeOffsetDistance", chargeOffsetDistance); nbt.setBoolean("FadeTrail", fadeTrail); nbt.setInteger("TrailFadeTime", trailFadeTime); - this.anchorData.writeNBT(nbt); - // Write trail points NBTTagList trailList = new NBTTagList(); for (Vec3 point : trailPoints) { diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index 04bf2b777..43fa459fc 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -33,48 +33,14 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { private float discThickness = 0.2f; // Height of disc private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; + // Charging state (disc-specific target sizes) private float targetDiscRadius = 1.0f; // Full radius to grow to during charging private float targetDiscThickness = 0.2f; // Full thickness to grow to during charging - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - public EntityAbilityDisc(World world) { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if disc is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor with all parameters using data classes. */ @@ -99,23 +65,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.discThickness = discThickness; // Calculate initial velocity toward target - if (target != null) { - double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; - double dz = target.posZ - z; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.motionX = (dx / len) * getSpeed(); - this.motionY = (dy / len) * getSpeed(); - this.motionZ = (dz / len) * getSpeed(); - } - } else { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - this.motionY = -Math.sin(pitch) * getSpeed(); - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } + calculateInitialVelocity(owner, target, x, y, z); } /** @@ -124,21 +74,12 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Position follows the owner based on anchor point. */ public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; - this.vertical = vertical; this.targetDiscRadius = this.discRadius; this.targetDiscThickness = this.discThickness; + super.setupCharging(anchor, chargeDuration); + this.vertical = vertical; this.discRadius = 0.01f; this.discThickness = 0.01f; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; } /** @@ -188,8 +129,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - setCharging(false); // Update start position to current position @@ -222,8 +161,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Called by ability when windup ends. */ public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); // For player casters, snap to look vector for crosshair-aligned launch @@ -359,43 +296,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.posZ += motionZ; } - private void updateHoming() { - if (!isHoming()) return; - - Entity target = getTargetEntity(); - if (target == null || !target.isEntityAlive()) return; - - double dx = target.posX - posX; - double dy = (target.posY + target.getEyeHeight()) - posY; - double dz = target.posZ - posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (dist <= getHomingRange() && dist > 0) { - // Calculate effective homing strength - increases when closer to commit to target - float effectiveStrength = getHomingStrength(); - if (dist < getHomingRange() * 0.3) { - effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); - } else if (dist < getHomingRange() * 0.6) { - effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); - } - - double desiredVX = (dx / dist) * getSpeed(); - double desiredVY = (dy / dist) * getSpeed(); - double desiredVZ = (dz / dist) * getSpeed(); - - motionX += (desiredVX - motionX) * effectiveStrength; - motionY += (desiredVY - motionY) * effectiveStrength; - motionZ += (desiredVZ - motionZ) * effectiveStrength; - - double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); - if (vLen > 0) { - motionX = (motionX / vLen) * getSpeed(); - motionY = (motionY / vLen) * getSpeed(); - motionZ = (motionZ / vLen) * getSpeed(); - } - } - } - private void updateReturnToOwner() { Entity owner = getOwnerEntity(); @@ -485,8 +385,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { /** * Update during charging state - follow owner based on anchor point. + * Overrides base to grow disc-specific radius/thickness instead of just size. */ - private void updateCharging() { + @Override + protected void updateCharging() { chargeTick++; Entity owner = getOwnerEntity(); @@ -511,24 +413,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { updateRotation(); } - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - /** - * Get interpolated charge progress for smooth rendering. - */ - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - // ==================== GETTERS ==================== public float getDiscRadius() { @@ -579,12 +463,8 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.discThickness = nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f; this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false; this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning"); - // Charging state - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + // Charging state (common fields handled by base) + readChargingNBT(nbt); this.targetDiscRadius = nbt.hasKey("TargetDiscRadius") ? nbt.getFloat("TargetDiscRadius") : this.discRadius; this.targetDiscThickness = nbt.hasKey("TargetDiscThickness") ? nbt.getFloat("TargetDiscThickness") : this.discThickness; } @@ -597,10 +477,8 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { nbt.setFloat("DiscThickness", discThickness); nbt.setBoolean("Vertical", vertical); nbt.setBoolean("Returning", returning); - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); + // Charging state (common fields handled by base) + writeChargingNBT(nbt); nbt.setFloat("TargetDiscRadius", targetDiscRadius); nbt.setFloat("TargetDiscThickness", targetDiscThickness); } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 8a1325a27..a10dae0b8 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -44,47 +44,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { // End point for rendering private double endX, endY, endZ; - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; - private float targetSize = 1.0f; // Full size to grow to during charging - - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - public EntityAbilityLaser(World world) { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if orb is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor with all parameters using data classes. */ @@ -131,25 +94,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endZ = z; } - /** - * Setup this orb in charging mode (for windup phase). - * The orb will grow from 0 to orbSize over chargeDuration ticks. - * Position follows the owner based on anchor point. - */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; - this.targetSize = this.size; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - } - @Override protected void updateRotation() { // Laser doesn't rotate @@ -252,8 +196,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); // Initialize from current anchor position @@ -322,44 +264,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } } - /** - * Update during charging state - follow owner based on anchor point. - */ - private void updateCharging() { - chargeTick++; - - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } - - // Grow size based on charge progress - float progress = getChargeProgress(); - this.size = targetSize * progress; - - // Calculate position based on anchor point, offset downward by half size to center - if (owner instanceof EntityLivingBase) { - Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); - setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - } - } - - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - private void checkEntityCollisionAlongLine() { // Expand search AABB by entity sizes to ensure we find all potential targets double expand = Math.max(laserWidth, 1.0); @@ -520,13 +424,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endY = nbt.getDouble("EndY"); this.endZ = nbt.getDouble("EndZ"); - // Charging state - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; - this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; + readChargingNBT(nbt); } @Override @@ -543,11 +441,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { nbt.setDouble("EndY", endY); nbt.setDouble("EndZ", endZ); - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); - nbt.setFloat("TargetSize", targetSize); + writeChargingNBT(nbt); } /** diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java index c461e9575..c85b7be40 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -20,47 +20,10 @@ import java.util.List; */ public class EntityAbilityOrb extends EntityAbilityProjectile { - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; - private float targetSize = 1.0f; // Full size to grow to during charging - - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - public EntityAbilityOrb(World world) { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if orb is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor using data classes for grouped parameters. */ @@ -77,43 +40,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { this.homingData = homing; // Calculate initial velocity toward target - if (target != null) { - double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; - double dz = target.posZ - z; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.motionX = (dx / len) * homing.speed; - this.motionY = (dy / len) * homing.speed; - this.motionZ = (dz / len) * homing.speed; - } - } else { - // Fire in NPC's facing direction - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * homing.speed; - this.motionY = -Math.sin(pitch) * homing.speed; - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * homing.speed; - } - } - - /** - * Setup this orb in charging mode (for windup phase). - * The orb will grow from 0 to orbSize over chargeDuration ticks. - * Position follows the owner based on anchor point. - */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; - this.targetSize = this.size; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; + calculateInitialVelocity(owner, target, x, y, z); } /** @@ -161,8 +88,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - setCharging(false); // Update start position to current position @@ -196,8 +121,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Called by ability when windup ends. */ public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); // For player casters, snap to look vector for crosshair-aligned launch @@ -302,47 +225,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { return true; } - private void updateHoming() { - if (!isHoming()) return; - - Entity target = getTargetEntity(); - if (target == null || !target.isEntityAlive()) return; - - double dx = target.posX - posX; - double dy = (target.posY + target.getEyeHeight()) - posY; - double dz = target.posZ - posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (dist <= getHomingRange() && dist > 0) { - // Calculate effective homing strength - increases when closer to commit to target - // This prevents orbiting behavior at close range - float effectiveStrength = getHomingStrength(); - if (dist < getHomingRange() * 0.3) { - // Within 30% of homing range, dramatically increase strength to commit - effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); - } else if (dist < getHomingRange() * 0.6) { - // Within 60% of homing range, moderately increase strength - effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); - } - - double desiredVX = (dx / dist) * getSpeed(); - double desiredVY = (dy / dist) * getSpeed(); - double desiredVZ = (dz / dist) * getSpeed(); - - motionX += (desiredVX - motionX) * effectiveStrength; - motionY += (desiredVY - motionY) * effectiveStrength; - motionZ += (desiredVZ - motionZ) * effectiveStrength; - - // Normalize to maintain speed - double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); - if (vLen > 0) { - motionX = (motionX / vLen) * getSpeed(); - motionY = (motionY / vLen) * getSpeed(); - motionZ = (motionZ / vLen) * getSpeed(); - } - } - } - private void checkBlockCollision() { Vec3 currentPos = Vec3.createVectorHelper(posX, posY, posZ); Vec3 nextPos = Vec3.createVectorHelper(posX + motionX, posY + motionY, posZ + motionZ); @@ -387,47 +269,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { } } - /** - * Update during charging state - follow owner based on anchor point. - */ - private void updateCharging() { - chargeTick++; - - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } - - // Grow size based on charge progress - float progress = getChargeProgress(); - this.size = targetSize * progress; - - // Calculate position based on anchor point, offset downward by half size to center - if (owner instanceof EntityLivingBase) { - Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); - setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - } - } - - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - /** - * Get interpolated charge progress for smooth rendering. - */ - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - // ==================== GETTERS ==================== // Legacy getter for renderer compatibility @@ -439,22 +280,11 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { @Override protected void readProjectileNBT(NBTTagCompound nbt) { - // Charging state - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; - this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; + readChargingNBT(nbt); } @Override protected void writeProjectileNBT(NBTTagCompound nbt) { - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); - anchorData.writeNBT(nbt); - nbt.setFloat("TargetSize", targetSize); + writeChargingNBT(nbt); } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index e70b06009..9b30abab6 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -10,6 +10,7 @@ import kamkeel.npcs.controllers.data.ability.AbilityEffect; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.IAbilityDamageHandler; import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -74,7 +75,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP protected double startX, startY, startZ; protected int ownerEntityId = -1; protected int targetEntityId = -1; - protected int siblingEntityId = -1; // ==================== STATE ==================== protected boolean hasHit = false; @@ -84,6 +84,13 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP /** The ability that spawned this projectile. Transient, not saved to NBT. */ protected transient Ability sourceAbility = null; + // ==================== CHARGING STATE ==================== + protected boolean charging = false; + protected int chargeDuration = 40; + protected int chargeTick = 0; + protected float targetSize = 1.0f; + protected static final int DW_CHARGING = 20; + // ==================== ROTATION INTERPOLATION ==================== public float prevRotationValX, prevRotationValY, prevRotationValZ; public float rotationValX, rotationValY, rotationValZ; @@ -108,7 +115,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP /** * Initialize common properties using data classes. Call from subclass constructors. */ - protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, EntityAbilityProjectile sibling, + protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, double x, double y, double z, float size, EnergyDisplayData display, EnergyCombatData combat, EnergyLightningData lightning, EnergyLifespanData lifespan, @@ -120,7 +127,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.ownerEntityId = owner.getEntityId(); this.targetEntityId = target != null ? target.getEntityId() : -1; - this.siblingEntityId = sibling != null ? sibling.getEntityId() : -1; // Visual this.size = size; @@ -136,18 +142,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.prevRenderSize = size; } - // Initialize projectile without a sibling - protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, - double x, double y, double z, float size, - EnergyDisplayData display, EnergyCombatData combat, - EnergyLightningData lightning, EnergyLifespanData lifespan, - EnergyTrajectoryData trajectory) { - initProjectile(owner, target, null, x, y, z, size, display, combat, lightning, lifespan, trajectory); - } - @Override protected void entityInit() { - // No DataWatcher needed - using IEntityAdditionalSpawnData with NBT + this.dataWatcher.addObject(DW_CHARGING, (byte) 0); } @Override @@ -455,6 +452,170 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP prevPosZ = newZ; } + // ==================== CHARGING METHODS ==================== + + /** + * Check if entity is in charging state (synced via data watcher). + * In preview mode, uses local field since data watcher isn't synced. + */ + public boolean isCharging() { + if (previewMode) return this.charging; + return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; + } + + /** + * Set charging state (server only, synced to clients via data watcher). + */ + protected void setCharging(boolean value) { + this.charging = value; + if (!worldObj.isRemote) { + this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); + } + } + + public float getChargeProgress() { + if (chargeDuration <= 0) return 1.0f; + return Math.min(1.0f, (float) chargeTick / chargeDuration); + } + + public float getInterpolatedChargeProgress(float partialTicks) { + if (chargeDuration <= 0) return 1.0f; + float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); + float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); + return prevProgress + (currProgress - prevProgress) * partialTicks; + } + + /** + * Setup this entity in charging mode (for windup phase). + * Grows from 0 to current size over chargeDuration ticks. + * Subclasses with different charging behavior should override or use their own method. + */ + public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { + setCharging(true); + this.chargeDuration = chargeDuration; + this.chargeTick = 0; + this.anchorData = anchor; + this.targetSize = this.size; + this.size = 0.01f; + this.renderCurrentSize = 0.01f; + this.prevRenderSize = 0.01f; + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + } + + /** + * Update during charging state - grow size and follow anchor. + * Default implementation grows {@code size} from 0 to {@code targetSize}. + * Override in subclasses for type-specific charging (Disc, Beam). + */ + protected void updateCharging() { + chargeTick++; + Entity owner = getOwnerEntity(); + if (owner == null || owner.isDead) { + setDead(); + return; + } + float progress = getChargeProgress(); + this.size = targetSize * progress; + if (owner instanceof EntityLivingBase) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + } + } + + // ==================== HOMING ==================== + + /** + * Update homing toward target. Uses position-based homing with distance-scaled strength. + * Override in subclasses for type-specific homing (e.g. Beam uses head offset). + */ + protected void updateHoming() { + if (!isHoming()) return; + Entity target = getTargetEntity(); + if (target == null || !target.isEntityAlive()) return; + + double dx = target.posX - posX; + double dy = (target.posY + target.getEyeHeight()) - posY; + double dz = target.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + if (dist <= getHomingRange() && dist > 0) { + float effectiveStrength = getHomingStrength(); + if (dist < getHomingRange() * 0.3) { + effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); + } else if (dist < getHomingRange() * 0.6) { + effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); + } + + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); + + motionX += (desiredVX - motionX) * effectiveStrength; + motionY += (desiredVY - motionY) * effectiveStrength; + motionZ += (desiredVZ - motionZ) * effectiveStrength; + + double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + if (vLen > 0) { + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); + } + } + } + + // ==================== VELOCITY HELPERS ==================== + + /** + * Calculate initial velocity toward target or forward based on owner facing. + * Call from subclass constructors after initProjectile(). + */ + protected void calculateInitialVelocity(EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z) { + if (target != null) { + double dx = target.posX - x; + double dy = (target.posY + target.getEyeHeight()) - y; + double dz = target.posZ - z; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + this.motionX = (dx / len) * getSpeed(); + this.motionY = (dy / len) * getSpeed(); + this.motionZ = (dz / len) * getSpeed(); + } + } else { + float yaw = (float) Math.toRadians(owner.rotationYaw); + float pitch = (float) Math.toRadians(owner.rotationPitch); + this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + this.motionY = -Math.sin(pitch) * getSpeed(); + this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); + } + } + + // ==================== CHARGING NBT ==================== + + /** + * Read common charging state from NBT. Call from subclass readProjectileNBT(). + */ + protected void readChargingNBT(NBTTagCompound nbt) { + boolean isChargingVal = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); + this.charging = isChargingVal; + this.dataWatcher.updateObject(DW_CHARGING, (byte) (isChargingVal ? 1 : 0)); + this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; + this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; + } + + /** + * Write common charging state to NBT. Call from subclass writeProjectileNBT(). + */ + protected void writeChargingNBT(NBTTagCompound nbt) { + nbt.setBoolean("Charging", isCharging()); + nbt.setInteger("ChargeDuration", chargeDuration); + nbt.setInteger("ChargeTick", chargeTick); + nbt.setFloat("TargetSize", targetSize); + } + // ==================== ENTITY HELPERS ==================== public Entity getOwnerEntity() { @@ -502,26 +663,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP return NpcAPI.Instance().getIEntity(getTargetEntity()); } - @Override - public int getSiblingEntityId() { - return siblingEntityId; - } - - @Override - public void setSiblingEntityId(int siblingEntityId) { - if (!(worldObj.getEntityByID(siblingEntityId) instanceof EntityAbilityProjectile)) return; - - this.siblingEntityId = siblingEntityId; - } - - @Override - public IEnergyProjectile getSibling() { - if (siblingEntityId == -1) return null; - return (EntityAbilityProjectile) worldObj.getEntityByID(siblingEntityId); - } - /** * Check if an entity should be ignored for collision. + * Ignores: the owner, same-faction NPCs, and other projectiles from the same caster. */ protected boolean shouldIgnoreEntity(Entity entity) { Entity owner = getOwnerEntity(); @@ -533,8 +677,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP if (ownerNpc.faction.id == targetNpc.faction.id) return true; } - if (entity.getEntityId() == getSiblingEntityId()) - return true; + // Ignore other projectiles from the same caster (e.g. multi-projectile abilities) + if (entity instanceof EntityAbilityProjectile) { + EntityAbilityProjectile other = (EntityAbilityProjectile) entity; + if (other.ownerEntityId == this.ownerEntityId) return true; + } return false; } @@ -746,7 +893,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.ownerEntityId = nbt.getInteger("OwnerId"); this.targetEntityId = nbt.getInteger("TargetId"); - this.siblingEntityId = nbt.getInteger("SiblingId"); this.motionX = nbt.getDouble("MotionX"); this.motionY = nbt.getDouble("MotionY"); @@ -789,7 +935,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP nbt.setInteger("OwnerId", ownerEntityId); nbt.setInteger("TargetId", targetEntityId); - nbt.setInteger("SiblingId", targetEntityId); nbt.setDouble("MotionX", motionX); nbt.setDouble("MotionY", motionY); diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 9020b0ba8..8edcba628 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -186,7 +186,7 @@ public class DataAbilities { playAbilitySound(currentAbility.getWindUpSound()); playAbilityAnimation(currentAbility.getWindUpAnimation()); } - currentAbility.onWindUpTick(npc, target, npc.worldObj, currentAbility.getCurrentTick()); + currentAbility.onWindUpTick(npc, target, currentAbility.getCurrentTick()); break; case ACTIVE: @@ -221,11 +221,6 @@ public class DataAbilities { releaseLockedPosition(); } - // Burst re-fire without replay: let entity-spawning abilities spawn+fire in one step - if (oldPhase == AbilityPhase.BURST_DELAY && !currentAbility.isBurstReplayAnimations()) { - currentAbility.onBurstRefire(npc, target, npc.worldObj); - } - // Play active sound and animation // Abilities that keep telegraph during active manage their own sound timing if (!currentAbility.keepTelegraphDuringActive()) { @@ -247,7 +242,7 @@ public class DataAbilities { } // Call onExecute - currentAbility.onExecute(npc, target, npc.worldObj); + currentAbility.onExecute(npc, target); // Check if ability completed during onExecute (signalCompletion was called) if (currentAbility.getPhase() == AbilityPhase.IDLE) { @@ -255,7 +250,7 @@ public class DataAbilities { return; } } - currentAbility.onActiveTick(npc, target, npc.worldObj, currentAbility.getCurrentTick()); + currentAbility.onActiveTick(npc, target, currentAbility.getCurrentTick()); // Check if ability completed during onActiveTick (signalCompletion was called) if (currentAbility.getPhase() == AbilityPhase.IDLE) { @@ -554,7 +549,7 @@ public class DataAbilities { } // Call onExecute - ability.onExecute(npc, target, npc.worldObj); + ability.onExecute(npc, target); // Check if ability completed during onExecute if (ability.getPhase() == AbilityPhase.IDLE) { diff --git a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java index 7d856d916..6ed26666f 100644 --- a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java +++ b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java @@ -290,7 +290,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { private void tickWindup() { // Call the REAL windup tick method - previewAbility.onWindUpTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); + previewAbility.onWindUpTick(previewNpc, fakeTarget, currentTick); if (currentTick >= previewAbility.getWindUpTicks()) { transitionToActive(); @@ -299,7 +299,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { private void tickActive() { // Call the REAL active tick method - previewAbility.onActiveTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); + previewAbility.onActiveTick(previewNpc, fakeTarget, currentTick); // Simulate physics for movement abilities simulatePhysics(); @@ -330,7 +330,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { previewTelegraph = null; // Call the REAL onExecute method (fires entities, initiates movement, etc.) - previewAbility.onExecute(previewNpc, fakeTarget, previewNpc.worldObj); + previewAbility.onExecute(previewNpc, fakeTarget); // Start active animation Animation activeAnim = previewAbility.getActiveAnimation(); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 7807074f3..0f87ddf5a 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -161,7 +161,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { playAbilitySound(player, currentAbility.getWindUpSound()); playAbilityAnimation(currentAbility.getWindUpAnimation()); } - currentAbility.onWindUpTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); + currentAbility.onWindUpTick(player, currentTarget, currentAbility.getCurrentTick()); break; case ACTIVE: @@ -170,7 +170,10 @@ public class PlayerAbilityData implements IPlayerAbilityData { for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } - removeTelegraph(currentAbility, player); + // Remove telegraph unless the ability keeps it during active phase + if (!currentAbility.keepTelegraphDuringActive()) { + removeTelegraph(currentAbility, player); + } // Handle rotation control transition from WINDUP to ACTIVE if (currentAbility.isRotationLockedDuringActive()) { @@ -195,20 +198,28 @@ public class PlayerAbilityData implements IPlayerAbilityData { playAbilityAnimation(currentAbility.getActiveAnimation()); // Call onExecute - currentAbility.onExecute(player, currentTarget, player.worldObj); + currentAbility.onExecute(player, currentTarget); if (currentAbility.getPhase() == AbilityPhase.IDLE) { handleAbilityCompletion(player); return; } } - currentAbility.onActiveTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); + currentAbility.onActiveTick(player, currentTarget, currentAbility.getCurrentTick()); if (currentAbility.getPhase() == AbilityPhase.IDLE) { handleAbilityCompletion(player); return; } + // Auto-complete for burst overlap mode (entities fly independently) + if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap() + && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() + && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { + currentAbility.signalCompletion(); + } + // Release locks during burst delay if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { if (rotationLocked) releaseRotationControl(); @@ -348,7 +359,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { playAbilityAnimation(ability.getActiveAnimation()); // Call onExecute - ability.onExecute(player, currentTarget, player.worldObj); + ability.onExecute(player, currentTarget); // Check if ability completed during onExecute if (ability.getPhase() == AbilityPhase.IDLE) { From 3be9104ec356b350d595755c7d6274395ee20b73 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 14 Feb 2026 19:43:03 -0300 Subject: [PATCH 54/76] Made min and max double neg/pos infinity --- .../data/ability/type/AbstractEnergyProjectileAbility.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java index da48a2d97..c317b4beb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java @@ -572,11 +572,13 @@ public abstract class AbstractEnergyProjectileAbility projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); defs.add(FieldDef.row( - FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v) + .min(Float.NEGATIVE_INFINITY), FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + .min(Float.NEGATIVE_INFINITY) ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) - .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); // Color override (only when multiple projectiles) defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) From f03d93d6a819cc4af2b14dce86d0ff9788ae80e4 Mon Sep 17 00:00:00 2001 From: Vidal Date: Sat, 14 Feb 2026 19:43:34 -0300 Subject: [PATCH 55/76] Oopsie i swapped commits, last commit was changing min values on anchor offset fields --- src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java index 0a15e8c7c..a30b53fa8 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java @@ -22,7 +22,7 @@ public class GuiNpcTextField extends GuiTextField { private ITextfieldListener listener; public int id; public int min = 0, max = Integer.MAX_VALUE, def = 0; - public double minDouble = 0, maxDouble = Double.MAX_VALUE, defDouble = 0; + public double minDouble = Double.NEGATIVE_INFINITY, maxDouble = Double.POSITIVE_INFINITY, defDouble = 0; public float minFloat = Float.NEGATIVE_INFINITY, maxFloat = Float.POSITIVE_INFINITY, defFloat = 0; protected static GuiNpcTextField activeTextfield = null; public boolean canEdit = true; From f8c75dd79b33f0f8f6a6b34f7fb146548fbb7009 Mon Sep 17 00:00:00 2001 From: Kam Date: Sat, 14 Feb 2026 20:08:56 -0500 Subject: [PATCH 56/76] Fix Burst Refiring --- .../data/ability/type/AbstractEnergyProjectileAbility.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java index c317b4beb..2be9256eb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java @@ -256,8 +256,11 @@ public abstract class AbstractEnergyProjectileAbility Date: Sat, 14 Feb 2026 21:06:12 -0500 Subject: [PATCH 57/76] Refactor ability handling: replace damage handler with ability extenders for improved lifecycle management and damage routing --- .../controllers/data/ability/Ability.java | 11 +-- .../data/ability/AbilityController.java | 69 ++++++++++++++--- .../data/ability/IAbilityDamageHandler.java | 27 ------- .../data/ability/IAbilityExtender.java | 76 +++++++++++++++++++ .../npcs/entity/EntityAbilityProjectile.java | 18 ++--- src/main/java/noppes/npcs/DataAbilities.java | 18 +++++ .../controllers/data/PlayerAbilityData.java | 18 +++++ 7 files changed, 184 insertions(+), 53 deletions(-) delete mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.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 1878337b8..f755bc370 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -329,13 +329,10 @@ public abstract class Ability implements IAbility { // Apply damage if (damage > 0) { - // Check for external damage handler first (e.g., DBC Addon) - IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler(); - boolean handled = false; - if (handler != null) { - handled = handler.handleDamage(this, caster, hitEntity, damage, knockback, knockbackUp, - knockbackDirX, knockbackDirZ); - } + // Check for ability extenders (e.g., DBC Addon damage routing) + boolean handled = AbilityController.Instance.fireOnAbilityDamage( + this, caster, hitEntity, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ); if (!handled) { // Default damage path if (caster instanceof EntityNPCInterface) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index b65276211..c86e3e623 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -2,6 +2,7 @@ package kamkeel.npcs.controllers.data.ability; import kamkeel.npcs.controllers.data.ability.type.*; import kamkeel.npcs.controllers.SyncController; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; import noppes.npcs.LogWriter; @@ -24,7 +25,7 @@ public class AbilityController implements IAbilityHandler { // ── Extension Points ───────────────────────────────────────────────────── private final Map> externalVariants = new LinkedHashMap<>(); private final List fieldProviders = new ArrayList<>(); - private IAbilityDamageHandler damageHandler = null; + private final List extenders = new ArrayList<>(); // ── Derived State ──────────────────────────────────────────────────────── private final Set builtInTypeIds = new HashSet<>(); @@ -350,14 +351,6 @@ public class AbilityController implements IAbilityHandler { return result; } - public void registerDamageHandler(IAbilityDamageHandler handler) { - this.damageHandler = handler; - } - - public IAbilityDamageHandler getDamageHandler() { - return damageHandler; - } - public void registerFieldProvider(IAbilityFieldProvider provider) { fieldProviders.add(provider); } @@ -366,6 +359,64 @@ public class AbilityController implements IAbilityHandler { return fieldProviders; } + public void registerExtender(IAbilityExtender extender) { + extenders.add(extender); + } + + public List getExtenders() { + return extenders; + } + + /** + * Fire onAbilityStart on all extenders. Returns false if ANY extender cancels. + */ + public boolean fireOnAbilityStart(Ability ability, EntityLivingBase caster, EntityLivingBase target) { + for (IAbilityExtender ext : extenders) { + if (!ext.onAbilityStart(ability, caster, target)) { + return false; + } + } + return true; + } + + /** + * Fire onAbilityTick on all extenders. Returns false if ANY extender says to interrupt. + */ + public boolean fireOnAbilityTick(Ability ability, EntityLivingBase caster, EntityLivingBase target, + AbilityPhase phase, int tick) { + for (IAbilityExtender ext : extenders) { + if (!ext.onAbilityTick(ability, caster, target, phase, tick)) { + return false; + } + } + return true; + } + + /** + * Fire onAbilityComplete on all extenders. + */ + public void fireOnAbilityComplete(Ability ability, EntityLivingBase caster, EntityLivingBase target, + boolean interrupted) { + for (IAbilityExtender ext : extenders) { + ext.onAbilityComplete(ability, caster, target, interrupted); + } + } + + /** + * Fire onAbilityDamage on all extenders. Chain of responsibility — first true wins. + */ + public boolean fireOnAbilityDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, + float damage, float knockback, float knockbackUp, + double knockbackDirX, double knockbackDirZ) { + for (IAbilityExtender ext : extenders) { + if (ext.onAbilityDamage(ability, caster, target, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ)) { + return true; + } + } + return false; + } + // ═══════════════════════════════════════════════════════════════════════════ // IAbilityHandler // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java deleted file mode 100644 index 9a7f353c1..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import net.minecraft.entity.EntityLivingBase; - -/** - * External damage handler for abilities. - * When registered, called AFTER script events but BEFORE default attackEntityFrom. - * If handleDamage returns true, default damage is skipped. - */ -public interface IAbilityDamageHandler { - /** - * Handle damage from an ability. - * - * @param ability The ability dealing damage - * @param caster The entity executing the ability - * @param target The entity being hit - * @param damage The damage amount (after script event modifications) - * @param knockback The horizontal knockback - * @param knockbackUp The vertical knockback - * @param knockbackDirX The X component of knockback direction - * @param knockbackDirZ The Z component of knockback direction - * @return true if damage was handled (skip default), false to use default damage - */ - boolean handleDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, - float damage, float knockback, float knockbackUp, - double knockbackDirX, double knockbackDirZ); -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java new file mode 100644 index 000000000..e3e7e5c0b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java @@ -0,0 +1,76 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.EntityLivingBase; + +/** + * General-purpose extension point for abilities. Multiple extenders can be registered. + * Covers lifecycle hooks (start/tick/complete) and damage handling. + *

+ * All methods have no-op defaults so extenders only override what they need. + */ +public interface IAbilityExtender { + + /** + * Called before an ability starts executing. + * Return false to cancel the ability (e.g., insufficient resources). + * + * @param ability The ability about to start + * @param caster The entity executing the ability (NPC or Player) + * @param target The target entity (may be null for player self-cast) + * @return true to allow, false to cancel + */ + default boolean onAbilityStart(Ability ability, EntityLivingBase caster, EntityLivingBase target) { + return true; + } + + /** + * Called each tick during ability execution. + * Return false to interrupt the ability (e.g., resource depleted). + * + * @param ability The executing ability + * @param caster The entity executing the ability + * @param target The target entity (may be null) + * @param phase The current ability phase (WINDUP, ACTIVE, DAZED, BURST_DELAY) + * @param tick The current tick within the phase + * @return true to continue, false to interrupt + */ + default boolean onAbilityTick(Ability ability, EntityLivingBase caster, EntityLivingBase target, + AbilityPhase phase, int tick) { + return true; + } + + /** + * Called when an ability completes (normally or via interruption). + * + * @param ability The completed ability + * @param caster The entity that was executing the ability + * @param target The target entity (may be null) + * @param interrupted true if the ability was interrupted, false if it completed normally + */ + default void onAbilityComplete(Ability ability, EntityLivingBase caster, EntityLivingBase target, + boolean interrupted) { + } + + /** + * Called when an ability deals damage, AFTER script events but BEFORE default attackEntityFrom. + * Return true to handle the damage (skips default damage application). + *

+ * Chain of responsibility: extenders are called in registration order. + * The first extender returning true claims the damage; remaining extenders are skipped. + * + * @param ability The ability dealing damage + * @param caster The entity executing the ability + * @param target The entity being hit + * @param damage The damage amount (after script event modifications) + * @param knockback The horizontal knockback + * @param knockbackUp The vertical knockback + * @param knockbackDirX The X component of knockback direction + * @param knockbackDirZ The Z component of knockback direction + * @return true if damage was handled (skip default), false to pass to next extender or default + */ + default boolean onAbilityDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, + float damage, float knockback, float knockbackUp, + double knockbackDirX, double knockbackDirZ) { + return false; + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index 9b30abab6..dee2ed292 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -8,7 +8,7 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilityEffect; import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.IAbilityDamageHandler; + import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; @@ -326,17 +326,15 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP if (previewMode) return; // Skip damage in preview mode Entity owner = getOwnerEntity(); - // Check for external damage handler (e.g., DBC Addon) + // Check for ability extenders (e.g., DBC Addon damage routing) boolean handled = false; if (sourceAbility != null && owner instanceof EntityLivingBase) { - IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler(); - if (handler != null) { - double dx = target.posX - posX; - double dz = target.posZ - posZ; - float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f; - handled = handler.handleDamage(sourceAbility, (EntityLivingBase) owner, target, - dmg, kb, kbUp, dx, dz); - } + double dx = target.posX - posX; + double dz = target.posZ - posZ; + float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f; + handled = AbilityController.Instance.fireOnAbilityDamage( + sourceAbility, (EntityLivingBase) owner, target, + dmg, kb, kbUp, dx, dz); } if (!handled) { diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 8edcba628..eb3082a59 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -171,6 +171,13 @@ public class DataAbilities { // Fire tick event for scripts fireTickEvent(currentAbility, target); + // Fire extender tick hook (e.g., per-tick resource drain) + if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, npc, target, + currentAbility.getPhase(), currentAbility.getCurrentTick())) { + interruptCurrentAbility(null, 0); + return; + } + // Handle phase-specific logic switch (currentAbility.getPhase()) { case WINDUP: @@ -342,6 +349,9 @@ public class DataAbilities { // Remove any remaining telegraphs (for abilities that keep telegraph during active) removeTelegraph(currentAbility); + // Fire extender complete hook + AbilityController.Instance.fireOnAbilityComplete(currentAbility, npc, target, false); + // Call onComplete callback currentAbility.onComplete(npc, target); @@ -501,6 +511,11 @@ public class DataAbilities { return false; } + // Fire extender start hook (e.g., resource cost checks) + if (!AbilityController.Instance.fireOnAbilityStart(ability, npc, target)) { + return false; + } + currentAbility = ability; lastTarget = target; ability.start(target); @@ -750,6 +765,9 @@ public class DataAbilities { releaseRotationControl(); releaseLockedPosition(); + // Fire extender complete hook (interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, npc, lastTarget, true); + // Fire interrupt event AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent( npc.wrappedNPC, currentAbility, lastTarget, source, damage); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 0f87ddf5a..aa8d4301d 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -147,6 +147,13 @@ public class PlayerAbilityData implements IPlayerAbilityData { // Tick advances time and possibly changes phase boolean phaseChanged = currentAbility.tick(); + // Fire extender tick hook (e.g., per-tick resource drain) + if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, player, currentTarget, + currentAbility.getPhase(), currentAbility.getCurrentTick())) { + interruptCurrentAbility(); + return; + } + switch (currentAbility.getPhase()) { case WINDUP: if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { @@ -249,6 +256,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { private void handleAbilityCompletion(EntityPlayer player) { if (currentAbility == null) return; + // Fire extender complete hook + AbilityController.Instance.fireOnAbilityComplete(currentAbility, player, currentTarget, false); + currentAbility.onComplete(player, currentTarget); // Release all locks @@ -318,6 +328,11 @@ public class PlayerAbilityData implements IPlayerAbilityData { // Check conditions (skip target-requiring ones) if (!ability.checkConditionsForPlayer(player)) return false; + // Fire extender start hook (e.g., resource cost checks) + if (!AbilityController.Instance.fireOnAbilityStart(ability, player, null)) { + return false; + } + // Start the ability currentAbility = ability; currentAbilityKey = key; @@ -517,6 +532,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { public void interruptCurrentAbility() { if (currentAbility != null && currentAbility.isExecuting()) { + // Fire extender complete hook (interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, playerData.player, currentTarget, true); + currentAbility.interrupt(); stopAbilityAnimation(); releaseRotationControl(); From 61405add979f55128e8e2940a0574d89ae43bc0f Mon Sep 17 00:00:00 2001 From: Vidal Date: Sun, 15 Feb 2026 00:40:43 -0300 Subject: [PATCH 58/76] Added Ki Cost to Ability --- .../npcs/controllers/data/ability/Ability.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) 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 f755bc370..a4dfcfe61 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -110,6 +110,9 @@ public abstract class Ability implements IAbility { protected boolean burstReplayAnimations = true; protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts + // Ki + protected int kiCost = 0; + // ═══════════════════════════════════════════════════════════════════ // EXECUTION STATE (not saved, reset each combat) // ═══════════════════════════════════════════════════════════════════ @@ -1149,6 +1152,9 @@ public abstract class Ability implements IAbility { nbt.setBoolean("burstReplayAnimations", burstReplayAnimations); nbt.setBoolean("burstOverlap", burstOverlap); + // Ki + nbt.setInteger("kiCost", kiCost); + // Conditions NBTTagList condList = new NBTTagList(); for (Condition c : conditions) condList.appendTag(c.writeNBT()); @@ -1212,6 +1218,9 @@ public abstract class Ability implements IAbility { burstReplayAnimations = nbt.getBoolean("burstReplayAnimations"); burstOverlap = nbt.getBoolean("burstOverlap"); + // Ki + kiCost = nbt.getInteger("kiCost"); + // Conditions conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); @@ -1751,6 +1760,14 @@ public abstract class Ability implements IAbility { return burstIndex; } + public int getKiCost() { + return kiCost; + } + + public void setKiCost(int kiCost) { + this.kiCost = kiCost; + } + /** * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). */ From e466ef67711806ede8ae1617415befdd037f0853 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 04:47:19 -0500 Subject: [PATCH 59/76] Remove Ki Cost from base Ability - DBC-specific concern Ki Cost belongs in the DBC Addon's DBCAbilityStats system, not in the base ability infrastructure. Co-Authored-By: Claude Opus 4.6 --- .../npcs/controllers/data/ability/Ability.java | 17 ----------------- 1 file changed, 17 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 a4dfcfe61..f755bc370 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -110,9 +110,6 @@ public abstract class Ability implements IAbility { protected boolean burstReplayAnimations = true; protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts - // Ki - protected int kiCost = 0; - // ═══════════════════════════════════════════════════════════════════ // EXECUTION STATE (not saved, reset each combat) // ═══════════════════════════════════════════════════════════════════ @@ -1152,9 +1149,6 @@ public abstract class Ability implements IAbility { nbt.setBoolean("burstReplayAnimations", burstReplayAnimations); nbt.setBoolean("burstOverlap", burstOverlap); - // Ki - nbt.setInteger("kiCost", kiCost); - // Conditions NBTTagList condList = new NBTTagList(); for (Condition c : conditions) condList.appendTag(c.writeNBT()); @@ -1218,9 +1212,6 @@ public abstract class Ability implements IAbility { burstReplayAnimations = nbt.getBoolean("burstReplayAnimations"); burstOverlap = nbt.getBoolean("burstOverlap"); - // Ki - kiCost = nbt.getInteger("kiCost"); - // Conditions conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); @@ -1760,14 +1751,6 @@ public abstract class Ability implements IAbility { return burstIndex; } - public int getKiCost() { - return kiCost; - } - - public void setKiCost(int kiCost) { - this.kiCost = kiCost; - } - /** * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). */ From 8c2ef1084a8e2dd9008e6d43864702c0bc6c5f4c Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 17:47:44 -0500 Subject: [PATCH 60/76] Fix Burst Refire --- .../controllers/data/ability/Ability.java | 6 ++-- .../type/AbstractEnergyProjectileAbility.java | 32 ++++++++++++++++--- src/main/java/noppes/npcs/DataAbilities.java | 2 +- .../controllers/data/PlayerAbilityData.java | 2 +- 4 files changed, 32 insertions(+), 10 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 f755bc370..11ceffea8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -910,9 +910,9 @@ public abstract class Ability implements IAbility { if (phase == AbilityPhase.ACTIVE) { // Check if more burst iterations remain if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) { - if (!burstOverlap) { - cleanup(); - } + // Don't cleanup here - entities may still be in flight + // For non-overlap: cleaned up when next burst starts (in onExecute) + // For overlap: entities continue flying indefinitely burstIndex++; phase = AbilityPhase.BURST_DELAY; currentTick = 0; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java index 2be9256eb..f3ee572c2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java @@ -258,9 +258,13 @@ public abstract class AbstractEnergyProjectileAbility 5 && entity.worldObj != null + && entity.worldObj.getEntityByID(entity.getEntityId()) != entity) { + entity.setDead(); + continue; + } + + allDead = false; + break; + } + + // Failsafe timeout: force completion if active phase exceeded max possible flight time + if (!allDead) { + int lastFireTick = fireDelay > 0 ? fireDelay * (projectileCount - 1) : 0; + int maxFlightTime = lifespanData.maxLifetime > 0 ? lifespanData.maxLifetime : 200; + if (tick > lastFireTick + maxFlightTime + 20) { + cleanup(); + allDead = true; } } + if (allDead) { signalCompletion(); } diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index eb3082a59..78692162f 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -269,7 +269,7 @@ public class DataAbilities { // This allows entity-spawning abilities to immediately chain next burst // without each type needing to check burst state in their onActiveTick() // Wait until all staggered projectiles have been fired before auto-completing - if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap() + if (currentAbility.isBurstEnabled() && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() && currentAbility.getPhase() == AbilityPhase.ACTIVE && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index aa8d4301d..f0a4c8c70 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -220,7 +220,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { } // Auto-complete for burst overlap mode (entities fly independently) - if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap() + if (currentAbility.isBurstEnabled() && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() && currentAbility.getPhase() == AbilityPhase.ACTIVE && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { From ff9f9b9660f0c942fe9f68cf5735af19a1b8136f Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 18:05:07 -0500 Subject: [PATCH 61/76] Enhance ability variant selection: inject a default "Base" variant when no built-in variants are available --- .../npcs/controllers/data/ability/AbilityController.java | 5 +++++ src/main/resources/assets/customnpcs/lang/en_US.lang | 1 + 2 files changed, 6 insertions(+) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index c86e3e623..992c56cd9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -346,6 +346,11 @@ public class AbilityController implements IAbilityHandler { } List ext = externalVariants.get(typeId); if (ext != null) { + // If no built-in variants exist but external ones do, + // inject a "Base" variant so the user always gets a choice + if (result.isEmpty()) { + result.add(new AbilityVariant("ability.variant.base", a -> {})); + } result.addAll(ext); } 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 a29759c31..f265f0fe9 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1910,6 +1910,7 @@ ability.modifyParent=Edit Parent # Ability Variant Selection ability.selectVariant=Select Variant +ability.variant.base=Base ability.variant.single=Single ability.variant.dual=Dual ability.variant.barrage=Barrage From 2dfdfb19d1aa7fd084cb7b9250ad35868fd1c8e4 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 18:15:56 -0500 Subject: [PATCH 62/76] Client-side trade validation and stock update Perform more complete client-side checks before predicting currency deductions in GuiNPCTrader.handleMouseClick. The method now verifies that the item can be given to the player (canGivePlayerClient), that the slot is enabled, and that stock is available, mirroring server-side checks. When a client-side purchase is accepted, availableStock is decremented if applicable. Added a private canGivePlayerClient(ItemStack) helper to check cursor-stack compatibility and max stack size. These changes prevent the UI from showing incorrect balances for trades the server would reject. --- .../npcs/client/gui/player/GuiNPCTrader.java | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java index 55f88ac8c..49edf72b6 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java @@ -337,18 +337,45 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData { protected void handleMouseClick(Slot slot, int slotId, int mouseButton, int modifier) { // Client-side balance prediction: immediately subtract currency cost on click // so the displayed balance updates instantly without waiting for server response. + // Must mirror ALL server-side checks in ContainerNPCTrader.slotClick() to avoid + // predicting a deduction for trades the server will reject. if (slotId >= 0 && slotId < 18 && mouseButton == 0) { long cost = currencyCost[slotId]; if (cost > 0 && playerBalance >= cost) { ItemStack sold = role.inventorySold.items.get(slotId); - if (sold != null && container.canBuy(slotId, player)) { + if (sold != null + && canGivePlayerClient(sold) + && container.isSlotEnabled(slotId, player) + && (!stockEnabled || availableStock[slotId] > 0) + && container.canBuy(slotId, player)) { playerBalance -= cost; + if (stockEnabled && availableStock[slotId] < Integer.MAX_VALUE) { + availableStock[slotId]--; + } } } } super.handleMouseClick(slot, slotId, mouseButton, modifier); } + /** + * Client-side mirror of ContainerNPCTrader.canGivePlayer. + * Checks if the item can be added to the player's cursor stack. + */ + private boolean canGivePlayerClient(ItemStack item) { + ItemStack held = player.inventory.getItemStack(); + if (held == null) { + return true; + } + if (NoppesUtilPlayer.compareItems(held, item, false, false)) { + int k1 = item.stackSize; + if (k1 > 0 && k1 + held.stackSize <= held.getMaxStackSize()) { + return true; + } + } + return false; + } + @Override public void save() { } From 45d05b9157220d1d639bb40df37db08781da8f4f Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 19:19:57 -0500 Subject: [PATCH 63/76] Add trap presets & trigger-reveal visuals Introduce client-side trap presets and a visual "trigger reveal" for traps, plus related entity/renderer changes. - AbilityTrap: add TrapPreset enum and applyTrapPresetDefaults; wire a SubGuiTrapPresetSelector hook to apply presets from the GUI; pass visibility into created trap entities. - EntityAbilityZone: add visible flag, TRIGGER_FLASH_STATUS state, setEntityState usage to notify clients of triggers, handleHealthUpdate to start client-side flash, and adjust construction/serialization accordingly. - RenderAbilityZone: implement trigger-reveal visuals (revealFade, triggerReveal) that briefly show a burst when traps trigger, skip rendering for invisible traps unless revealing, and tweak flash/timing logic. - Minor cleanup: remove/condense comment blocks and refactor noisy helpers across AbilityZone/AbilityHazard, plus language entry update and new SubGuiTrapPresetSelector GUI class. These changes enable preset application for traps and improve client-side feedback when traps trigger. --- .../client/renderer/RenderAbilityZone.java | 114 ++++------ .../data/ability/type/AbilityHazard.java | 19 -- .../data/ability/type/AbilityTrap.java | 113 ++++++++-- .../data/ability/type/AbilityZone.java | 64 ------ .../npcs/entity/EntityAbilityZone.java | 206 +++++------------- .../client/gui/SubGuiTrapPresetSelector.java | 72 ++++++ .../assets/customnpcs/lang/en_US.lang | 6 + 7 files changed, 271 insertions(+), 323 deletions(-) create mode 100644 src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java index 9fae0e982..e9775c542 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java @@ -22,10 +22,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Random; -/** - * Renders zone effects for Trap and Hazard abilities. - * Supports CIRCLE and SQUARE shapes with composable visual layers. - */ @SideOnly(Side.CLIENT) public class RenderAbilityZone extends Render { @@ -33,43 +29,35 @@ public class RenderAbilityZone extends Render { private static final int ACCENT_LINE_COUNT = 12; private static final Random RANDOM = new Random(); - // Track last particle spawn tick per entity to avoid duplicate spawns private final Map lastParticleTick = new HashMap<>(); - - // Persistent lightning state private final Map lightningStates = new HashMap<>(); - // ═══════════════════════════════════════════════════════════════════ - // RENDER CONTEXT - // ═══════════════════════════════════════════════════════════════════ + private static final int TRIGGER_REVEAL_TICKS = 10; private static class Ctx { EntityAbilityZone zone; ZoneShape shape; float radius, height; - float ir, ig, ib; // inner color + float ir, ig, ib; float outerR, outerG, outerB; boolean outerEnabled; float time, pulse, rotation, brightness; boolean flash, newTick; float particleDensity, particleScale, animSpeed, lightningDensity; - // Visual layer fields (always populated) boolean groundFill, rings, border, accents, lightning, particles; float groundAlpha, borderSpeed; int ringCount, accentStyle, particleMotion, particleSize; boolean particleGlow; String particleDir; + boolean trapVisible; + boolean triggerReveal; + float revealFade; } - // ═══════════════════════════════════════════════════════════════════ - // MAIN RENDER - // ═══════════════════════════════════════════════════════════════════ - @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { EntityAbilityZone zone = (EntityAbilityZone) entity; - // Build context Ctx c = new Ctx(); c.zone = zone; c.shape = zone.getShape(); @@ -92,7 +80,6 @@ public class RenderAbilityZone extends Render { c.animSpeed = zone.getAnimSpeed(); c.lightningDensity = zone.getLightningDensity(); - // Visual layer fields — always populated c.groundFill = zone.isGroundFill(); c.groundAlpha = zone.getGroundAlpha(); c.rings = zone.isRings(); @@ -113,7 +100,27 @@ public class RenderAbilityZone extends Render { c.rotation = c.time * 1.5f * c.animSpeed; c.brightness = 1.0f; + c.trapVisible = true; + c.triggerReveal = false; + c.revealFade = 0.0f; + if (zone.getZoneType() == ZoneType.TRAP) { + c.trapVisible = zone.isVisible(); + + // Trigger reveal: 10-tick full visual burst that fades out + if (zone.getTriggerFlashTick() >= 0) { + float ticksSinceTrigger = zone.ticksExisted - zone.getTriggerFlashTick() + partialTicks; + if (ticksSinceTrigger < TRIGGER_REVEAL_TICKS) { + c.triggerReveal = true; + c.revealFade = Math.max(0.0f, 1.0f - ticksSinceTrigger / TRIGGER_REVEAL_TICKS); + } + } + + // Skip render entirely if invisible and not in reveal + if (!c.trapVisible && !c.triggerReveal) { + return; + } + if (!zone.isArmed()) { c.brightness = 0.4f; } else { @@ -121,16 +128,14 @@ public class RenderAbilityZone extends Render { } } - c.flash = zone.getTriggerFlashTick() >= 0 - && zone.ticksExisted - zone.getTriggerFlashTick() < 4; + // White flash during first 2 ticks of reveal + c.flash = c.triggerReveal && c.revealFade > 0.8f; c.newTick = isNewTick(zone); - // Render setupRenderState(); GL11.glPushMatrix(); GL11.glTranslated(x, y, z); - GL11.glDepthMask(false); renderZone(c); @@ -161,14 +166,21 @@ public class RenderAbilityZone extends Render { return state; } - // ═══════════════════════════════════════════════════════════════════ - // UNIFIED RENDER — Composable visual layers - // ═══════════════════════════════════════════════════════════════════ - private void renderZone(Ctx c) { + // During trigger reveal, override visual layers for dramatic burst + if (c.triggerReveal) { + c.brightness = c.revealFade; + c.groundFill = true; + c.groundAlpha = 0.35f * c.revealFade; + c.rings = true; + c.ringCount = 3; + c.accents = true; + c.accentStyle = 2; // FLICKERING + c.border = true; + } + float rR = ringR(c), rG = ringG(c), rB = ringB(c); - // 1. Ground fill if (c.groundFill) { if (c.flash) { renderShapeFill(c.shape, c.radius, 1, 1, 1, 0.5f); @@ -178,7 +190,6 @@ public class RenderAbilityZone extends Render { } } - // 2. Pulse rings if (c.rings) { int count = Math.max(1, Math.min(5, c.ringCount)); for (int i = 0; i < count; i++) { @@ -188,18 +199,15 @@ public class RenderAbilityZone extends Render { renderRingLine(c.shape, c.radius * frac, rR, rG, rB, ra, yOff); } - // Always include outer edge ring float edgeA = (0.5f + 0.4f * sin(c.pulse + count * Math.PI / 3)) * c.brightness; renderRingLine(c.shape, c.radius, rR, rG, rB, edgeA, 0.02f + count * 0.01f); } - // 3. Rotating border if (c.border) { renderRotatingBorder(c.shape, c.radius, rR, rG, rB, 0.7f * c.brightness, c.rotation * c.borderSpeed, 0.05f); } - // 4. Vertical accents if (c.accents) { float aa = 0.5f * c.brightness * (0.3f + 0.2f * sin(c.pulse * 0.7f)); AccentStyle style = AccentStyle.values()[Math.min(c.accentStyle, AccentStyle.values().length - 1)]; @@ -216,7 +224,6 @@ public class RenderAbilityZone extends Render { } } - // 5. Lightning if (c.lightning) { int innerColor = c.zone.getInnerColor(); int outerColor = c.outerEnabled ? c.zone.getOuterColor() : innerColor; @@ -246,10 +253,9 @@ public class RenderAbilityZone extends Render { } } state.render(); - GL11.glDepthMask(false); // Reset after lightning + GL11.glDepthMask(false); } - // 6. Particles if (c.particles && c.newTick && c.particleDensity > 0) { if (c.particleDir != null && !c.particleDir.isEmpty()) { if (c.particleDir.startsWith("mc:")) { @@ -263,7 +269,6 @@ public class RenderAbilityZone extends Render { } } - /** Spawn vanilla Minecraft particles using mc: prefix (e.g. "mc:flame"). */ private void spawnVanillaParticle(Ctx c) { String particleName = c.particleDir.substring(3); int count = Math.round(3 * c.particleDensity); @@ -276,7 +281,6 @@ public class RenderAbilityZone extends Render { } } - /** Spawn CustomFX particles using a texture directory. */ private void spawnCustomFXParticle(Ctx c) { int count = Math.round(3 * c.particleDensity); for (int i = 0; i < count; i++) { @@ -308,7 +312,6 @@ public class RenderAbilityZone extends Render { } } - /** Spawn default ZoneParticleFX with motion style from ParticleMotion enum. */ private void spawnDefaultParticles(Ctx c) { int count = Math.round(3 * c.particleDensity); ParticleMotion motion = ParticleMotion.values()[Math.min(c.particleMotion, ParticleMotion.values().length - 1)]; @@ -346,7 +349,6 @@ public class RenderAbilityZone extends Render { } } - /** Get motion vector for a CustomFX particle based on ParticleMotion ordinal. */ private double[] getMotionForStyle(int motionOrdinal) { ParticleMotion motion = ParticleMotion.values()[Math.min(motionOrdinal, ParticleMotion.values().length - 1)]; switch (motion) { @@ -371,18 +373,12 @@ public class RenderAbilityZone extends Render { } } - // ═══════════════════════════════════════════════════════════════════ - // STYLE HELPERS - // ═══════════════════════════════════════════════════════════════════ - - /** Get the ring/outer color (falls back to inner if outer not enabled). */ private float ringR(Ctx c) { return c.outerEnabled ? c.outerR : c.ir; } private float ringG(Ctx c) { return c.outerEnabled ? c.outerG : c.ig; } private float ringB(Ctx c) { return c.outerEnabled ? c.outerB : c.ib; } private static float sin(double v) { return (float) Math.sin(v); } - /** Vertical accents with sinusoidal sway per line. */ private void renderSwayingAccents(Ctx c, float r, float g, float b, float a, float height) { if (height <= 0.1f) return; float rotRad = (float) Math.toRadians(c.rotation * 0.2f); @@ -436,7 +432,6 @@ public class RenderAbilityZone extends Render { } } - /** Vertical accents with per-line random alpha flicker. */ private void renderFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height) { if (height <= 0.1f) return; float rotRad = (float) Math.toRadians(c.rotation * 0.4f); @@ -492,7 +487,6 @@ public class RenderAbilityZone extends Render { } } - /** Pick a random position within the zone's area. Returns {x, y, z} offsets from zone center. */ private double[] randomPosInZone(Ctx c) { if (c.shape == ZoneShape.SQUARE) { double px = (RANDOM.nextDouble() * 2 - 1) * c.radius; @@ -507,7 +501,6 @@ public class RenderAbilityZone extends Render { } } - /** Pick a random position on the edge of the zone. Returns {x, z}. */ private double[] randomEdgePos(Ctx c) { if (c.shape == ZoneShape.SQUARE) { int side = RANDOM.nextInt(4); @@ -525,7 +518,6 @@ public class RenderAbilityZone extends Render { } } - /** Spawn a zone particle at world position. */ private void spawnParticle(EntityAbilityZone zone, double offsetX, double offsetY, double offsetZ, double mx, double my, double mz, float r, float g, float b, float alpha, @@ -537,10 +529,6 @@ public class RenderAbilityZone extends Render { Minecraft.getMinecraft().effectRenderer.addEffect(particle); } - // ═══════════════════════════════════════════════════════════════════ - // GL STATE - // ═══════════════════════════════════════════════════════════════════ - private void setupRenderState() { GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); GL11.glDisable(GL11.GL_TEXTURE_2D); @@ -561,10 +549,6 @@ public class RenderAbilityZone extends Render { GL11.glPopAttrib(); } - // ═══════════════════════════════════════════════════════════════════ - // SHAPE FILL (Ground plane) - // ═══════════════════════════════════════════════════════════════════ - private void renderShapeFill(ZoneShape shape, float radius, float r, float g, float b, float a) { GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL); GL11.glPolygonOffset(-1.0f, -1.0f); @@ -602,10 +586,6 @@ public class RenderAbilityZone extends Render { tess.draw(); } - // ═══════════════════════════════════════════════════════════════════ - // RING LINES (Concentric pulse rings) - // ═══════════════════════════════════════════════════════════════════ - private void renderRingLine(ZoneShape shape, float radius, float r, float g, float b, float a, float yOffset) { switch (shape) { @@ -640,18 +620,13 @@ public class RenderAbilityZone extends Render { tess.draw(); } - // ═══════════════════════════════════════════════════════════════════ - // ROTATING BORDER - // ═══════════════════════════════════════════════════════════════════ - private void renderRotatingBorder(ZoneShape shape, float radius, float r, float g, float b, float a, float rotationDeg, float yOffset) { int dashCount = 16; if (shape == ZoneShape.SQUARE) { - // Dashes along 4 rectangle edges with offset - float perimeter = radius * 8; // total perimeter = 4 * (2*radius) + float perimeter = radius * 8; float dashLen = perimeter / dashCount; float offset = (rotationDeg % 360.0f) / 360.0f * perimeter; @@ -691,7 +666,6 @@ public class RenderAbilityZone extends Render { } } - /** Convert a distance along the square perimeter to an x,z position. */ private double[] perimeterPos(float dist, float radius) { float sideLen = radius * 2; if (dist < sideLen) { @@ -713,10 +687,6 @@ public class RenderAbilityZone extends Render { return new double[]{-radius, radius - dist}; } - // ═══════════════════════════════════════════════════════════════════ - // VERTICAL ACCENT LINES - // ═══════════════════════════════════════════════════════════════════ - private void renderVerticalAccents(ZoneShape shape, float radius, float r, float g, float b, float a, float height, float rotationDeg) { @@ -725,7 +695,6 @@ public class RenderAbilityZone extends Render { Tessellator tess = Tessellator.instance; if (shape == ZoneShape.SQUARE) { - // Lines at corners + distributed along edges int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); for (int side = 0; side < 4; side++) { for (int j = 0; j < perSide; j++) { @@ -745,7 +714,6 @@ public class RenderAbilityZone extends Render { tess.draw(); } } - // Corner accent lines float[][] corners = {{-radius, -radius}, {radius, -radius}, {radius, radius}, {-radius, radius}}; for (float[] corner : corners) { tess.startDrawing(GL11.GL_LINES); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 26409d5fe..7ca81c95a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -19,14 +19,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -/** - * Hazard ability: Creates persistent ground effect zones around the caster. - * Spawns one or more EntityAbilityZone entities in random positions - * within spawnRadius. Damage and zone logic handled by the entity. - */ public class AbilityHazard extends AbilityZone implements IAbilityHazard { - // Hazard-specific fields private float radius = 2.0f; private float damagePerSecond = 1.0f; private int damageInterval = 20; @@ -51,7 +45,6 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { public void onExecute(EntityLivingBase caster, EntityLivingBase target) { activeEntities.clear(); - // Use pre-calculated positions from telegraph phase, or generate new ones List positions; if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { positions = new ArrayList<>(preCalculatedPositions); @@ -93,10 +86,6 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { } } - // ═══════════════════════════════════════════════════════════════════ - // NBT - // ═══════════════════════════════════════════════════════════════════ - @Override public void writeTypeNBT(NBTTagCompound nbt) { writeZoneNBT(nbt); @@ -117,10 +106,6 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { this.affectsCaster = nbt.getBoolean("affectsCaster"); } - // ═══════════════════════════════════════════════════════════════════ - // HAZARD-SPECIFIC GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ - public float getRadius() { return radius; } public void setRadius(float radius) { this.radius = radius; } @@ -136,10 +121,6 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { public boolean isAffectsCaster() { return affectsCaster; } public void setAffectsCaster(boolean affectsCaster) { this.affectsCaster = affectsCaster; } - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ - @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 7766c3d45..62471c051 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -1,16 +1,16 @@ package kamkeel.npcs.controllers.data.ability.type; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.entity.EntityAbilityZone; import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; - - import noppes.npcs.api.ability.type.IAbilityTrap; - +import noppes.npcs.client.gui.SubGuiTrapPresetSelector; import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import noppes.npcs.constants.EnumPotionType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -19,14 +19,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -/** - * Trap ability: Places proximity-triggered traps around the caster. - * Spawns one or more EntityAbilityZone entities in random positions - * within spawnRadius of the caster. Damage and trigger logic handled by the entity. - */ public class AbilityTrap extends AbilityZone implements IAbilityTrap { - // Trap-specific fields private float triggerRadius = 2.0f; private int armTime = 20; private int maxTriggers = 1; @@ -54,7 +48,6 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { public void onExecute(EntityLivingBase caster, EntityLivingBase target) { activeEntities.clear(); - // Use pre-calculated positions from telegraph phase, or generate new ones List positions; if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { positions = new ArrayList<>(preCalculatedPositions); @@ -81,6 +74,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, zoneHeight, particleDensity, particleScale, animSpeed, lightningDensity, + visible, getEffects()); applyVisualToEntity(entity); @@ -94,9 +88,81 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { } } - // ═══════════════════════════════════════════════════════════════════ - // NBT - // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) + public enum TrapPreset { + HIDDEN, VENOM, EXPLOSIVE, CURSED, SHOCK, SNARE; + + @Override + public String toString() { + return "ability.preset." + name().toLowerCase(); + } + } + + private void applyTrapPresetDefaults(String preset) { + effects.clear(); + particleDir = ""; + + groundFill = true; + rings = false; + ringCount = 1; + border = false; + borderSpeed = 1.0f; + accents = false; + accentStyle = 0; + lightning = false; + particleGlow = false; + + switch (preset) { + case "VENOM": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.5f; + particleMotion = 1; particleDir = "mc:mobSpell"; + colorData.innerColor = 0x44DD44; colorData.outerColor = 0x116611; + windUpColor = 0x6044DD44; activeColor = 0xC044FF44; + effects.add(new AbilityEffect(EnumPotionType.Poison, 100, 0)); + break; + case "EXPLOSIVE": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.6f; + particleMotion = 0; particleDir = "mc:smoke"; + colorData.innerColor = 0xFF6611; colorData.outerColor = 0xCC2200; + windUpColor = 0x60FF6611; activeColor = 0xC0FF4400; + effects.add(new AbilityEffect(EnumPotionType.Fire, 60, 0)); + break; + case "CURSED": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.5f; + particleMotion = 1; particleDir = "mc:portal"; + colorData.innerColor = 0xAA44FF; colorData.outerColor = 0x6622BB; + windUpColor = 0x60AA44FF; activeColor = 0xC0CC66FF; + effects.add(new AbilityEffect(EnumPotionType.Weakness, 100, 0)); + break; + case "SHOCK": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.4f; + particleMotion = 2; particleDir = "mc:enchantmenttable"; + colorData.innerColor = 0x4488FF; colorData.outerColor = 0x2244BB; + windUpColor = 0x604488FF; activeColor = 0xC066AAFF; + effects.add(new AbilityEffect(EnumPotionType.MiningFatigue, 80, 1)); + break; + case "SNARE": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.5f; + particleMotion = 1; particleDir = "mc:snowshovel"; + colorData.innerColor = 0x88CCFF; colorData.outerColor = 0x4488CC; + windUpColor = 0x6088CCFF; activeColor = 0xC0AADDFF; + effects.add(new AbilityEffect(EnumPotionType.Slowness, 100, 1)); + break; + case "HIDDEN": + default: + groundAlpha = 0.03f; + particles = false; particleDensity = 0.0f; particleScale = 1.0f; + particleMotion = 0; + colorData.innerColor = 0x888888; colorData.outerColor = 0x444444; + windUpColor = 0x60888888; activeColor = 0xC0AAAAAA; + break; + } + } @Override public void writeTypeNBT(NBTTagCompound nbt) { @@ -124,10 +190,6 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { this.visible = nbt.getBoolean("visible"); } - // ═══════════════════════════════════════════════════════════════════ - // TRAP-SPECIFIC GETTERS & SETTERS - // ═══════════════════════════════════════════════════════════════════ - public float getTriggerRadius() { return triggerRadius; } public void setTriggerRadius(float triggerRadius) { this.triggerRadius = triggerRadius; } public int getArmTime() { return armTime; } @@ -145,9 +207,18 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } - // ═══════════════════════════════════════════════════════════════════ - // GUI FIELD DEFINITIONS - // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) + @Override + protected void addPresetFieldDef(List defs) { + defs.add(FieldDef.subGuiField("gui.applyPreset", + SubGuiTrapPresetSelector::new, + gui -> { + SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui; + if (selector.selectedPreset != null) { + applyTrapPresetDefaults(selector.selectedPreset); + } + })); + } @SideOnly(Side.CLIENT) @Override 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 438fd11d4..0d4b0ce8f 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 @@ -31,27 +31,20 @@ import java.util.Iterator; import java.util.List; import java.util.Random; -/** - * Abstract base class for zone-based abilities (Trap, Hazard). - * Extracts shared fields: duration, shape, spawn, visual, lifecycle, and FieldDefs. - */ public abstract class AbilityZone extends Ability { - // Zone properties protected int durationTicks; protected ZoneShape zoneShape = ZoneShape.CIRCLE; protected float spawnRadius = 10.0f; protected int zoneCount = 3; protected float zoneHeight = 2.0f; - // Visual parameters protected float particleDensity = 1.0f; protected float particleScale = 1.0f; protected float animSpeed = 1.0f; protected float lightningDensity = 1.0f; protected EnergyDisplayData colorData; - // Visual layer fields (always active) protected boolean groundFill = true; protected float groundAlpha = 0.25f; protected boolean rings = true; @@ -67,7 +60,6 @@ public abstract class AbilityZone extends Ability { protected int particleSize = 32; protected boolean particleGlow = true; - // Runtime state protected static final Random RANDOM = new Random(); protected transient List activeEntities = new ArrayList<>(); protected transient List preCalculatedPositions = new ArrayList<>(); @@ -82,10 +74,6 @@ public abstract class AbilityZone extends Ability { this.allowedBy = UserType.NPC_ONLY; } - // ═════════════════════════════════════════════════════════════════ - // SHARED OVERRIDES - // ═════════════════════════════════════════════════════════════════ - @Override public boolean allowBurst() { return false; @@ -101,17 +89,12 @@ public abstract class AbilityZone extends Ability { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - /** - * Returns the actual zone effect radius for telegraph sizing. - * AbilityHazard returns its damage radius, AbilityTrap returns triggerRadius. - */ public abstract float getZoneRadius(); @Override public List createTelegraphs(EntityLivingBase caster, EntityLivingBase target) { if (!showTelegraph || windUpTicks <= 0) return new ArrayList<>(); - // Pre-calculate zone positions preCalculatedPositions.clear(); List placedPositions = new ArrayList<>(); float minSeparation = getZoneRadius() * 2.0f; @@ -122,7 +105,6 @@ public abstract class AbilityZone extends Ability { preCalculatedPositions.add(pos); } - // Create a telegraph for each zone position List telegraphs = new ArrayList<>(); float zoneRadius = getZoneRadius(); @@ -152,7 +134,6 @@ public abstract class AbilityZone extends Ability { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { - // Remove dead entities Iterator it = activeEntities.iterator(); while (it.hasNext()) { EntityAbilityZone entity = it.next(); @@ -192,13 +173,6 @@ public abstract class AbilityZone extends Ability { return durationTicks + 10; } - // ═════════════════════════════════════════════════════════════════ - // SHARED SPAWN HELPER - // ═════════════════════════════════════════════════════════════════ - - /** - * Find a non-overlapping spawn position within spawnRadius of the caster. - */ protected double[] findSpawnPosition(EntityLivingBase caster, List placedPositions, float minSeparation) { double spawnX = caster.posX; double spawnZ = caster.posZ; @@ -227,9 +201,6 @@ public abstract class AbilityZone extends Ability { return new double[]{spawnX, spawnZ}; } - /** - * Apply visual settings to a zone entity. - */ protected void applyVisualToEntity(EntityAbilityZone entity) { entity.applyVisual(groundFill, groundAlpha, rings, ringCount, border, borderSpeed, @@ -238,13 +209,6 @@ public abstract class AbilityZone extends Ability { particleSize, particleGlow); } - // ═════════════════════════════════════════════════════════════════ - // PRESET SUPPORT - // ═════════════════════════════════════════════════════════════════ - - /** - * Apply preset defaults by style name. - */ private void applyPresetDefaults(String styleName) { effects.clear(); particleDir = ""; @@ -307,10 +271,6 @@ public abstract class AbilityZone extends Ability { } } - /** - * Client-only preset enum for the GUI dropdown. - * Not persisted — presets simply set field values. - */ @SideOnly(Side.CLIENT) public enum ZonePreset { DEFAULT, TOXIC, INFERNO, ARCANE, ELECTRIC, FROST; @@ -321,10 +281,6 @@ public abstract class AbilityZone extends Ability { } } - // ═════════════════════════════════════════════════════════════════ - // SHARED NBT - // ═════════════════════════════════════════════════════════════════ - protected void writeZoneNBT(NBTTagCompound nbt) { nbt.setInteger("durationTicks", durationTicks); nbt.setString("zoneShape", zoneShape.name()); @@ -337,7 +293,6 @@ public abstract class AbilityZone extends Ability { nbt.setFloat("lightningDensity", lightningDensity); colorData.writeNBT(nbt); - // Visual layer fields — always written as top-level keys nbt.setBoolean("groundFill", groundFill); nbt.setFloat("groundAlpha", groundAlpha); nbt.setBoolean("rings", rings); @@ -367,7 +322,6 @@ public abstract class AbilityZone extends Ability { this.lightningDensity = nbt.getFloat("lightningDensity"); colorData.readNBT(nbt); - // Visual layer fields this.groundFill = nbt.getBoolean("groundFill"); this.groundAlpha = nbt.getFloat("groundAlpha"); this.rings = nbt.getBoolean("rings"); @@ -384,10 +338,6 @@ public abstract class AbilityZone extends Ability { this.particleGlow = nbt.getBoolean("particleGlow"); } - // ═════════════════════════════════════════════════════════════════ - // SHARED GETTERS & SETTERS - // ═════════════════════════════════════════════════════════════════ - public int getDurationTicks() { return durationTicks; } public void setDurationTicks(int durationTicks) { this.durationTicks = Math.max(1, durationTicks); } @@ -416,7 +366,6 @@ public abstract class AbilityZone extends Ability { public float getLightningDensity() { return lightningDensity; } public void setLightningDensity(float v) { this.lightningDensity = Math.max(0, Math.min(3, v)); } - // Color getters/setters public int getInnerColor() { return colorData.innerColor; } public void setInnerColor(int color) { colorData.innerColor = color; } public int getOuterColor() { return colorData.outerColor; } @@ -424,7 +373,6 @@ public abstract class AbilityZone extends Ability { public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } public void setOuterColorEnabled(boolean enabled) { colorData.outerColorEnabled = enabled; } - // Visual layer getters/setters public boolean isGroundFill() { return groundFill; } public void setGroundFill(boolean v) { this.groundFill = v; } public float getGroundAlpha() { return groundAlpha; } @@ -458,10 +406,6 @@ public abstract class AbilityZone extends Ability { public boolean isParticleGlow() { return particleGlow; } public void setParticleGlow(boolean v) { this.particleGlow = v; } - // ═════════════════════════════════════════════════════════════════ - // SHARED FIELD DEFINITIONS (client-only) - // ═════════════════════════════════════════════════════════════════ - @SideOnly(Side.CLIENT) protected void addPresetFieldDef(List defs) { defs.add(FieldDef.subGuiField("gui.applyPreset", @@ -477,42 +421,36 @@ public abstract class AbilityZone extends Ability { @SideOnly(Side.CLIENT) protected void addVisualFieldDefs(List defs) { defs.addAll(Arrays.asList( - // Ground Fill FieldDef.section("ability.section.ground").tab("ability.tab.visual"), FieldDef.row( FieldDef.boolField("gui.enabled", this::isGroundFill, this::setGroundFill), FieldDef.floatField("gui.alpha", this::getGroundAlpha, this::setGroundAlpha) ).tab("ability.tab.visual"), - // Rings FieldDef.section("ability.section.rings").tab("ability.tab.visual"), FieldDef.row( FieldDef.boolField("gui.enabled", this::isRings, this::setRings), FieldDef.intField("gui.count", this::getRingCount, this::setRingCount).range(1, 5) ).tab("ability.tab.visual"), - // Border FieldDef.section("ability.section.border").tab("ability.tab.visual"), FieldDef.row( FieldDef.boolField("gui.enabled", this::isBorder, this::setBorder), FieldDef.floatField("gui.speed", this::getBorderSpeed, this::setBorderSpeed) ).tab("ability.tab.visual"), - // Accents FieldDef.section("ability.section.accents").tab("ability.tab.visual"), FieldDef.row( FieldDef.boolField("gui.enabled", this::isAccents, this::setAccents), FieldDef.enumField("gui.style", AccentStyle.class, this::getAccentStyleEnum, this::setAccentStyleEnum) ).tab("ability.tab.visual"), - // Lightning FieldDef.section("ability.section.lightning").tab("ability.tab.visual"), FieldDef.row( FieldDef.boolField("gui.enabled", this::isLightning, this::setLightning), FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) ).tab("ability.tab.visual"), - // Particles FieldDef.section("ability.section.particles").tab("ability.tab.visual"), FieldDef.boolField("gui.enabled", this::isParticles, this::setParticles) .tab("ability.tab.visual"), @@ -527,12 +465,10 @@ public abstract class AbilityZone extends Ability { FieldDef.stringField("gui.texture", this::getParticleDir, this::setParticleDir) .tab("ability.tab.visual").visibleWhen(this::isParticles), - // Animation FieldDef.section("ability.section.animation").tab("ability.tab.visual"), FieldDef.floatField("gui.speed", this::getAnimSpeed, this::setAnimSpeed) .tab("ability.tab.visual"), - // Colors FieldDef.section("ability.section.colors").tab("ability.tab.visual"), FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) .tab("ability.tab.visual"), diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java index 2f2bc00e9..34156e362 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -26,7 +26,7 @@ import java.util.UUID; /** * Shared zone entity for Trap and Hazard abilities. - * Handles rendering, positioning, and damage logic. + * ZoneType distinguishes behavior: TRAP (proximity-triggered burst) vs HAZARD (persistent AoE). */ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnData { @@ -76,11 +76,11 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD } } - /** Tiny Y offset above ground to prevent z-clipping */ private static final double GROUND_OFFSET = 0.005; + private static final byte TRIGGER_FLASH_STATUS = 60; // ═══════════════════════════════════════════════════════════════════ - // COMMON PROPERTIES (synced via ByteBuf) + // COMMON PROPERTIES // ═══════════════════════════════════════════════════════════════════ private ZoneType zoneType = ZoneType.TRAP; @@ -99,13 +99,12 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD private float zoneHeight = 2.0f; - // Visual parameters (synced for renderer) private float particleDensity = 1.0f; private float particleScale = 1.0f; private float animSpeed = 1.0f; private float lightningDensity = 1.0f; - // Visual layer parameters (always active) + // Visual layer fields private boolean groundFill = true; private float groundAlpha = 0.25f; private boolean rings = true; @@ -113,18 +112,15 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD private boolean border = true; private float borderSpeed = 1.0f; private boolean accents = true; - private int accentStyle = 0; // AccentStyle ordinal + private int accentStyle = 0; private boolean lightning = false; private boolean particles = true; - private int particleMotion = 0; // ParticleMotion ordinal + private int particleMotion = 0; private String particleDir = ""; private int particleSize = 32; private boolean particleGlow = true; - // Lifetime private long deathWorldTime = -1; - - // Effects private List effects = new ArrayList<>(); // ═══════════════════════════════════════════════════════════════════ @@ -138,6 +134,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD private float damage = 6.0f; private float damageRadius = 0.0f; private float knockback = 0.5f; + private boolean visible = true; // ═══════════════════════════════════════════════════════════════════ // HAZARD-SPECIFIC PROPERTIES @@ -149,21 +146,18 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD private boolean affectsCaster = false; // ═══════════════════════════════════════════════════════════════════ - // RUNTIME STATE (transient) + // RUNTIME STATE // ═══════════════════════════════════════════════════════════════════ - // Trap runtime private transient boolean armed = false; private transient int triggerCount = 0; private transient int ticksSinceLastTrigger = 0; private transient Set triggeredEntities = new HashSet<>(); - private transient int triggerFlashTick = -1; // For visual flash on trigger + private transient int triggerFlashTick = -1; - // Hazard runtime private transient int ticksSinceDamage = 0; private transient Set damagedThisTick = new HashSet<>(); - // Preview mode private boolean previewMode = false; private EntityLivingBase previewOwner = null; @@ -179,11 +173,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.ignoreFrustumCheck = true; } - /** - * Full constructor for creating a zone entity. - * Use the static factory methods for cleaner creation. - * Position is snapped to ground level with a tiny offset to avoid z-clipping. - */ private EntityAbilityZone(World world, ZoneType type, EntityLivingBase owner, double x, double y, double z) { this(world); @@ -194,9 +183,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.setPosition(x, groundY, z); } - /** - * Create a Trap zone entity. - */ public static EntityAbilityZone createTrap(World world, EntityLivingBase owner, double x, double y, double z, ZoneShape shape, @@ -207,6 +193,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD float zoneHeight, float particleDensity, float particleScale, float animSpeed, float lightningDensity, + boolean visible, List effects) { EntityAbilityZone zone = new EntityAbilityZone(world, ZoneType.TRAP, owner, x, y, z); zone.shape = shape; @@ -228,19 +215,16 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD zone.particleScale = particleScale; zone.animSpeed = animSpeed; zone.lightningDensity = lightningDensity; + zone.visible = visible; if (effects != null) { for (AbilityEffect e : effects) { zone.effects.add(e.copy()); } } - // Ready to trigger immediately after arm time zone.ticksSinceLastTrigger = triggerCooldown; return zone; } - /** - * Create a Hazard zone entity. - */ public static EntityAbilityZone createHazard(World world, EntityLivingBase owner, double x, double y, double z, ZoneShape shape, @@ -275,7 +259,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD zone.effects.add(e.copy()); } } - // Ready to deal damage immediately zone.ticksSinceDamage = damageInterval; return zone; } @@ -285,8 +268,15 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD // ═══════════════════════════════════════════════════════════════════ @Override - protected void entityInit() { - // No DataWatcher needed + protected void entityInit() {} + + @Override + public void handleHealthUpdate(byte id) { + if (id == TRIGGER_FLASH_STATUS) { + this.triggerFlashTick = this.ticksExisted; + } else { + super.handleHealthUpdate(id); + } } @Override @@ -297,18 +287,15 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD super.onUpdate(); - // Set death time on first tick if (deathWorldTime < 0 && worldObj != null) { deathWorldTime = worldObj.getTotalWorldTime() + maxTicks; } - // Check lifetime if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { this.setDead(); return; } - // Server handles damage if (!worldObj.isRemote && !previewMode) { switch (zoneType) { case TRAP: @@ -322,11 +309,10 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD } // ═══════════════════════════════════════════════════════════════════ - // TRAP LOGIC (server-only) + // TRAP LOGIC // ═══════════════════════════════════════════════════════════════════ private void tickTrap() { - // Arm time countdown if (!armed) { if (ticksExisted >= armTime) { armed = true; @@ -336,18 +322,15 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD ticksSinceLastTrigger++; - // All triggers used if (maxTriggers > 0 && triggerCount >= maxTriggers) { this.setDead(); return; } - // Cooldown between triggers if (ticksSinceLastTrigger < triggerCooldown) { return; } - // Proximity detection AxisAlignedBB box = AxisAlignedBB.getBoundingBox( posX - triggerRadius, posY - 0.5, posZ - triggerRadius, posX + triggerRadius, posY + zoneHeight, posZ + triggerRadius @@ -419,7 +402,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD anyDamaged = true; } - // Apply knockback only if damage landed if (hit && knockback > 0) { double dx = entity.posX - posX; double dz = entity.posZ - posZ; @@ -430,23 +412,22 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD } } - // Apply effects only if damage landed if (hit) { applyEffects(entity); } } - // Only count the trigger if at least one entity was actually damaged if (anyDamaged) { triggerCount++; ticksSinceLastTrigger = 0; triggeredEntities.add(triggerer.getUniqueID()); triggerFlashTick = ticksExisted; + worldObj.setEntityState(this, TRIGGER_FLASH_STATUS); } } // ═══════════════════════════════════════════════════════════════════ - // HAZARD LOGIC (server-only) + // HAZARD LOGIC // ═══════════════════════════════════════════════════════════════════ private void tickHazard() { @@ -545,12 +526,12 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override @SideOnly(Side.CLIENT) public boolean isInRangeToRenderDist(double distance) { - return distance < 16384.0D; // 128 blocks + return distance < 16384.0D; } @Override public boolean shouldRenderInPass(int pass) { - return pass == 1; // Translucent pass + return pass == 1; } @Override @@ -576,6 +557,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD public boolean isOuterColorEnabled() { return outerColorEnabled; } public float getZoneHeight() { return zoneHeight; } public boolean isArmed() { return armed || ticksExisted >= armTime; } + public boolean isVisible() { return visible; } public int getTriggerFlashTick() { return triggerFlashTick; } public int getDurationTicks() { return durationTicks; } public int getMaxTicks() { return maxTicks; } @@ -584,7 +566,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD public float getAnimSpeed() { return animSpeed; } public float getLightningDensity() { return lightningDensity; } - // Visual layer getters public boolean isGroundFill() { return groundFill; } public float getGroundAlpha() { return groundAlpha; } public boolean isRings() { return rings; } @@ -600,9 +581,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD public int getParticleSize() { return particleSize; } public boolean isParticleGlow() { return particleGlow; } - /** - * Apply visual settings from ability data. - */ public void applyVisual(boolean groundFill, float groundAlpha, boolean rings, int ringCount, boolean border, float borderSpeed, @@ -626,44 +604,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.particleGlow = particleGlow; } - /** - * Apply preset defaults by old style name (for backward compatibility). - */ - private void applyPresetDefaults(String styleName) { - switch (styleName) { - case "TOXIC": - groundFill = true; groundAlpha = 0.30f; rings = true; ringCount = 3; - border = false; borderSpeed = 1.0f; accents = true; accentStyle = 1; - lightning = false; particles = true; particleMotion = 0; particleGlow = true; - break; - case "INFERNO": - groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; - border = true; borderSpeed = 2.0f; accents = true; accentStyle = 2; - lightning = false; particles = true; particleMotion = 0; particleGlow = true; - break; - case "ARCANE": - groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; - border = true; borderSpeed = 0.8f; accents = true; accentStyle = 0; - lightning = false; particles = true; particleMotion = 1; particleGlow = true; - break; - case "ELECTRIC": - groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; - border = false; borderSpeed = 1.0f; accents = false; accentStyle = 0; - lightning = true; particles = true; particleMotion = 2; particleGlow = true; - break; - case "FROST": - groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; - border = true; borderSpeed = 0.3f; accents = true; accentStyle = 0; - lightning = false; particles = true; particleMotion = 1; particleGlow = true; - break; - default: // DEFAULT - groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; - border = true; borderSpeed = 1.0f; accents = true; accentStyle = 0; - lightning = false; particles = false; particleMotion = 0; particleGlow = true; - break; - } - } - // ═══════════════════════════════════════════════════════════════════ // NBT SERIALIZATION // ═══════════════════════════════════════════════════════════════════ @@ -671,16 +611,9 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override protected void readEntityFromNBT(NBTTagCompound nbt) { this.zoneType = ZoneType.values()[nbt.getInteger("ZoneType")]; - - // Shape: read new string key first, fall back to old ordinal (always CIRCLE for old RING/CONE) - if (nbt.hasKey("ShapeName")) { - try { - this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); - } catch (Exception e) { - this.shape = ZoneShape.CIRCLE; - } - } else { - // Legacy: old ordinal data — RING(1) and CONE(2) map to CIRCLE + try { + this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); + } catch (Exception e) { this.shape = ZoneShape.CIRCLE; } @@ -691,51 +624,28 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.innerColor = nbt.getInteger("InnerColor"); this.outerColor = nbt.getInteger("OuterColor"); this.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.hasKey("DeathWorldTime") ? nbt.getLong("DeathWorldTime") : -1; + this.zoneHeight = nbt.getFloat("ZoneHeight"); + this.particleDensity = nbt.getFloat("ParticleDensity"); + this.particleScale = nbt.getFloat("ParticleScale"); + this.animSpeed = nbt.getFloat("AnimSpeed"); + this.lightningDensity = nbt.getFloat("LightningDensity"); + this.deathWorldTime = nbt.getLong("DeathWorldTime"); - // Visual fields — backward compat with old ZoneStyle format - if (nbt.hasKey("ZoneStyle")) { - // OLD FORMAT: apply preset defaults, then overlay CustomVisual - applyPresetDefaults(nbt.getString("ZoneStyle")); - if (nbt.hasKey("CustomVisual")) { - NBTTagCompound cv = nbt.getCompoundTag("CustomVisual"); - this.groundFill = !cv.hasKey("GroundFill") || cv.getBoolean("GroundFill"); - this.groundAlpha = cv.hasKey("GroundAlpha") ? cv.getFloat("GroundAlpha") : 0.25f; - this.rings = !cv.hasKey("Rings") || cv.getBoolean("Rings"); - this.ringCount = cv.hasKey("RingCount") ? cv.getInteger("RingCount") : 3; - this.border = !cv.hasKey("Border") || cv.getBoolean("Border"); - this.borderSpeed = cv.hasKey("BorderSpeed") ? cv.getFloat("BorderSpeed") : 1.0f; - this.accents = !cv.hasKey("Accents") || cv.getBoolean("Accents"); - this.accentStyle = cv.hasKey("AccentStyle") ? cv.getInteger("AccentStyle") : 0; - this.lightning = cv.hasKey("Lightning") && cv.getBoolean("Lightning"); - this.particles = !cv.hasKey("Particles") || cv.getBoolean("Particles"); - this.particleMotion = cv.hasKey("ParticleMotion") ? cv.getInteger("ParticleMotion") : 0; - this.particleDir = cv.hasKey("ParticleDir") ? cv.getString("ParticleDir") : ""; - this.particleSize = cv.hasKey("ParticleSize") ? cv.getInteger("ParticleSize") : 32; - this.particleGlow = !cv.hasKey("ParticleGlow") || cv.getBoolean("ParticleGlow"); - } - } else { - // NEW FORMAT: read individual top-level keys - this.groundFill = !nbt.hasKey("GroundFill") || nbt.getBoolean("GroundFill"); - this.groundAlpha = nbt.hasKey("GroundAlpha") ? nbt.getFloat("GroundAlpha") : 0.25f; - this.rings = !nbt.hasKey("Rings") || nbt.getBoolean("Rings"); - this.ringCount = nbt.hasKey("RingCount") ? nbt.getInteger("RingCount") : 3; - this.border = !nbt.hasKey("Border") || nbt.getBoolean("Border"); - this.borderSpeed = nbt.hasKey("BorderSpeed") ? nbt.getFloat("BorderSpeed") : 1.0f; - this.accents = !nbt.hasKey("Accents") || nbt.getBoolean("Accents"); - this.accentStyle = nbt.hasKey("AccentStyle") ? nbt.getInteger("AccentStyle") : 0; - this.lightning = nbt.hasKey("Lightning") && nbt.getBoolean("Lightning"); - this.particles = !nbt.hasKey("Particles") || nbt.getBoolean("Particles"); - this.particleMotion = nbt.hasKey("ParticleMotion") ? nbt.getInteger("ParticleMotion") : 0; - this.particleDir = nbt.hasKey("ParticleDir") ? nbt.getString("ParticleDir") : ""; - this.particleSize = nbt.hasKey("ParticleSize") ? nbt.getInteger("ParticleSize") : 32; - this.particleGlow = !nbt.hasKey("ParticleGlow") || nbt.getBoolean("ParticleGlow"); - } + // 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"); @@ -745,6 +655,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.damage = nbt.getFloat("Damage"); this.damageRadius = nbt.getFloat("DamageRadius"); this.knockback = nbt.getFloat("Knockback"); + this.visible = nbt.getBoolean("Visible"); // Hazard this.damagePerSecond = nbt.getFloat("DamagePerSecond"); @@ -783,7 +694,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD nbt.setFloat("LightningDensity", lightningDensity); nbt.setLong("DeathWorldTime", deathWorldTime); - // Visual fields — always written as top-level keys + // Visual layer fields nbt.setBoolean("GroundFill", groundFill); nbt.setFloat("GroundAlpha", groundAlpha); nbt.setBoolean("Rings", rings); @@ -807,6 +718,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD nbt.setFloat("Damage", damage); nbt.setFloat("DamageRadius", damageRadius); nbt.setFloat("Knockback", knockback); + nbt.setBoolean("Visible", visible); // Hazard nbt.setFloat("DamagePerSecond", damagePerSecond); @@ -843,7 +755,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD buffer.writeFloat(animSpeed); buffer.writeFloat(lightningDensity); - // Visual fields — always written individually + // Visual layer fields buffer.writeBoolean(groundFill); buffer.writeFloat(groundAlpha); buffer.writeBoolean(rings); @@ -859,10 +771,11 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD buffer.writeInt(particleSize); buffer.writeBoolean(particleGlow); - // Trap-specific (client needs armTime for visual state) + // Trap-specific buffer.writeInt(armTime); + buffer.writeBoolean(visible); - // Effects via NBT in buffer + // Effects NBTTagCompound effectsNbt = new NBTTagCompound(); NBTTagList effectList = new NBTTagList(); for (AbilityEffect effect : effects) { @@ -894,7 +807,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.animSpeed = buffer.readFloat(); this.lightningDensity = buffer.readFloat(); - // Visual fields — always read individually + // Visual layer fields this.groundFill = buffer.readBoolean(); this.groundAlpha = buffer.readFloat(); this.rings = buffer.readBoolean(); @@ -911,8 +824,9 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.particleGlow = buffer.readBoolean(); this.armTime = buffer.readInt(); + this.visible = buffer.readBoolean(); - // Effects via NBT + // Effects NBTTagCompound effectsNbt = ByteBufUtils.readTag(buffer); effects.clear(); if (effectsNbt != null && effectsNbt.hasKey("Effects")) { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java b/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java new file mode 100644 index 000000000..b8fb9e376 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; + +@SideOnly(Side.CLIENT) +public class SubGuiTrapPresetSelector extends SubGuiInterface { + + public String selectedPreset = null; + + private static final String[] PRESET_NAMES = {"HIDDEN", "VENOM", "EXPLOSIVE", "CURSED", "SHOCK", "SNARE"}; + private static final String[] PRESET_LABELS = { + "ability.preset.hidden", "ability.preset.venom", "ability.preset.explosive", + "ability.preset.cursed", "ability.preset.shock", "ability.preset.snare" + }; + private static final int[] PRESET_COLORS = {0x888888, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF}; + + public SubGuiTrapPresetSelector() { + xSize = 170; + ySize = 135; + setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + int btnW = 72; + int btnH = 20; + int gapY = 4; + int col1 = guiLeft + 7; + int col2 = col1 + btnW + 6; + int startY = guiTop + 22; + + for (int i = 0; i < 6; i++) { + int x = (i % 2 == 0) ? col1 : col2; + int y = startY + (i / 2) * (btnH + gapY); + addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i])); + } + + int cancelY = startY + 3 * (btnH + gapY) + 4; + addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton btn) { + super.actionPerformed(btn); + if (btn.id >= 0 && btn.id < 6) { + selectedPreset = PRESET_NAMES[btn.id]; + close(); + } else if (btn.id == 10) { + close(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + super.drawScreen(mouseX, mouseY, f); + drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF); + for (int i = 0; i < 6; i++) { + GuiNpcButton btn = getButton(i); + if (btn != null && btn.visible) { + int x = btn.xPosition + 4; + int y = btn.yPosition + 5; + drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]); + } + } + } +} diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index f265f0fe9..eaaf48a45 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1578,6 +1578,12 @@ ability.preset.inferno=Inferno ability.preset.arcane=Arcane ability.preset.electric=Electric ability.preset.frost=Frost +ability.preset.hidden=Hidden +ability.preset.venom=Venom +ability.preset.explosive=Explosive +ability.preset.cursed=Cursed +ability.preset.shock=Shock +ability.preset.snare=Snare # Accent Styles ability.accentStyle.static=Static From ce24c0a4ff4d63676d53396f096fb72df2390ab8 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 19:21:30 -0500 Subject: [PATCH 64/76] Enhance ability selection and display: add toggleable ability handling, improve ability name color coding, and update ability selection messaging --- .../kamkeel/npcs/command/AbilityCommand.java | 4 +-- .../data/ability/AbilityController.java | 18 +++++++--- .../controllers/data/ability/AbilitySlot.java | 34 ++++++++++++++++++- .../npcs/entity/EntityAbilityBeam.java | 20 +++++++++++ .../npcs/entity/EntityAbilityProjectile.java | 16 +++++---- .../noppes/npcs/client/ClientTickHandler.java | 4 ++- .../client/gui/advanced/GuiNPCAbilities.java | 6 ++-- 7 files changed, 86 insertions(+), 16 deletions(-) diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java index 004274fc3..90d20ea1e 100644 --- a/src/main/java/kamkeel/npcs/command/AbilityCommand.java +++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java @@ -306,8 +306,8 @@ public class AbilityCommand extends CommandKamkeelBase { } /** - * Get list of player-usable ability keys (for tab completion). - * Uses registry keys for built-in abilities (no spaces) and UUIDs for custom. + * Get list of player-usable ability names (for tab completion). + * Uses registry keys for built-in abilities and display names for custom abilities. * Used by CommandKamkeel for usage token. */ public static List getPlayerAbilityNames() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 992c56cd9..43af10b7c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -304,7 +304,13 @@ public class AbilityController implements IAbilityHandler { keys.add(id); } } - keys.addAll(customAbilities.keySet()); + // Use ability names for custom abilities (instead of UUIDs) for readable tab completion + for (Ability ability : customAbilities.values()) { + String name = ability.getName(); + if (name != null && !name.isEmpty()) { + keys.add(name); + } + } return keys; } @@ -318,9 +324,13 @@ public class AbilityController implements IAbilityHandler { } } } - for (Map.Entry entry : customAbilities.entrySet()) { - if (entry.getValue().getAllowedBy().allowsPlayer()) { - keys.add(entry.getKey()); + // Use ability names for custom abilities (instead of UUIDs) for readable tab completion + for (Ability ability : customAbilities.values()) { + if (ability.getAllowedBy().allowsPlayer()) { + String name = ability.getName(); + if (name != null && !name.isEmpty()) { + keys.add(name); + } } } return keys; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java index 5fde66586..4849e4dd4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java @@ -14,6 +14,9 @@ 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; @@ -67,10 +70,32 @@ public class AbilitySlot { } 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). */ @@ -104,6 +129,9 @@ public class AbilitySlot { 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(); @@ -113,7 +141,11 @@ public class AbilitySlot { if (nbt == null) return null; if (nbt.hasKey("Reference")) { - return reference(nbt.getString("Reference")); + AbilitySlot slot = reference(nbt.getString("Reference")); + if (nbt.hasKey("RefEnabled")) { + slot.enabledOverride = nbt.getBoolean("RefEnabled"); + } + return slot; } // Inline ability diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 0fb58bcfe..6f5b3a64d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -696,6 +696,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Read trail points (relative to origin) trailPoints.clear(); + trailPointAges.clear(); if (nbt.hasKey("Trail")) { NBTTagList trailList = nbt.getTagList("Trail", 10); for (int i = 0; i < trailList.tagCount(); i++) { @@ -707,6 +708,18 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { )); } } + + // Read trail point ages (must match trailPoints size for fading trail) + if (nbt.hasKey("TrailAges")) { + int[] ages = nbt.getIntArray("TrailAges"); + for (int age : ages) { + trailPointAges.add(age); + } + } + // If trail points exist but ages don't (legacy data), initialize ages to 0 + while (trailPointAges.size() < trailPoints.size()) { + trailPointAges.add(0); + } } @Override @@ -733,5 +746,12 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { trailList.appendTag(pointNbt); } nbt.setTag("Trail", trailList); + + // Write trail point ages for fading trail sync + int[] ages = new int[trailPointAges.size()]; + for (int i = 0; i < trailPointAges.size(); i++) { + ages[i] = trailPointAges.get(i); + } + nbt.setIntArray("TrailAges", ages); } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index dee2ed292..9368c5269 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -896,10 +896,10 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.motionY = nbt.getDouble("MotionY"); this.motionZ = nbt.getDouble("MotionZ"); - if (this.worldObj != null && this.worldObj.isRemote) { - this.renderCurrentSize = this.size; - this.prevRenderSize = this.size; - } + // Always initialize render size from NBT size so entities + // loading in from outside render distance render correctly + this.renderCurrentSize = this.size; + this.prevRenderSize = this.size; anchorData.readNBT(nbt); combatData.readNBT(nbt); @@ -965,7 +965,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP NBTTagCompound compound = new NBTTagCompound(); this.writeEntityToNBT(compound); cpw.mods.fml.common.network.ByteBufUtils.writeTag(buffer, compound); - } catch (Exception ignored) {} + } catch (Exception e) { + noppes.npcs.LogWriter.error("Error writing ability projectile spawn data", e); + } } @Override @@ -975,7 +977,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP if (compound != null) { this.readEntityFromNBT(compound); } - } catch (Exception ignored) {} + } catch (Exception e) { + noppes.npcs.LogWriter.error("Error reading ability projectile spawn data", e); + } } // ==================== COLLISION SETTINGS ==================== diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index b4e8738c8..7d82ca0f1 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -63,7 +63,9 @@ public class ClientTickHandler { if (event.phase == Phase.START) { EntityPlayer player = mc.thePlayer; if (player != null) { - boolean specialKeyDown = ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode()); + // Only process special key when no GUI screen is open + boolean specialKeyDown = mc.currentScreen == null + && ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode()); if (specialKeyDown != lastSpecialKeyDown) { PlayerData data = CustomNpcs.proxy.getPlayerData(player); if (data != null) { diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index f8ed53c7c..e927b088f 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -317,9 +317,11 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Toggle selected ability on/off if (id == 77) { if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - Ability ability = npcSlots.get(selectedAbilityIndex).getAbility(); + AbilitySlot slot = npcSlots.get(selectedAbilityIndex); + Ability ability = slot.getAbility(); if (ability != null) { - ability.setEnabled(((GuiNpcButton) guibutton).getValue() == 1); + boolean enabled = ((GuiNpcButton) guibutton).getValue() == 1; + slot.setEnabled(enabled); updateNpcAbilitiesList(); selectAbilityByIndex(selectedAbilityIndex); initGui(); From eda8931b5fa21737fc86a459837269f3399f607d Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 21:29:26 -0500 Subject: [PATCH 65/76] Refactor entity owner checks and enhance FULL_MODEL rotation support in ability entities --- .../npcs/entity/EntityAbilityBeam.java | 45 +++--- .../npcs/entity/EntityAbilityDisc.java | 8 +- .../npcs/entity/EntityAbilityLaser.java | 3 +- .../npcs/entity/EntityAbilityProjectile.java | 28 ++-- .../npcs/entity/EntityAbilitySweeper.java | 12 +- .../kamkeel/npcs/util/AnchorPointHelper.java | 136 +++++++++++++++++- 6 files changed, 175 insertions(+), 57 deletions(-) diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 6f5b3a64d..bfdca5346 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -386,33 +386,26 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { chargeTick++; Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; + if (owner != null) { + Vec3 pos; + if (owner instanceof EntityLivingBase) { + pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData, chargeOffsetDistance); + } else { + float yaw = (float) Math.toRadians(owner.rotationYaw); + double offsetX = -Math.sin(yaw) * chargeOffsetDistance; + double offsetZ = Math.cos(yaw) * chargeOffsetDistance; + pos = Vec3.createVectorHelper( + owner.posX + offsetX, + owner.posY + owner.getEyeHeight() * 0.7, + owner.posZ + offsetZ + ); + } + + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + startX = pos.xCoord; + startY = pos.yCoord; + startZ = pos.zCoord; } - - // Calculate position based on anchor point - Vec3 pos; - if (owner instanceof EntityLivingBase) { - pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData, chargeOffsetDistance); - } else { - // Fallback for non-living entities (shouldn't happen normally) - float yaw = (float) Math.toRadians(owner.rotationYaw); - double offsetX = -Math.sin(yaw) * chargeOffsetDistance; - double offsetZ = Math.cos(yaw) * chargeOffsetDistance; - pos = Vec3.createVectorHelper( - owner.posX + offsetX, - owner.posY + owner.getEyeHeight() * 0.7, - owner.posZ + offsetZ - ); - } - - setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - - // Also update origin for when firing starts - startX = pos.xCoord; - startY = pos.yCoord; - startZ = pos.zCoord; } /** diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index 43fa459fc..c0f3cbe8d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -391,19 +391,13 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { protected void updateCharging() { chargeTick++; - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } - // Grow size based on charge progress float progress = getChargeProgress(); this.discRadius = targetDiscRadius * progress; this.discThickness = targetDiscThickness * progress; this.size = this.discRadius; // Base size for interpolation - // Calculate position based on anchor point, offset downward by half radius to center + Entity owner = getOwnerEntity(); if (owner instanceof EntityLivingBase) { Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); setPosition(pos.xCoord, pos.yCoord, pos.zCoord); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index a10dae0b8..d17024680 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -156,8 +156,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { */ private void updateLaserOriginAndDirection() { Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) return; - if (!(owner instanceof EntityLivingBase)) return; + if (owner == null || !(owner instanceof EntityLivingBase)) return; EntityLivingBase livingOwner = (EntityLivingBase) owner; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index 9368c5269..ac6add74d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -184,16 +184,20 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Skip lifetime/distance checks in preview mode if (!previewMode) { - // Failsafe: if owner entity is gone, dead, or NPC was killed/reset, self-destruct + // Only self-destruct if the owner is confirmed dead/killed. + // A null owner (unloaded/out of chunk) is NOT treated as dead — + // the projectile keeps acting normally and deathWorldTime handles lifetime. if (ownerEntityId >= 0 && ticksExisted > 5) { Entity owner = worldObj.getEntityByID(ownerEntityId); - if (owner == null || owner.isDead) { - this.setDead(); - return; - } - if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { - this.setDead(); - return; + if (owner != null) { + if (owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + this.setDead(); + return; + } } } @@ -506,16 +510,14 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP * Update during charging state - grow size and follow anchor. * Default implementation grows {@code size} from 0 to {@code targetSize}. * Override in subclasses for type-specific charging (Disc, Beam). + * + * Note: Owner death checks are handled by onUpdate() before this is called. */ protected void updateCharging() { chargeTick++; - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } float progress = getChargeProgress(); this.size = targetSize * progress; + Entity owner = getOwnerEntity(); if (owner instanceof EntityLivingBase) { Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); setPosition(pos.xCoord, pos.yCoord, pos.zCoord); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index 4d072090e..6f0068d26 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -144,15 +144,19 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return; } - // Follow owner Entity owner = getOwner(); - if (owner == null) { + if (owner != null && owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { this.setDead(); return; } - // Update position to follow owner - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + if (owner != null) { + this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + } // Check if sweep is done if (completedRotations >= numberOfRotations) { diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index 802841c2a..3c9b10f1d 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -119,6 +119,20 @@ public class AnchorPointHelper { y += rotatedOffset.yCoord; z += rotatedOffset.zCoord; + // Apply FULL_MODEL rotation if active + FramePart fullModel = getFullModelPart(entity); + if (fullModel != null) { + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + Vec3 rotated = applyFullModelToWorldOffset(fullModel, entity, dx, dy, dz, bodyYaw, scale); + return Vec3.createVectorHelper( + entity.posX + rotated.xCoord, + entity.posY + rotated.yCoord, + entity.posZ + rotated.zCoord + ); + } + return Vec3.createVectorHelper(x, y, z); } @@ -162,16 +176,32 @@ public class AnchorPointHelper { /** * Calculate hand position using animation data if available. + * Applies FULL_MODEL rotation if an active animation has it. */ private static Vec3 calculateHandPosition(EntityLivingBase entity, EnergyAnchorData anchor, boolean rightHand, float scale) { // Try to get animated position first - Vec3 animatedPos = getAnimatedHandPosition(entity, anchor, rightHand, scale); - if (animatedPos != null) { - return animatedPos; + Vec3 pos = getAnimatedHandPosition(entity, anchor, rightHand, scale); + if (pos == null) { + // Fallback to static position + pos = calculateFallbackHandPosition(entity, anchor, rightHand, scale); } - // Fallback to static position - return calculateFallbackHandPosition(entity, anchor, rightHand, scale); + // Apply FULL_MODEL rotation if active + FramePart fullModel = getFullModelPart(entity); + if (fullModel != null) { + double dx = pos.xCoord - entity.posX; + double dy = pos.yCoord - entity.posY; + double dz = pos.zCoord - entity.posZ; + float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); + Vec3 rotated = applyFullModelToWorldOffset(fullModel, entity, dx, dy, dz, bodyYaw, scale); + return Vec3.createVectorHelper( + entity.posX + rotated.xCoord, + entity.posY + rotated.yCoord, + entity.posZ + rotated.zCoord + ); + } + + return pos; } /** @@ -390,4 +420,100 @@ public class AnchorPointHelper { double worldZ = -offsetX * sin + offsetZ * cos; return Vec3.createVectorHelper(worldX, offsetY, worldZ); } + + // ==================== FULL_MODEL ANIMATION SUPPORT ==================== + + /** + * Get the FULL_MODEL FramePart if the entity has an active animation with it. + * Returns null if no FULL_MODEL animation is active. + */ + private static FramePart getFullModelPart(EntityLivingBase entity) { + AnimationData animData = AnimationData.getData(entity); + if (animData == null || !animData.isActive() || animData.animation == null) { + return null; + } + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame == null) { + return null; + } + FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); + return part; + } + + /** + * Apply FULL_MODEL rotation to a world-space offset from entity position. + * Converts the offset to model space, applies FULL_MODEL rotation and pivots, + * then converts back to world space. + * + * The rendering pipeline is: entity_pos * body_yaw * scale(-1,-1,1) * FULL_MODEL * parts + * Combined body_yaw + scale maps model space to world space: + * worldX = mx*cos(yaw) + mz*sin(yaw) + * worldY = -my (model Y-down → world Y-up) + * worldZ = mx*sin(yaw) - mz*cos(yaw) + * This transform is its own inverse for X,Z. + * + * FULL_MODEL rotation order matches renderer: vertex sees Z, then Y, then X. + */ + private static Vec3 applyFullModelToWorldOffset(FramePart fullModel, EntityLivingBase entity, + double worldDX, double worldDY, double worldDZ, + float bodyYaw, float scale) { + float[] rotations = getRotations(fullModel, entity); + float[] pivots = getPivots(fullModel, entity); + + // Quick exit if no transform needed + boolean hasRotation = rotations[0] != 0 || rotations[1] != 0 || rotations[2] != 0; + boolean hasPivot = pivots[0] != 0 || pivots[1] != 0 || pivots[2] != 0; + if (!hasRotation && !hasPivot) { + return Vec3.createVectorHelper(worldDX, worldDY, worldDZ); + } + + // Convert world offset to model space + // Body yaw + scale combined transform is an involution (self-inverse) for X,Z + double cosYaw = Math.cos(bodyYaw); + double sinYaw = Math.sin(bodyYaw); + + double mx = worldDX * cosYaw + worldDZ * sinYaw; + double mz = worldDX * sinYaw - worldDZ * cosYaw; + double my = -worldDY; // Invert Y (world Y-up → model Y-down) + + // Apply FULL_MODEL rotations (vertex order: Z first, then Y, then X) + // Matches renderer: glRotatef(X), glRotatef(Y), glRotatef(Z) → vertex sees Z,Y,X + + // Z rotation + double cosZ = Math.cos(rotations[2]); + double sinZ = Math.sin(rotations[2]); + double nx = mx * cosZ - my * sinZ; + double ny = mx * sinZ + my * cosZ; + mx = nx; + my = ny; + + // Y rotation + double cosY = Math.cos(rotations[1]); + double sinY = Math.sin(rotations[1]); + nx = mx * cosY + mz * sinY; + double nz = -mx * sinY + mz * cosY; + mx = nx; + mz = nz; + + // X rotation + double cosX = Math.cos(rotations[0]); + double sinX = Math.sin(rotations[0]); + ny = my * cosX - mz * sinX; + nz = my * sinX + mz * cosX; + my = ny; + mz = nz; + + // Apply pivots in model space (after rotation, matching GL vertex ordering) + // Renderer: glTranslatef(px, -py, pz) → pivot Y is negated for model Y-down space + mx += pivots[0] * MODEL_SCALE * scale; + my -= pivots[1] * MODEL_SCALE * scale; + mz += pivots[2] * MODEL_SCALE * scale; + + // Convert back to world space (same involution for X,Z; invert Y back) + double newDX = mx * cosYaw + mz * sinYaw; + double newDZ = mx * sinYaw - mz * cosYaw; + double newDY = -my; + + return Vec3.createVectorHelper(newDX, newDY, newDZ); + } } From 3beaf6881508ab984f8179a775767309eae2f52a Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 21:44:36 -0500 Subject: [PATCH 66/76] Update GuiNPCAbilities.java --- .../client/gui/advanced/GuiNPCAbilities.java | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index e927b088f..2e89d3d49 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -491,8 +491,31 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC for (int i = 0; i < npcSlots.size(); i++) { list.add(getAbilityListEntry(i)); } + + // Sort: enabled first, then numerically by slot index + Collections.sort(list, new Comparator() { + @Override + public int compare(String a, String b) { + boolean aEnabled = a.startsWith("\u00A7a"); + boolean bEnabled = b.startsWith("\u00A7a"); + if (aEnabled != bEnabled) return aEnabled ? -1 : 1; + return extractIndex(a) - extractIndex(b); + } + + private int extractIndex(String entry) { + String stripped = entry.replaceAll("\u00A7.", "").trim(); + int dotIndex = stripped.indexOf("."); + if (dotIndex > 0) { + try { + return Integer.parseInt(stripped.substring(0, dotIndex).replaceAll("[^0-9]", "")); + } catch (NumberFormatException e) { } + } + return Integer.MAX_VALUE; + } + }); + if (npcAbilitiesScroll != null) { - npcAbilitiesScroll.setList(list); + npcAbilitiesScroll.setUnsortedList(list); } } From 248dbf66da17e3781e69d80ffd44b6e0f81fb4e2 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 22:03:32 -0500 Subject: [PATCH 67/76] Enhance ability animation handling: track ability animation state, clear orphaned animations on login, and ensure proper animation continuation --- .../controllers/data/PlayerAbilityData.java | 27 +++++++++++++++++++ .../npcs/controllers/data/PlayerData.java | 18 +++++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index f0a4c8c70..22ec80c4b 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -54,6 +54,13 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private int selectedIndex = 0; + /** + * Tracks whether the current animation was started by an ability. + * Persisted to NBT so orphaned ability animations can be detected and + * cleared on login (ability state is transient, but animation state is not). + */ + private boolean playingAbilityAnimation = false; + // ═══════════════════════════════════════════════════════════════════ // RUNTIME STATE (not saved) // ═══════════════════════════════════════════════════════════════════ @@ -779,6 +786,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { playerData.animationData.setEnabled(true); playerData.animationData.setAnimation(animation); playerData.animationData.updateClient(); + playingAbilityAnimation = true; } public void playAbilityAnimation(int animation) { @@ -800,6 +808,23 @@ public class PlayerAbilityData implements IPlayerAbilityData { private void stopAbilityAnimation() { playerData.animationData.setAnimation(null); playerData.animationData.updateClient(); + playingAbilityAnimation = false; + } + + /** + * Returns true if an ability-driven animation is currently playing. + * Used by PlayerData.onLogin() to detect orphaned ability animations. + */ + public boolean isPlayingAbilityAnimation() { + return playingAbilityAnimation; + } + + /** + * Clears an orphaned ability animation (e.g. after relog when the ability is gone). + * Stops the animation and resets the tracking flag. + */ + public void clearOrphanedAbilityAnimation() { + stopAbilityAnimation(); } private void playAbilitySound(EntityPlayer player, String sound) { @@ -819,6 +844,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { } compound.setTag("PlayerAbilities", list); compound.setInteger("PlayerAbilitySelected", selectedIndex); + compound.setBoolean("AbilityAnimating", playingAbilityAnimation); } public void readFromNBT(NBTTagCompound compound) { @@ -836,5 +862,6 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (selectedIndex >= unlockedAbilities.size()) { selectedIndex = Math.max(0, unlockedAbilities.size() - 1); } + playingAbilityAnimation = compound.getBoolean("AbilityAnimating"); } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index fa4e7d961..02fd67563 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -95,13 +95,21 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { private boolean specialKeyDown = false; public void onLogin() { - // Continue playing animation for self when re-logging + // Handle animation state from previous session AnimationData animationData = this.animationData; if (animationData != null && animationData.isClientAnimating()) { - Animation currentAnimation = animationData.currentClientAnimation; - NBTTagCompound compound = currentAnimation.writeToNBT(); - animationData.viewAnimation(currentAnimation, animationData, compound, - animationData.isClientAnimating(), currentAnimation.currentFrame, currentAnimation.currentFrameTime); + if (abilityData.isPlayingAbilityAnimation()) { + // Ability animation was playing when player disconnected. + // Ability state is transient (lost on disconnect), so this animation + // is orphaned - clear it instead of replaying a stuck animation. + abilityData.clearOrphanedAbilityAnimation(); + } else { + // Non-ability animation (e.g. script-driven) - continue playing + Animation currentAnimation = animationData.currentClientAnimation; + NBTTagCompound compound = currentAnimation.writeToNBT(); + animationData.viewAnimation(currentAnimation, animationData, compound, + animationData.isClientAnimating(), currentAnimation.currentFrame, currentAnimation.currentFrameTime); + } } CustomEffectController controller = CustomEffectController.getInstance(); From 1fb52a4ae90ca035fdb7fdc3641999c823b62e67 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 22:04:47 -0500 Subject: [PATCH 68/76] Refactor movement abilities: extract shared logic into AbilityMovement class for Charge and Dash abilities --- .../data/ability/type/AbilityCharge.java | 138 ++------- .../data/ability/type/AbilityDash.java | 111 ++----- .../data/ability/type/AbilityMovement.java | 270 ++++++++++++++++++ 3 files changed, 316 insertions(+), 203 deletions(-) create mode 100644 src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java 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 871249885..780ddc050 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 @@ -2,7 +2,6 @@ package kamkeel.npcs.controllers.data.ability.type; 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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.telegraph.Telegraph; @@ -12,8 +11,6 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.Vec3; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; @@ -25,9 +22,10 @@ import java.util.List; import java.util.Set; /** - * Charge ability: Rush attack where NPC charges in a line, damaging all targets hit. + * Charge ability: Rush attack where the caster charges in a line, damaging all targets hit. + * Extends AbilityMovement for shared direction locking, stall detection, and velocity application. */ -public class AbilityCharge extends Ability implements IAbilityCharge { +public class AbilityCharge extends AbilityMovement implements IAbilityCharge { // Type-specific parameters private float chargeSpeed = 0.8f; @@ -35,13 +33,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { private float knockback = 3.0f; private float hitWidth = 1.5f; - // Runtime state (transient) - private transient double startX, startY, startZ; - private transient double prevTickX, prevTickZ; - private transient Vec3 chargeDirection; + // Type-specific runtime state private transient Set hitEntities = new HashSet<>(); - private transient float lockedYaw; - private transient int maxActiveTicks; public AbilityCharge() { this.typeId = "ability.cnpc.charge"; @@ -71,138 +64,68 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public boolean hasAbilityMovement() { - return true; // This ability moves the NPC - } - /** * Called on the first tick of windup - lock direction here so it matches telegraph. */ @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (tick == 1) { - // Lock direction on first windup tick (same time telegraph is created) - lockChargeDirection(caster, target); + lockDirection(caster, target); } - // Keep caster facing the locked direction during windup enforceLockedRotation(caster); } - /** - * Locks the charge direction. Called once at windup start — direction won't change even if target moves. - * NPC: charges toward aggro target. - * Player: charges in look direction. - */ - private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) { - if (!isPlayerCaster(caster) && target != null) { - // NPC: charge toward aggro target - double dx = target.posX - caster.posX; - double dz = target.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - chargeDirection = Vec3.createVectorHelper(dx / len, 0, dz / len); - } else { - float yaw = (float) Math.toRadians(caster.rotationYaw); - chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); - } - } else { - // Player: charge in look direction - float yaw = (float) Math.toRadians(caster.rotationYaw); - chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); - } - lockedYaw = (float) Math.toDegrees(Math.atan2(-chargeDirection.xCoord, chargeDirection.zCoord)); - } - @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target) { - // Initialize charge - direction was already locked during windup - startX = caster.posX; - startY = caster.posY; - startZ = caster.posZ; - prevTickX = caster.posX; - prevTickZ = caster.posZ; + initMovement(caster, maxRange, chargeSpeed); hitEntities.clear(); - // Safety timeout: expected ticks + buffer to prevent infinite charge - maxActiveTicks = chargeSpeed > 0 ? (int)(maxRange / chargeSpeed) + 10 : 10; - // If direction wasn't set during windup (shouldn't happen), set it now - if (chargeDirection == null) { - lockChargeDirection(caster, target); + if (movementDirection == null) { + lockDirection(caster, target); } enforceLockedRotation(caster); } - private void enforceLockedRotation(EntityLivingBase caster) { - caster.rotationYaw = lockedYaw; - caster.rotationYawHead = lockedYaw; - caster.prevRotationYaw = lockedYaw; - caster.prevRotationYawHead = lockedYaw; - caster.renderYawOffset = lockedYaw; - caster.prevRenderYawOffset = lockedYaw; - } - @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { - // Safety timeout or missing state: force-complete to prevent stuck NPC - if (!isPreview() && (chargeDirection == null || tick > maxActiveTicks)) { + if (checkTimeout(tick)) { stopMomentum(caster); signalCompletion(); return; } - if (chargeDirection == null) { + if (movementDirection == null) { signalCompletion(); return; } - // Enforce rotation every tick if (!isPreview()) { enforceLockedRotation(caster); } - // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall - if (!isPreview() && tick > 1) { - double dx = caster.posX - prevTickX; - double dz = caster.posZ - prevTickZ; - if (dx * dx + dz * dz < 0.0001) { - stopMomentum(caster); - signalCompletion(); - return; - } + if (checkStall(caster, tick)) { + stopMomentum(caster); + signalCompletion(); + return; } - prevTickX = caster.posX; - prevTickZ = caster.posZ; + updatePrevPosition(caster); - // Calculate distance traveled - double distanceTraveled = Math.sqrt( - Math.pow(caster.posX - startX, 2) + - Math.pow(caster.posZ - startZ, 2) - ); - - // Check if reached max distance - if (distanceTraveled >= maxRange) { + if (getDistanceTraveled(caster) >= maxRange) { stopMomentum(caster); signalCompletion(); return; } - // Block detection (skip in preview - no real world collision) - if (!isPreview() && isChargeBlocked(caster)) { + if (checkBlocked(caster, chargeSpeed)) { stopMomentum(caster); signalCompletion(); return; } - // Move caster - caster.motionX = chargeDirection.xCoord * chargeSpeed; - caster.motionY = 0; - caster.motionZ = chargeDirection.zCoord * chargeSpeed; - if (!isPreview()) { - caster.velocityChanged = true; - } + // Move caster (flat: zero vertical motion) + applyVelocityFlat(caster, chargeSpeed); // Server-side collision damage (skip in preview) if (!caster.worldObj.isRemote && !isPreview()) { @@ -218,14 +141,11 @@ public class AbilityCharge extends Ability implements IAbilityCharge { EntityLivingBase livingEntity = (EntityLivingBase) entity; - // Hit this entity hitEntities.add(entity.getEntityId()); - // Apply damage with scripted event support boolean wasHit = applyAbilityDamageWithDirection(caster, livingEntity, damage, knockback, - chargeDirection.xCoord, chargeDirection.zCoord); + movementDirection.xCoord, movementDirection.zCoord); - // Apply effects and play impact sound if hit wasn't cancelled if (wasHit) { applyEffects(livingEntity); caster.worldObj.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f); @@ -246,24 +166,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { super.onInterrupt(caster, source, damage); } - private void stopMomentum(EntityLivingBase caster) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; - } - } - - private boolean isChargeBlocked(EntityLivingBase caster) { - return isMovementBlocked(caster, chargeDirection.xCoord, chargeDirection.zCoord, chargeSpeed); - } - @Override - public void reset() { - super.reset(); - chargeDirection = null; + public void cleanup() { + super.cleanup(); hitEntities.clear(); - maxActiveTicks = 0; } @Override 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 8dbd13c92..41c5faaa1 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 @@ -2,16 +2,12 @@ package kamkeel.npcs.controllers.data.ability.type; 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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; -import net.minecraft.util.Vec3; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.api.ability.type.IAbilityDash; @@ -22,9 +18,9 @@ import java.util.Random; /** * Dash ability: Quick evasive sidestep with NO telegraph. - * Defensive repositioning move to evade attacks. + * Extends AbilityMovement for shared direction locking, stall detection, and velocity application. */ -public class AbilityDash extends Ability implements IAbilityDash { +public class AbilityDash extends AbilityMovement implements IAbilityDash { /** * Dash behavior mode. @@ -88,12 +84,8 @@ public class AbilityDash extends Ability implements IAbilityDash { private float dashDistance = 4.0f; private float dashSpeed = 0.5f; - // Runtime state - private transient Vec3 dashDirection; - private transient double startX, startY, startZ; - private transient double prevTickX, prevTickZ; + // Type-specific runtime state private transient DashDirection chosenDirection; - private transient int maxActiveTicks; public AbilityDash() { this.typeId = "ability.cnpc.dash"; @@ -126,21 +118,9 @@ public class AbilityDash extends Ability implements IAbilityDash { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public boolean hasAbilityMovement() { - return true; // This ability moves the NPC - } - @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target) { - startX = caster.posX; - startY = caster.posY; - startZ = caster.posZ; - prevTickX = caster.posX; - prevTickZ = caster.posZ; - - // Safety timeout: expected ticks + generous buffer to prevent infinite dash - maxActiveTicks = dashSpeed > 0 ? (int)(dashDistance / dashSpeed) + 10 : 10; + initMovement(caster, dashDistance, dashSpeed); // Choose random direction based on mode DashDirection[] directions = dashMode == DashMode.AGGRESSIVE @@ -148,26 +128,10 @@ public class AbilityDash extends Ability implements IAbilityDash { : DEFENSIVE_DIRECTIONS; chosenDirection = directions[RANDOM.nextInt(directions.length)]; - // NPC: dash direction is relative to aggro target facing - // Player: dash direction is relative to look direction - float baseYaw; - if (!isPlayerCaster(caster) && target != null) { - double dx = target.posX - caster.posX; - double dz = target.posZ - caster.posZ; - baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); - } else { - baseYaw = caster.rotationYaw; - } - - // Apply direction offset + // Calculate direction: base yaw (toward target or look dir) + direction offset + float baseYaw = getBaseYaw(caster, target); float dashYaw = baseYaw + chosenDirection.getAngleOffset(); - float yawRad = (float) Math.toRadians(dashYaw); - - dashDirection = Vec3.createVectorHelper( - -Math.sin(yawRad), - 0, - Math.cos(yawRad) - ); + setDirectionFromYaw(dashYaw); // Small upward impulse for a skip/hop arc (gravity handles the descent) caster.motionY = 0.2; @@ -175,86 +139,59 @@ public class AbilityDash extends Ability implements IAbilityDash { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { - // Safety timeout or missing state: force-complete to prevent stuck NPC - if (!isPreview() && (dashDirection == null || tick > maxActiveTicks)) { - stopDash(caster); + if (checkTimeout(tick)) { + stopMomentum(caster); signalCompletion(); return; } - if (dashDirection == null) { + if (movementDirection == null) { signalCompletion(); return; } - // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall - if (!isPreview() && tick > 1) { - double dx = caster.posX - prevTickX; - double dz = caster.posZ - prevTickZ; - if (dx * dx + dz * dz < 0.0001) { - stopDash(caster); - signalCompletion(); - return; - } + if (checkStall(caster, tick)) { + stopMomentum(caster); + signalCompletion(); + return; } - prevTickX = caster.posX; - prevTickZ = caster.posZ; + updatePrevPosition(caster); - // Check if reached max distance - double travelDx = caster.posX - startX; - double travelDz = caster.posZ - startZ; - if (travelDx * travelDx + travelDz * travelDz >= (double) dashDistance * dashDistance) { - stopDash(caster); + if (getDistanceTraveledSq(caster) >= (double) dashDistance * dashDistance) { + stopMomentum(caster); signalCompletion(); return; } - // Block detection (skip in preview - no real world collision) - if (!isPreview() && isDashBlocked(caster)) { - stopDash(caster); + if (checkBlocked(caster, dashSpeed)) { + stopMomentum(caster); signalCompletion(); return; } // Move caster (motionY left to gravity for skip arc) - caster.motionX = dashDirection.xCoord * dashSpeed; - caster.motionZ = dashDirection.zCoord * dashSpeed; - if (!isPreview()) { - caster.velocityChanged = true; + applyVelocity(caster, dashSpeed); + if (!isPreview()) { // Trail particles caster.worldObj.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); } } - private void stopDash(EntityLivingBase caster) { - caster.motionX = 0; - caster.motionZ = 0; - if (!isPreview()) { - caster.velocityChanged = true; - } - } - @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - stopDash(caster); + stopMomentum(caster); } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - stopDash(caster); + stopMomentum(caster); } @Override public void cleanup() { - dashDirection = null; + super.cleanup(); chosenDirection = null; - maxActiveTicks = 0; - } - - private boolean isDashBlocked(EntityLivingBase caster) { - if (dashDirection == null) return true; - return isMovementBlocked(caster, dashDirection.xCoord, dashDirection.zCoord, dashSpeed); } @Override 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 new file mode 100644 index 000000000..de2090cc3 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java @@ -0,0 +1,270 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.Vec3; + +/** + * Abstract base class for abilities that move the caster along the ground + * in a specific direction (Charge, Dash, etc.). + *

+ * Provides shared movement logic: direction locking, stall detection with + * player-aware grace period, velocity application, distance tracking, + * rotation enforcement, and wall collision checking. + *

+ * NOT for ballistic/arc movement (Slam uses a different pattern). + */ +public abstract class AbilityMovement extends Ability { + + /** + * Grace period (in active ticks) before stall detection activates. + * Players need more time because: + * - Server sets motionX/Z and sends S12 velocity packet to client + * - Client receives S12 and starts moving + * - Client sends C03 position packet with updated position back to server + * 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 NPC_STALL_GRACE_TICKS = 2; + + // ═══════════════════════════════════════════════════════════════════ + // COMMON MOVEMENT STATE (transient, not saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + protected transient double startX, startY, startZ; + protected transient double prevTickX, prevTickZ; + protected transient Vec3 movementDirection; + protected transient float lockedYaw; + protected transient int maxActiveTicks; + + // ═══════════════════════════════════════════════════════════════════ + // OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean hasAbilityMovement() { + return true; + } + + @Override + public void cleanup() { + movementDirection = null; + maxActiveTicks = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // DIRECTION HELPERS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Lock direction based on caster type. + * NPC: toward target. Player: look direction. + */ + protected void lockDirection(EntityLivingBase caster, EntityLivingBase target) { + if (!isPlayerCaster(caster) && target != null) { + lockDirectionToTarget(caster, target); + } else { + lockDirectionFromLook(caster); + } + } + + /** + * Lock direction to the caster's look direction (horizontal only). + */ + protected void lockDirectionFromLook(EntityLivingBase caster) { + float yaw = (float) Math.toRadians(caster.rotationYaw); + movementDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); + lockedYaw = computeYawFromDirection(); + } + + /** + * Lock direction toward a target entity. + * Falls back to look direction if target is at the same position. + */ + protected void lockDirectionToTarget(EntityLivingBase caster, EntityLivingBase target) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dz * dz); + if (len > 0) { + movementDirection = Vec3.createVectorHelper(dx / len, 0, dz / len); + lockedYaw = computeYawFromDirection(); + } else { + lockDirectionFromLook(caster); + } + } + + /** + * Get the base yaw for direction calculation. + * NPC: yaw toward target. Player: current look yaw. + */ + protected float getBaseYaw(EntityLivingBase caster, EntityLivingBase target) { + if (!isPlayerCaster(caster) && target != null) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + return (float) Math.toDegrees(Math.atan2(-dx, dz)); + } + return caster.rotationYaw; + } + + /** + * Set movement direction from a yaw angle (degrees). + */ + protected void setDirectionFromYaw(float yawDegrees) { + float yawRad = (float) Math.toRadians(yawDegrees); + movementDirection = Vec3.createVectorHelper(-Math.sin(yawRad), 0, Math.cos(yawRad)); + lockedYaw = yawDegrees; + } + + // ═══════════════════════════════════════════════════════════════════ + // MOVEMENT INITIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Initialize movement tracking. Call from onExecute(). + * + * @param caster The entity performing the movement + * @param distance Maximum travel distance (for timeout computation) + * @param speed Movement speed in blocks/tick (for timeout computation) + */ + protected void initMovement(EntityLivingBase caster, float distance, float speed) { + startX = caster.posX; + startY = caster.posY; + startZ = caster.posZ; + prevTickX = caster.posX; + prevTickZ = caster.posZ; + maxActiveTicks = speed > 0 ? (int) (distance / speed) + 10 : 10; + } + + // ═══════════════════════════════════════════════════════════════════ + // ACTIVE TICK CHECKS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check for timeout or missing movement direction. + * + * @return true if the ability should stop + */ + protected boolean checkTimeout(int tick) { + return !isPreview() && (movementDirection == null || tick > maxActiveTicks); + } + + /** + * Check stall detection with appropriate grace period for player vs NPC. + * Players need a longer grace period because velocity sync via S12 packet + * takes time to reach the client, and C03 position packets lag behind. + * + * @return true if the entity is stalled (not moving) + */ + protected boolean checkStall(EntityLivingBase caster, int tick) { + if (isPreview()) return false; + int graceTicks = isPlayerCaster(caster) ? PLAYER_STALL_GRACE_TICKS : NPC_STALL_GRACE_TICKS; + if (tick <= graceTicks) return false; + + double dx = caster.posX - prevTickX; + double dz = caster.posZ - prevTickZ; + return dx * dx + dz * dz < 0.0001; + } + + /** + * Update previous tick position for stall detection. + * Call after stall check, before movement application. + */ + protected void updatePrevPosition(EntityLivingBase caster) { + prevTickX = caster.posX; + prevTickZ = caster.posZ; + } + + /** + * Get total linear distance traveled from start position. + */ + protected double getDistanceTraveled(EntityLivingBase caster) { + double dx = caster.posX - startX; + double dz = caster.posZ - startZ; + return Math.sqrt(dx * dx + dz * dz); + } + + /** + * Get total distance traveled squared (more efficient for comparison). + */ + protected double getDistanceTraveledSq(EntityLivingBase caster) { + double dx = caster.posX - startX; + double dz = caster.posZ - startZ; + return dx * dx + dz * dz; + } + + /** + * Check if movement direction is blocked by walls. + * + * @return true if blocked + */ + protected boolean checkBlocked(EntityLivingBase caster, float speed) { + if (isPreview() || movementDirection == null) return false; + return isMovementBlocked(caster, movementDirection.xCoord, movementDirection.zCoord, speed); + } + + // ═══════════════════════════════════════════════════════════════════ + // VELOCITY APPLICATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Apply movement velocity to the caster (horizontal only, Y unchanged). + */ + protected void applyVelocity(EntityLivingBase caster, float speed) { + caster.motionX = movementDirection.xCoord * speed; + caster.motionZ = movementDirection.zCoord * speed; + if (!isPreview()) { + caster.velocityChanged = true; + } + } + + /** + * Apply movement velocity with zero vertical motion. + * Used for ground-locked movement like Charge. + */ + protected void applyVelocityFlat(EntityLivingBase caster, float speed) { + caster.motionX = movementDirection.xCoord * speed; + caster.motionY = 0; + caster.motionZ = movementDirection.zCoord * speed; + if (!isPreview()) { + caster.velocityChanged = true; + } + } + + /** + * Stop all horizontal momentum. + */ + protected void stopMomentum(EntityLivingBase caster) { + caster.motionX = 0; + caster.motionZ = 0; + if (!isPreview()) { + caster.velocityChanged = true; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ROTATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Compute yaw angle (degrees) from current movement direction. + */ + protected float computeYawFromDirection() { + if (movementDirection == null) return 0; + return (float) Math.toDegrees(Math.atan2(-movementDirection.xCoord, movementDirection.zCoord)); + } + + /** + * Enforce locked rotation on all yaw fields. + * Sets rotationYaw, rotationYawHead, prevRotationYaw, prevRotationYawHead, + * renderYawOffset, and prevRenderYawOffset to lockedYaw. + */ + protected void enforceLockedRotation(EntityLivingBase caster) { + caster.rotationYaw = lockedYaw; + caster.rotationYawHead = lockedYaw; + caster.prevRotationYaw = lockedYaw; + caster.prevRotationYawHead = lockedYaw; + caster.renderYawOffset = lockedYaw; + caster.prevRenderYawOffset = lockedYaw; + } +} From 121563ba246c784c63702bc96bcd4fbef9467ba1 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 23:07:57 -0500 Subject: [PATCH 69/76] Enhance knockback mechanics: add methods for applying and forcefully applying knockback, respecting or ignoring knockback resistance --- src/api | 2 +- .../scripted/entity/ScriptLivingBase.java | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/api b/src/api index 2b95d3ca4..66fff09d2 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 2b95d3ca47558e804a09e4f7b7f45aeb69fa7861 +Subproject commit 66fff09d2078a9d85a6ef27ef98c02a5944eb325 diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java b/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java index 15459194e..50f1914a7 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java @@ -6,6 +6,7 @@ import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.EntityDamageSource; +import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import noppes.npcs.api.IBlock; import noppes.npcs.api.IDamageSource; @@ -380,4 +381,53 @@ public class ScriptLivingBase extends ScriptEntity 0.4D) { + entity.motionY = 0.4D; + } + + entity.velocityChanged = true; + } } From 1ed012331bb4a8c215148f1991cb5cd879eea216 Mon Sep 17 00:00:00 2001 From: Kam Date: Sun, 15 Feb 2026 23:15:50 -0500 Subject: [PATCH 70/76] Enhance ability input handling: block movement during ability locks, ensure proper input suppression, and cancel abilities on logout, dimension change, death, and respawn --- .../noppes/npcs/ScriptPlayerEventHandler.java | 22 +++++ .../npcs/client/ClientEventHandler.java | 13 ++- .../noppes/npcs/client/ClientTickHandler.java | 85 +++++++++++++++++-- .../controllers/data/PlayerAbilityData.java | 1 + .../npcs/controllers/data/PlayerData.java | 2 + 5 files changed, 116 insertions(+), 7 deletions(-) diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 909634a09..8c9bde6ac 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -106,6 +106,7 @@ public class ScriptPlayerEventHandler { Ability current = playerData.abilityData.getCurrentAbility(); if (current == null || !current.hasAbilityMovement()) { player.motionX = 0; + player.motionY = Math.min(player.motionY, 0); // Prevent jumping, allow gravity player.motionZ = 0; player.velocityChanged = true; } @@ -328,6 +329,12 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { + // Cancel any executing ability on dimension change + PlayerData playerData = PlayerData.get(event.player); + if (playerData != null) { + playerData.abilityData.interruptCurrentAbility(); + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(event.player); IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(event.player); EventHooks.onPlayerChangeDim(handler, scriptPlayer, event.fromDim, event.toDim); @@ -478,6 +485,13 @@ public class ScriptPlayerEventHandler { if (event.entityLiving.worldObj instanceof WorldServer) { if (event.entityLiving instanceof EntityPlayerMP) { + // Cancel jump if movement is locked by an ability + PlayerData playerData = PlayerData.get((EntityPlayer) event.entityLiving); + if (playerData != null && playerData.abilityData.isMovementLocked()) { + event.entityLiving.motionY = 0; + event.entityLiving.velocityChanged = true; + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(event.entityLiving); EventHooks.onPlayerJump(handler, scriptPlayer); @@ -532,6 +546,8 @@ public class ScriptPlayerEventHandler { EntityPlayer player = (EntityPlayer) event.entityLiving; PlayerData playerData = PlayerData.get(player); + // Cancel any executing ability on death + playerData.abilityData.interruptCurrentAbility(); if (ConfigScript.ClearActionsOnDeath) playerData.actionManager.clear(); } @@ -631,6 +647,12 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { + // Cancel any executing ability on respawn + PlayerData playerData = PlayerData.get(event.player); + if (playerData != null) { + playerData.abilityData.interruptCurrentAbility(); + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(event.player); IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(event.player); EventHooks.onPlayerRespawn(handler, scriptPlayer); diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index a7a0f2b39..6fc690b5a 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -84,9 +84,20 @@ public class ClientEventHandler { @SubscribeEvent public void onMouse(MouseEvent event) { - if (Minecraft.getMinecraft().currentScreen != null) + Minecraft mc = Minecraft.getMinecraft(); + if (mc.currentScreen != null) return; + // Block mouse movement during ability rotation lock. + // Allow clicks (button >= 0) and scroll (dwheel != 0) to pass through. + if (mc.theWorld != null && mc.thePlayer != null + && ClientAbilityState.shouldLockRotation() + && (event.dx != 0 || event.dy != 0) + && event.button == -1 && event.dwheel == 0) { + event.setCanceled(true); + return; + } + ArrayList removeList = new ArrayList<>(); for (Map.Entry entry : disabledButtonTimes.entrySet()) { if (entry.getValue() > 0) { diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 7d82ca0f1..d12921756 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -13,6 +13,7 @@ import kamkeel.npcs.network.packets.player.InputDevicePacket; import kamkeel.npcs.network.packets.player.ScreenSizePacket; import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket; import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ContainerPlayer; @@ -75,13 +76,27 @@ public class ClientTickHandler { lastSpecialKeyDown = specialKeyDown; } - // Suppress player input during ability-controlled phases - if (ClientAbilityState.shouldSuppressMovementInput()) { + // Suppress player input during ability-controlled phases. + // Only suppress when no GUI screen is open (screens already capture input). + if (mc.currentScreen == null && ClientAbilityState.shouldSuppressMovementInput()) { + // Unpress movement keybinds at the source BEFORE updatePlayerMoveState() reads them. + // This is more robust than just zeroing movementInput fields, because + // updatePlayerMoveState() reads directly from keybind pressed state. + KeyBinding.setKeyBindState(mc.gameSettings.keyBindForward.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindBack.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindLeft.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindRight.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindJump.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindSprint.getKeyCode(), false); + + // Also zero the movementInput values directly as a safety net mc.thePlayer.movementInput.moveForward = 0; mc.thePlayer.movementInput.moveStrafe = 0; mc.thePlayer.movementInput.jump = false; + mc.thePlayer.movementInput.sneak = false; } - if (ClientAbilityState.shouldLockRotation()) { + if (mc.currentScreen == null && ClientAbilityState.shouldLockRotation()) { mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw; mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch; mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw; @@ -100,8 +115,42 @@ public class ClientTickHandler { } } if (event.phase == Phase.END) { - if (mc.thePlayer != null && mc.theWorld != null && !mc.isGamePaused() && ClientEventHandler.hasOverlays(mc.thePlayer)) { - renderCNPCPlayer.itemRenderer.updateEquippedItem(); + if (mc.thePlayer != null) { + // Re-enforce ability locks AFTER entity update. + // EntityPlayerSP.onLivingUpdate() calls updatePlayerMoveState() which + // overwrites Phase.START suppression with actual keyboard state, causing + // client-predicted movement that fights the server lock. Undo it here. + // Skip when a GUI screen is open (screens already capture all input). + if (mc.currentScreen == null && ClientAbilityState.shouldSuppressMovementInput()) { + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + mc.thePlayer.movementInput.sneak = false; + + // Zero horizontal motion (unless ability provides its own movement) + if (!ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionX = 0; + mc.thePlayer.motionZ = 0; + } + + // Prevent jumping: clamp upward motion when locked (allow gravity) + if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) + && !ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + } + } + + if (mc.currentScreen == null && ClientAbilityState.shouldLockRotation()) { + mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.rotationYawHead = ClientAbilityState.lockedYaw; + } + + if (mc.theWorld != null && !mc.isGamePaused() && ClientEventHandler.hasOverlays(mc.thePlayer)) { + renderCNPCPlayer.itemRenderer.updateEquippedItem(); + } } return; } @@ -159,8 +208,9 @@ public class ClientTickHandler { @SubscribeEvent public void onKey(InputEvent.KeyInputEvent event) { + Minecraft mc = Minecraft.getMinecraft(); + if (ClientProxy.NPCButton.isPressed()) { - Minecraft mc = Minecraft.getMinecraft(); if (mc.currentScreen == null) { InventoryTabCustomNpc.tabHelper(); } else if (mc.currentScreen instanceof GuiCNPCInventory) @@ -171,10 +221,33 @@ public class ClientTickHandler { int key = Keyboard.getEventKey(); boolean keyDown = Keyboard.isKeyDown(key); + // Block movement keys during ability lock (only when no GUI is open and world exists). + // Non-movement keys (ESC, chat, inventory, etc.) always pass through. + if (mc.theWorld != null && mc.currentScreen == null && keyDown + && ClientAbilityState.shouldSuppressMovementInput() && isMovementKey(key)) { + // Unpress the keybind so vanilla doesn't process it + KeyBinding.setKeyBindState(key, false); + return; + } + InputDevicePacket.sendKeyboard(key, keyDown); } } + /** + * Check if a key code corresponds to a movement keybind (WASD, jump, sneak, sprint). + */ + private boolean isMovementKey(int keyCode) { + Minecraft mc = Minecraft.getMinecraft(); + return keyCode == mc.gameSettings.keyBindForward.getKeyCode() + || keyCode == mc.gameSettings.keyBindBack.getKeyCode() + || keyCode == mc.gameSettings.keyBindLeft.getKeyCode() + || keyCode == mc.gameSettings.keyBindRight.getKeyCode() + || keyCode == mc.gameSettings.keyBindJump.getKeyCode() + || keyCode == mc.gameSettings.keyBindSneak.getKeyCode() + || keyCode == mc.gameSettings.keyBindSprint.getKeyCode(); + } + private boolean isIgnoredKey(int key) { int[] var2 = this.ignoreKeys; int var3 = var2.length; diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 22ec80c4b..6ced6f68a 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -699,6 +699,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { player.prevPosY = lockedPosY; player.prevPosZ = lockedPosZ; player.motionX = 0; + player.motionY = 0; // Full vertical freeze for position lock player.motionZ = 0; } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index 02fd67563..7f326a344 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -124,6 +124,8 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { } public void onLogout() { + // Cancel any executing ability and release all locks + abilityData.interruptCurrentAbility(); this.partyInvites.clear(); this.actionManager.clear(); } From 071d89cc15ac5a3020d02779ed579b015a13dd2e Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 16 Feb 2026 01:03:05 -0500 Subject: [PATCH 71/76] Add energy projectile types and events: implement IEnergyOrb, IEnergyBeam, IEnergyDisc, and IEnergyLaser interfaces, along with their respective script handlers and event hooks --- .../npcs/entity/EntityAbilityBeam.java | 16 ++ .../npcs/entity/EntityAbilityDisc.java | 28 ++ .../npcs/entity/EntityAbilityLaser.java | 33 +++ .../kamkeel/npcs/entity/EntityAbilityOrb.java | 4 + .../npcs/entity/EntityAbilityProjectile.java | 216 ++++++++------- src/main/java/noppes/npcs/EventHooks.java | 134 ++++++++++ .../noppes/npcs/constants/EnumScriptType.java | 8 +- .../noppes/npcs/constants/ScriptContext.java | 12 +- .../controllers/ScriptHookController.java | 30 +++ .../controllers/data/PlayerAbilityData.java | 102 ++++++- .../java/noppes/npcs/scripted/NpcAPI.java | 16 ++ .../noppes/npcs/scripted/ScriptWorld.java | 50 ++++ .../npcs/scripted/constants/EntityType.java | 4 + .../scripted/entity/ScriptEnergyBeam.java | 69 +++++ .../scripted/entity/ScriptEnergyDisc.java | 75 ++++++ .../scripted/entity/ScriptEnergyLaser.java | 82 ++++++ .../npcs/scripted/entity/ScriptEnergyOrb.java | 53 ++++ .../entity/ScriptEnergyProjectile.java | 252 ++++++++++++++++++ .../npcs/scripted/entity/ScriptEntity.java | 15 ++ .../npcs/scripted/entity/ScriptNpc.java | 11 + .../npcs/scripted/entity/ScriptPlayer.java | 11 + .../scripted/event/EnergyProjectileEvent.java | 132 +++++++++ .../event/player/PlayerAbilityEvent.java | 104 ++++++++ 23 files changed, 1363 insertions(+), 94 deletions(-) create mode 100644 src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java create mode 100644 src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java create mode 100644 src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java create mode 100644 src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java create mode 100644 src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java create mode 100644 src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index bfdca5346..db57660e4 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -544,6 +545,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } hasHit = true; if (isExplosive()) { posX = blockHit.hitVec.xCoord; @@ -593,10 +597,22 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { return beamWidth; } + public void setBeamWidth(float beamWidth) { + this.beamWidth = beamWidth; + } + public float getHeadSize() { return headSize; } + public void setHeadSize(float headSize) { + this.headSize = headSize; + } + + public void setAttachedToOwner(boolean attached) { + this.attachedToOwner = attached; + } + /** * Get interpolated head offset for smooth rendering. * Returns offset RELATIVE to origin. diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index c0f3cbe8d..dd499f122 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; @@ -344,6 +345,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } hasHit = true; if (isExplosive()) { posX = blockHit.hitVec.xCoord; @@ -413,14 +417,34 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { return discRadius; } + public void setDiscRadius(float radius) { + this.discRadius = radius; + } + public float getDiscThickness() { return discThickness; } + public void setDiscThickness(float thickness) { + this.discThickness = thickness; + } + public boolean isBoomerang() { return boomerang; } + public void setBoomerang(boolean boomerang) { + this.boomerang = boomerang; + } + + public int getBoomerangDelay() { + return boomerangDelay; + } + + public void setBoomerangDelay(int delay) { + this.boomerangDelay = delay; + } + public boolean isReturning() { return returning; } @@ -429,6 +453,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { return vertical; } + public void setVertical(boolean vertical) { + this.vertical = vertical; + } + /** * Get the yaw angle (degrees) from motion vector for vertical disc orientation. * During charging, uses owner's facing direction. diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index d17024680..5adabc4b6 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; @@ -145,6 +146,9 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { endZ = startZ + dirZ * currentLength; if (ticksSinceFullExtension >= lingerTicks) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileExpired(this); + } this.setDead(); } } @@ -236,6 +240,9 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(start, end, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } // Laser stops at block currentLength = (float) Math.sqrt( (blockHit.hitVec.xCoord - startX) * (blockHit.hitVec.xCoord - startX) + @@ -355,6 +362,32 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { return laserWidth; } + public void setLaserWidth(float width) { + this.laserWidth = width; + } + + public float getExpansionSpeed() { + return expansionSpeed; + } + + public void setExpansionSpeed(float speed) { + this.expansionSpeed = speed; + } + + public int getLingerTicks() { + return lingerTicks; + } + + public void setLingerTicks(int ticks) { + this.lingerTicks = ticks; + } + + public void setDirection(double x, double y, double z) { + this.dirX = x; + this.dirY = y; + this.dirZ = z; + } + public float getCurrentLength() { return currentLength; } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java index c85b7be40..2eb5c0084 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; @@ -232,6 +233,9 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } hasHit = true; if (isExplosive()) { posX = blockHit.hitVec.xCoord; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index ac6add74d..99c66edaa 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -20,13 +20,17 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.Vec3; import net.minecraft.world.World; +import noppes.npcs.EventHooks; import noppes.npcs.NpcDamageSource; -import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntity; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.scripted.NpcAPI; +import java.lang.ref.WeakReference; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; @@ -36,7 +40,38 @@ import java.util.Map; * * Design inspired by LouisXIV's energy attack system. */ -public abstract class EntityAbilityProjectile extends Entity implements IEnergyProjectile, IEntityAdditionalSpawnData { +public abstract class EntityAbilityProjectile extends Entity implements IEntityAdditionalSpawnData { + + // ==================== ACTIVE PROJECTILE TRACKING ==================== + private static final Map>> activeProjectiles = new HashMap<>(); + + public static void trackProjectile(EntityAbilityProjectile projectile) { + int ownerId = projectile.getOwnerEntityId(); + if (ownerId < 0) return; + List> refs = activeProjectiles.get(ownerId); + if (refs == null) { + refs = new ArrayList<>(); + activeProjectiles.put(ownerId, refs); + } + refs.add(new WeakReference<>(projectile)); + } + + public static List getActiveProjectiles(int ownerEntityId) { + List> refs = activeProjectiles.get(ownerEntityId); + if (refs == null) return Collections.emptyList(); + List result = new ArrayList<>(); + Iterator> it = refs.iterator(); + while (it.hasNext()) { + EntityAbilityProjectile p = it.next().get(); + if (p == null || p.isDead) { + it.remove(); + } else { + result.add(p); + } + } + if (refs.isEmpty()) activeProjectiles.remove(ownerEntityId); + return result; + } // ==================== VISUAL PROPERTIES ==================== protected float size = 1.0f; @@ -174,6 +209,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Skip super.onUpdate() in preview mode to avoid world checks if (!previewMode) { super.onUpdate(); + + // Track on first server tick + if (ticksExisted == 1 && !worldObj.isRemote) { + trackProjectile(this); + } } // Update rotation @@ -208,12 +248,18 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Check lifespan using world time (survives chunk unload/reload) if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileExpired(this); + } this.setDead(); return; } // Check max distance (subclass can override if needed) if (checkMaxDistance()) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileExpired(this); + } this.setDead(); return; } @@ -226,6 +272,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Subclass-specific update updateProjectile(); + + // Fire tick event (server-side, non-preview only) + if (!previewMode && !worldObj.isRemote) { + EventHooks.onEnergyProjectileTick(this); + } } /** @@ -328,6 +379,14 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP protected void applyDamage(EntityLivingBase target, float dmg, float kb) { if (previewMode) return; // Skip damage in preview mode + + // Fire entity impact event (may cancel or modify damage) + if (!worldObj.isRemote) { + float result = EventHooks.onEnergyProjectileEntityImpact(this, target, dmg); + if (result < 0) return; // Event was cancelled + dmg = result; + } + Entity owner = getOwnerEntity(); // Check for ability extenders (e.g., DBC Addon damage routing) @@ -627,12 +686,14 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP return worldObj.getEntityByID(ownerEntityId); } - @Override public int getOwnerEntityId() { return ownerEntityId; } - @Override + public void setOwnerEntityId(int id) { + this.ownerEntityId = id; + } + public IEntity getOwner() { if (previewMode) return null; if (getOwnerEntity() == null) return null; @@ -647,17 +708,19 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.previewOwner = owner; } - @Override public int getTargetEntityId() { return targetEntityId; } + public void setTargetEntityId(int id) { + this.targetEntityId = id; + } + public Entity getTargetEntity() { if (targetEntityId == -1) return null; return worldObj.getEntityByID(targetEntityId); } - @Override public IEntity getTarget() { if (getTargetEntity() == null) return null; return NpcAPI.Instance().getIEntity(getTargetEntity()); @@ -686,162 +749,135 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP return false; } - // ==================== VISUAL GETTERS ==================== + // ==================== VISUAL GETTERS & SETTERS ==================== - @Override - public float getSize() { - return size; + public float getSize() { return size; } + public void setProjectileSize(float size) { + this.size = size; + this.renderCurrentSize = size; + this.prevRenderSize = size; } - @Override - public int getInnerColor() { - return displayData.getInnerColor(); + /** + * Set the start position for distance calculations. + * Used by factory methods when creating projectiles without the full constructor. + */ + public void setStartPosition(double x, double y, double z) { + this.startX = x; + this.startY = y; + this.startZ = z; } - @Override - public int getOuterColor() { - return displayData.getOuterColor(); - } + public int getInnerColor() { return displayData.getInnerColor(); } + public void setInnerColor(int color) { displayData.setInnerColor(color); } - @Override - public boolean isOuterColorEnabled() { - return displayData.isOuterColorEnabled(); - } + public int getOuterColor() { return displayData.getOuterColor(); } + public void setOuterColor(int color) { displayData.setOuterColor(color); } - @Override - public float getOuterColorWidth() { - return displayData.getOuterColorWidth(); - } + public boolean isOuterColorEnabled() { return displayData.isOuterColorEnabled(); } + public void setOuterColorEnabled(boolean enabled) { displayData.setOuterColorEnabled(enabled); } - @Override - public float getOuterColorAlpha() { - return displayData.getOuterColorAlpha(); - } + public float getOuterColorWidth() { return displayData.getOuterColorWidth(); } + public void setOuterColorWidth(float width) { displayData.setOuterColorWidth(width); } - @Override - public float getRotationSpeed() { - return displayData.getRotationSpeed(); - } + public float getOuterColorAlpha() { return displayData.getOuterColorAlpha(); } + public void setOuterColorAlpha(float alpha) { displayData.setOuterColorAlpha(alpha); } + + public float getRotationSpeed() { return displayData.getRotationSpeed(); } + public void setRotationSpeed(float speed) { displayData.setRotationSpeed(speed); } // ==================== ROTATION GETTERS ==================== - @Override public float getInterpolatedRotationX(float partialTicks) { return this.prevRotationValX + (this.rotationValX - this.prevRotationValX) * partialTicks; } - @Override public float getInterpolatedRotationY(float partialTicks) { return this.prevRotationValY + (this.rotationValY - this.prevRotationValY) * partialTicks; } - @Override public float getInterpolatedRotationZ(float partialTicks) { return this.prevRotationValZ + (this.rotationValZ - this.prevRotationValZ) * partialTicks; } - @Override public float getInterpolatedSize(float partialTicks) { return this.prevRenderSize + (this.renderCurrentSize - this.prevRenderSize) * partialTicks; } - // ==================== LIGHTNING GETTERS ==================== + // ==================== LIGHTNING GETTERS & SETTERS ==================== - @Override - public boolean hasLightningEffect() { - return lightningData.isLightningEffect(); - } + public boolean hasLightningEffect() { return lightningData.isLightningEffect(); } + public void setLightningEffect(boolean enabled) { lightningData.setLightningEffect(enabled); } - @Override - public float getLightningDensity() { - return lightningData.getLightningDensity(); - } + public float getLightningDensity() { return lightningData.getLightningDensity(); } + public void setLightningDensity(float density) { lightningData.setLightningDensity(density); } - @Override - public float getLightningRadius() { - return lightningData.getLightningRadius(); - } + public float getLightningRadius() { return lightningData.getLightningRadius(); } + public void setLightningRadius(float radius) { lightningData.setLightningRadius(radius); } - @Override - public int getLightningFadeTime() { - return lightningData.getLightningFadeTime(); - } + public int getLightningFadeTime() { return lightningData.getLightningFadeTime(); } + public void setLightningFadeTime(int ticks) { lightningData.setLightningFadeTime(ticks); } - // ==================== LIFESPAN GETTERS ==================== + // ==================== LIFESPAN GETTERS & SETTERS ==================== - @Override public float getMaxDistance() { return lifespanData.getMaxDistance(); } + public void setMaxDistance(float distance) { lifespanData.setMaxDistance(distance); } - @Override public int getMaxLifetime() { return lifespanData.getMaxLifetime(); } + public void setMaxLifetime(int ticks) { lifespanData.setMaxLifetime(ticks); } - // ==================== COMBAT GETTERS ==================== + // ==================== COMBAT GETTERS & SETTERS ==================== - @Override public float getDamage() { return combatData.getDamage(); } + public void setCombatDamage(float damage) { combatData.setDamage(damage); } - @Override public float getKnockback() { return combatData.knockback; } + public void setCombatKnockback(float knockback) { combatData.setKnockback(knockback); } - @Override public float getKnockbackUp() { return combatData.knockbackUp; } + public void setCombatKnockbackUp(float knockbackUp) { combatData.setKnockbackUp(knockbackUp); } - @Override public boolean isExplosive() { return combatData.isExplosive(); } + public void setExplosive(boolean explosive) { combatData.setExplosive(explosive); } - @Override public float getExplosionRadius() { return combatData.explosionRadius; } + public void setExplosionRadius(float radius) { combatData.setExplosionRadius(radius); } - @Override public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + public void setExplosionDamageFalloff(float falloff) { combatData.setExplosionDamageFalloff(falloff); } - // ==================== HOMING GETTERS ==================== + // ==================== HOMING GETTERS & SETTERS ==================== - @Override public boolean isHoming() { return homingData.isHoming(); } + public void setHomingEnabled(boolean homing) { homingData.setHoming(homing); } - @Override public float getHomingStrength() { return homingData.getHomingStrength(); } + public void setHomingStrength(float strength) { homingData.setHomingStrength(strength); } - @Override public float getHomingRange() { return homingData.getHomingRange(); } + public void setHomingRange(float range) { homingData.setHomingRange(range); } - // ==================== TRAJECTORY GETTERS ==================== + // ==================== SPEED & ANCHOR GETTERS & SETTERS ==================== - - - // ==================== ANCHOR GETTERS ==================== - - @Override public float getSpeed() { return homingData.getSpeed(); } + public void setSpeed(float speed) { homingData.setSpeed(speed); } public AnchorPoint getAnchorPoint() { return anchorData.getAnchorPoint(); } - @Override public int getAnchor() { return anchorData.getAnchor(); } - - @Override public float getAnchorOffsetX() { return anchorData.getAnchorOffsetX(); } - - @Override public float getAnchorOffsetY() { return anchorData.getAnchorOffsetY(); } - - @Override public float getAnchorOffsetZ() { return anchorData.getAnchorOffsetZ(); } // ==================== MOVEMENT GETTERS ==================== - @Override public double getStartX() { return startX; } + public double getStartX() { return startX; } + public double getStartY() { return startY; } + public double getStartZ() { return startZ; } - @Override public double getStartY() { return startY; } + // ==================== STATE GETTERS ==================== - @Override public double getStartZ() { return startZ; } - - @Override public double getMotionX() { return motionX; } - - @Override public double getMotionY() { return motionY; } - - @Override public double getMotionZ() { return motionZ; } + public boolean getHasHit() { return hasHit; } // ==================== BRIGHTNESS ==================== diff --git a/src/main/java/noppes/npcs/EventHooks.java b/src/main/java/noppes/npcs/EventHooks.java index 5f9d1388f..75b615671 100644 --- a/src/main/java/noppes/npcs/EventHooks.java +++ b/src/main/java/noppes/npcs/EventHooks.java @@ -1,6 +1,7 @@ package noppes.npcs; import cpw.mods.fml.common.eventhandler.Event; +import kamkeel.npcs.entity.EntityAbilityProjectile; import kamkeel.npcs.network.packets.data.AchievementPacket; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; @@ -16,7 +17,10 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.world.WorldEvent; +import noppes.npcs.api.IBlock; +import noppes.npcs.api.IPos; import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IAnimatable; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.entity.IEntity; @@ -52,6 +56,7 @@ import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AnimationEvent; import noppes.npcs.scripted.event.BlockEvent; import noppes.npcs.scripted.event.CustomNPCsEvent; +import noppes.npcs.scripted.event.EnergyProjectileEvent; import noppes.npcs.scripted.event.ForgeEvent; import noppes.npcs.scripted.event.ItemEvent; import noppes.npcs.scripted.event.LinkedItemEvent; @@ -448,6 +453,110 @@ public class EventHooks { NpcAPI.EVENT_BUS.post(event); } + // ==================== ENERGY PROJECTILE EVENTS ==================== + + public static void onEnergyProjectileFired(EntityAbilityProjectile projectile) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.FiredEvent event = new EnergyProjectileEvent.FiredEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_FIRED, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_FIRED, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_FIRED, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + public static void onEnergyProjectileTick(EntityAbilityProjectile projectile) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.UpdateEvent event = new EnergyProjectileEvent.UpdateEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + /** + * Fires the entity impact event. Returns the (possibly modified) damage, or -1 if cancelled. + */ + public static float onEnergyProjectileEntityImpact(EntityAbilityProjectile projectile, EntityLivingBase target, float damage) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + IEntity wrappedTarget = NpcAPI.Instance().getIEntity(target); + EnergyProjectileEvent.EntityImpactEvent event = new EnergyProjectileEvent.EntityImpactEvent(wrapped, wrappedTarget, damage); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + + if (event.isCanceled()) { + return -1; + } + return event.getDamage(); + } + + public static void onEnergyProjectileBlockImpact(EntityAbilityProjectile projectile, int blockX, int blockY, int blockZ) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + IPos pos = NpcAPI.Instance().getIPos(blockX, blockY, blockZ); + IWorld world = NpcAPI.Instance().getIWorld(projectile.worldObj); + IBlock block = NpcAPI.Instance().getIBlock(world, pos); + EnergyProjectileEvent.BlockImpactEvent event = new EnergyProjectileEvent.BlockImpactEvent(wrapped, block); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + public static void onEnergyProjectileExpired(EntityAbilityProjectile projectile) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.ExpiredEvent event = new EnergyProjectileEvent.ExpiredEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_EXPIRED, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_EXPIRED, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_EXPIRED, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + public static void onPlayerInit(PlayerDataScript handler, IPlayer player) { PlayerEvent.InitEvent event = new PlayerEvent.InitEvent(player); handler.callScript(EnumScriptType.INIT, event); @@ -693,6 +802,31 @@ public class EventHooks { return NpcAPI.EVENT_BUS.post(event); } + public static boolean onPlayerAbilityStart(PlayerDataScript handler, PlayerAbilityEvent.StartEvent event) { + handler.callScript(EnumScriptType.ABILITY_START, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onPlayerAbilityExecute(PlayerDataScript handler, PlayerAbilityEvent.ExecuteEvent event) { + handler.callScript(EnumScriptType.ABILITY_EXECUTE, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static void onPlayerAbilityTick(PlayerDataScript handler, PlayerAbilityEvent.TickEvent event) { + handler.callScript(EnumScriptType.ABILITY_TICK, event); + NpcAPI.EVENT_BUS.post(event); + } + + public static void onPlayerAbilityInterrupt(PlayerDataScript handler, PlayerAbilityEvent.InterruptEvent event) { + handler.callScript(EnumScriptType.ABILITY_INTERRUPT, event); + NpcAPI.EVENT_BUS.post(event); + } + + public static void onPlayerAbilityComplete(PlayerDataScript handler, PlayerAbilityEvent.CompleteEvent event) { + handler.callScript(EnumScriptType.ABILITY_COMPLETE, event); + NpcAPI.EVENT_BUS.post(event); + } + public static boolean onPlayerAbilityHit(PlayerDataScript handler, PlayerAbilityEvent.HitEvent event) { handler.callScript(EnumScriptType.ABILITY_HIT, event); return NpcAPI.EVENT_BUS.post(event); diff --git a/src/main/java/noppes/npcs/constants/EnumScriptType.java b/src/main/java/noppes/npcs/constants/EnumScriptType.java index 99a8b4091..da4e8f136 100644 --- a/src/main/java/noppes/npcs/constants/EnumScriptType.java +++ b/src/main/java/noppes/npcs/constants/EnumScriptType.java @@ -125,7 +125,13 @@ public enum EnumScriptType { ABILITY_INTERRUPT("abilityInterrupt"), ABILITY_COMPLETE("abilityComplete"), ABILITY_HIT("abilityHit"), - ABILITY_TICK("abilityTick"); + ABILITY_TICK("abilityTick"), + + ENERGY_PROJECTILE_FIRED("energyProjectileFired"), + ENERGY_PROJECTILE_TICK("energyProjectileTick"), + ENERGY_PROJECTILE_ENTITY_IMPACT("energyProjectileEntityImpact"), + ENERGY_PROJECTILE_BLOCK_IMPACT("energyProjectileBlockImpact"), + ENERGY_PROJECTILE_EXPIRED("energyProjectileExpired"); public String function; diff --git a/src/main/java/noppes/npcs/constants/ScriptContext.java b/src/main/java/noppes/npcs/constants/ScriptContext.java index dcc5b5d95..c5861927a 100644 --- a/src/main/java/noppes/npcs/constants/ScriptContext.java +++ b/src/main/java/noppes/npcs/constants/ScriptContext.java @@ -1,14 +1,17 @@ package noppes.npcs.constants; +import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.api.event.IAnimationEvent; import noppes.npcs.api.event.IBlockEvent; import noppes.npcs.api.event.ICustomGuiEvent; import noppes.npcs.api.event.IDialogEvent; +import noppes.npcs.api.event.IEnergyProjectileEvent; import noppes.npcs.api.event.IFactionEvent; import noppes.npcs.api.event.IForgeEvent; import noppes.npcs.api.event.IItemEvent; import noppes.npcs.api.event.INpcEvent; import noppes.npcs.api.event.IPartyEvent; +import noppes.npcs.api.event.IPlayerAbilityEvent; import noppes.npcs.api.event.IPlayerEvent; import noppes.npcs.api.event.IProjectileEvent; import noppes.npcs.api.event.IQuestEvent; @@ -52,7 +55,10 @@ public class ScriptContext { public static final ScriptContext NPC = register("NPC", "npc", INpcEvent.class, - IProjectileEvent.class + IProjectileEvent.class, + IEnergyProjectileEvent.class, + IAbilityEvent.class, + IAnimationEvent.class ); public static final ScriptContext PLAYER = register("PLAYER", "player", @@ -62,7 +68,9 @@ public class ScriptContext { IDialogEvent.class, IQuestEvent.class, IFactionEvent.class, - ICustomGuiEvent.class + ICustomGuiEvent.class, + IEnergyProjectileEvent.class, + IPlayerAbilityEvent.class ); public static final ScriptContext BLOCK = register("BLOCK", "block", diff --git a/src/main/java/noppes/npcs/controllers/ScriptHookController.java b/src/main/java/noppes/npcs/controllers/ScriptHookController.java index f3bad8e9d..88a12e20d 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptHookController.java +++ b/src/main/java/noppes/npcs/controllers/ScriptHookController.java @@ -2,10 +2,12 @@ package noppes.npcs.controllers; import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.api.event.IAnimationEvent; +import noppes.npcs.api.event.IPlayerAbilityEvent; import noppes.npcs.api.event.IBlockEvent; import noppes.npcs.api.event.ICustomGuiEvent; import noppes.npcs.api.event.ICustomNPCsEvent; import noppes.npcs.api.event.IDialogEvent; +import noppes.npcs.api.event.IEnergyProjectileEvent; import noppes.npcs.api.event.IFactionEvent; import noppes.npcs.api.event.IForgeEvent; import noppes.npcs.api.event.IItemEvent; @@ -106,6 +108,13 @@ public class ScriptHookController implements IScriptHookHandler { hook(NPC, PROJECTILE_TICK, IProjectileEvent.UpdateEvent.class); hook(NPC, PROJECTILE_IMPACT, IProjectileEvent.ImpactEvent.class); + // Energy Projectile + hook(NPC, ENERGY_PROJECTILE_FIRED, IEnergyProjectileEvent.FiredEvent.class); + hook(NPC, ENERGY_PROJECTILE_TICK, IEnergyProjectileEvent.UpdateEvent.class); + hook(NPC, ENERGY_PROJECTILE_ENTITY_IMPACT, IEnergyProjectileEvent.EntityImpactEvent.class); + hook(NPC, ENERGY_PROJECTILE_BLOCK_IMPACT, IEnergyProjectileEvent.BlockImpactEvent.class); + hook(NPC, ENERGY_PROJECTILE_EXPIRED, IEnergyProjectileEvent.ExpiredEvent.class); + // Ability hook(NPC, ABILITY_START, IAbilityEvent.StartEvent.class); hook(NPC, ABILITY_EXECUTE, IAbilityEvent.ExecuteEvent.class); @@ -113,6 +122,12 @@ public class ScriptHookController implements IScriptHookHandler { hook(NPC, ABILITY_TICK, IAbilityEvent.TickEvent.class); hook(NPC, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); hook(NPC, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + + // Animation + hook(NPC, ANIMATION_START, IAnimationEvent.Started.class); + hook(NPC, ANIMATION_END, IAnimationEvent.Ended.class); + hook(NPC, ANIMATION_FRAME_ENTER, IAnimationEvent.IFrameEvent.Entered.class); + hook(NPC, ANIMATION_FRAME_EXIT, IAnimationEvent.IFrameEvent.Exited.class); } private void initializePlayerHooks() { @@ -208,6 +223,21 @@ public class ScriptHookController implements IScriptHookHandler { hook(PLAYER, ANIMATION_FRAME_ENTER, IAnimationEvent.IFrameEvent.Entered.class); hook(PLAYER, ANIMATION_FRAME_EXIT, IAnimationEvent.IFrameEvent.Exited.class); + // Energy Projectile + hook(PLAYER, ENERGY_PROJECTILE_FIRED, IEnergyProjectileEvent.FiredEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_TICK, IEnergyProjectileEvent.UpdateEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_ENTITY_IMPACT, IEnergyProjectileEvent.EntityImpactEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_BLOCK_IMPACT, IEnergyProjectileEvent.BlockImpactEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_EXPIRED, IEnergyProjectileEvent.ExpiredEvent.class); + + // Ability + hook(PLAYER, ABILITY_START, IPlayerAbilityEvent.StartEvent.class); + hook(PLAYER, ABILITY_EXECUTE, IPlayerAbilityEvent.ExecuteEvent.class); + hook(PLAYER, ABILITY_HIT, IPlayerAbilityEvent.HitEvent.class); + hook(PLAYER, ABILITY_TICK, IPlayerAbilityEvent.TickEvent.class); + hook(PLAYER, ABILITY_INTERRUPT, IPlayerAbilityEvent.InterruptEvent.class); + hook(PLAYER, ABILITY_COMPLETE, IPlayerAbilityEvent.CompleteEvent.class); + // Profile hook(PLAYER, PROFILE_CHANGE, IPlayerEvent.ProfileEvent.Changed.class); hook(PLAYER, PROFILE_REMOVE, IPlayerEvent.ProfileEvent.Removed.class); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 6ced6f68a..088017e62 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -15,9 +15,14 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.DamageSource; +import noppes.npcs.EventHooks; import noppes.npcs.api.ability.IPlayerAbilityData; +import noppes.npcs.api.entity.IPlayer; import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.Animation; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; @@ -154,6 +159,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { // Tick advances time and possibly changes phase boolean phaseChanged = currentAbility.tick(); + // Fire tick event for scripts + firePlayerTickEvent(player, currentAbility, currentTarget); + // Fire extender tick hook (e.g., per-tick resource drain) if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, player, currentTarget, currentAbility.getPhase(), currentAbility.getCurrentTick())) { @@ -211,6 +219,11 @@ public class PlayerAbilityData implements IPlayerAbilityData { playAbilitySound(player, currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); + // Fire execute event (cancelable) + if (firePlayerExecuteEvent(player, currentAbility, currentTarget)) { + return; // Cancelled + } + // Call onExecute currentAbility.onExecute(player, currentTarget); @@ -268,6 +281,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentAbility.onComplete(player, currentTarget); + // Fire complete event + firePlayerCompleteEvent(player, currentAbility, currentTarget); + // Release all locks releaseRotationControl(); releaseLockedPosition(); @@ -340,6 +356,11 @@ public class PlayerAbilityData implements IPlayerAbilityData { return false; } + // Fire start event (cancelable) + if (firePlayerStartEvent(player, ability)) { + return false; // Cancelled + } + // Start the ability currentAbility = ability; currentAbilityKey = key; @@ -380,6 +401,11 @@ public class PlayerAbilityData implements IPlayerAbilityData { playAbilitySound(player, ability.getActiveSound()); playAbilityAnimation(ability.getActiveAnimation()); + // Fire execute event (cancelable) + if (firePlayerExecuteEvent(player, ability, currentTarget)) { + return; // Cancelled + } + // Call onExecute ability.onExecute(player, currentTarget); @@ -538,10 +564,17 @@ public class PlayerAbilityData implements IPlayerAbilityData { } public void interruptCurrentAbility() { + interruptCurrentAbility(null, 0); + } + + public void interruptCurrentAbility(DamageSource source, float damage) { if (currentAbility != null && currentAbility.isExecuting()) { // Fire extender complete hook (interrupted) AbilityController.Instance.fireOnAbilityComplete(currentAbility, playerData.player, currentTarget, true); + // Fire interrupt event + firePlayerInterruptEvent(playerData.player, currentAbility, currentTarget, source, damage); + currentAbility.interrupt(); stopAbilityAnimation(); releaseRotationControl(); @@ -594,7 +627,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { // Check for ability interruption if (currentAbility != null && currentAbility.canInterrupt(source)) { - interruptCurrentAbility(); + interruptCurrentAbility(source, amount); } return amount; @@ -834,6 +867,73 @@ public class PlayerAbilityData implements IPlayerAbilityData { } } + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT EVENTS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Fire the ability start event. Returns true if cancelled. + */ + private boolean firePlayerStartEvent(EntityPlayer player, Ability ability) { + if (ScriptController.Instance == null) return false; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return false; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.StartEvent event = new PlayerAbilityEvent.StartEvent(iPlayer, ability, null); + return EventHooks.onPlayerAbilityStart(handler, event); + } + + /** + * Fire the ability execute event. Returns true if cancelled. + */ + private boolean firePlayerExecuteEvent(EntityPlayer player, Ability ability, EntityLivingBase target) { + if (ScriptController.Instance == null) return false; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return false; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.ExecuteEvent event = new PlayerAbilityEvent.ExecuteEvent(iPlayer, ability, target); + return EventHooks.onPlayerAbilityExecute(handler, event); + } + + /** + * Fire the ability tick event. + */ + private void firePlayerTickEvent(EntityPlayer player, Ability ability, EntityLivingBase target) { + if (ScriptController.Instance == null) return; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.TickEvent event = new PlayerAbilityEvent.TickEvent( + iPlayer, ability, target, ability.getPhase().ordinal(), ability.getCurrentTick()); + EventHooks.onPlayerAbilityTick(handler, event); + } + + /** + * Fire the ability interrupt event. + */ + private void firePlayerInterruptEvent(EntityPlayer player, Ability ability, EntityLivingBase target, + DamageSource source, float damage) { + if (ScriptController.Instance == null) return; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.InterruptEvent event = new PlayerAbilityEvent.InterruptEvent( + iPlayer, ability, target, source, damage); + EventHooks.onPlayerAbilityInterrupt(handler, event); + } + + /** + * Fire the ability complete event. + */ + private void firePlayerCompleteEvent(EntityPlayer player, Ability ability, EntityLivingBase target) { + if (ScriptController.Instance == null) return; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.CompleteEvent event = new PlayerAbilityEvent.CompleteEvent(iPlayer, ability, target); + EventHooks.onPlayerAbilityComplete(handler, event); + } + // ═══════════════════════════════════════════════════════════════════ // NBT SERIALIZATION // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index c80c18d28..24f271f33 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -7,6 +7,10 @@ import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; import net.minecraft.block.Block; import net.minecraft.command.CommandHandler; import net.minecraft.entity.Entity; @@ -119,6 +123,10 @@ import noppes.npcs.items.ItemScripted; import noppes.npcs.scripted.entity.ScriptAnimal; 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.ScriptEnergyLaser; +import noppes.npcs.scripted.entity.ScriptEnergyOrb; import noppes.npcs.scripted.entity.ScriptEntity; import noppes.npcs.scripted.entity.ScriptEntityItem; import noppes.npcs.scripted.entity.ScriptFishHook; @@ -454,6 +462,14 @@ public class NpcAPI extends AbstractNpcAPI { data = new ScriptEntityData(new ScriptArrow<>((EntityArrow) entity)); else if (entity instanceof EntityFishHook) data = new ScriptEntityData(new ScriptFishHook<>((EntityFishHook) entity)); + else if (entity instanceof EntityAbilityOrb) + data = new ScriptEntityData(new ScriptEnergyOrb<>((EntityAbilityOrb) entity)); + else if (entity instanceof EntityAbilityBeam) + data = new ScriptEntityData(new ScriptEnergyBeam<>((EntityAbilityBeam) entity)); + else if (entity instanceof EntityAbilityDisc) + data = new ScriptEntityData(new ScriptEnergyDisc<>((EntityAbilityDisc) entity)); + else if (entity instanceof EntityAbilityLaser) + data = new ScriptEntityData(new ScriptEnergyLaser<>((EntityAbilityLaser) entity)); else data = new ScriptEntityData(new ScriptEntity<>(entity)); entity.registerExtendedProperties("ScriptedObject", data); diff --git a/src/main/java/noppes/npcs/scripted/ScriptWorld.java b/src/main/java/noppes/npcs/scripted/ScriptWorld.java index c9b806ca9..b827315d2 100644 --- a/src/main/java/noppes/npcs/scripted/ScriptWorld.java +++ b/src/main/java/noppes/npcs/scripted/ScriptWorld.java @@ -21,6 +21,10 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.BlockSnapshot; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.world.BlockEvent; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; import noppes.npcs.CustomNpcs; import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.IBlock; @@ -28,6 +32,10 @@ import noppes.npcs.api.IParticle; import noppes.npcs.api.IPos; import noppes.npcs.api.ITileEntity; import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEnergyBeam; +import noppes.npcs.api.entity.IEnergyDisc; +import noppes.npcs.api.entity.IEnergyLaser; +import noppes.npcs.api.entity.IEnergyOrb; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.handler.data.ISound; @@ -1242,6 +1250,48 @@ public class ScriptWorld implements IWorld { return "DIM" + this.getDimensionID(); } + @Override + public IEnergyOrb createEnergyOrb(IEntity owner, double x, double y, double z, float size) { + EntityAbilityOrb entity = new EntityAbilityOrb(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setProjectileSize(size); + return (IEnergyOrb) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyBeam createEnergyBeam(IEntity owner, double x, double y, double z, float beamWidth, float headSize) { + EntityAbilityBeam entity = new EntityAbilityBeam(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setBeamWidth(beamWidth); + entity.setHeadSize(headSize); + return (IEnergyBeam) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyDisc createEnergyDisc(IEntity owner, double x, double y, double z, float radius, float thickness) { + EntityAbilityDisc entity = new EntityAbilityDisc(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setDiscRadius(radius); + entity.setDiscThickness(thickness); + return (IEnergyDisc) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyLaser createEnergyLaser(IEntity owner, double x, double y, double z, float laserWidth) { + EntityAbilityLaser entity = new EntityAbilityLaser(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setLaserWidth(laserWidth); + return (IEnergyLaser) NpcAPI.Instance().getIEntity(entity); + } + @Override public void broadcast(String message) { world.func_73046_m().getConfigurationManager().sendChatMsg(new ChatComponentText(message)); diff --git a/src/main/java/noppes/npcs/scripted/constants/EntityType.java b/src/main/java/noppes/npcs/scripted/constants/EntityType.java index 995969682..355173646 100644 --- a/src/main/java/noppes/npcs/scripted/constants/EntityType.java +++ b/src/main/java/noppes/npcs/scripted/constants/EntityType.java @@ -15,4 +15,8 @@ public class EntityType { public static final int THROWABLE = 11; public static final int FISH_HOOK = 12; public static final int ENERGY_PROJECTILE = 13; + public static final int ENERGY_ORB = 14; + public static final int ENERGY_BEAM = 15; + public static final int ENERGY_DISC = 16; + public static final int ENERGY_LASER = 17; } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java new file mode 100644 index 000000000..b42a32b1d --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java @@ -0,0 +1,69 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityBeam; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyBeam; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyBeam extends ScriptEnergyProjectile implements IEnergyBeam { + + public ScriptEnergyBeam(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_BEAM; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_BEAM || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 1; + } + + // ==================== BEAM-SPECIFIC ==================== + + public float getBeamWidth() { return entity.getBeamWidth(); } + public void setBeamWidth(float width) { entity.setBeamWidth(width); } + + public float getHeadSize() { return entity.getHeadSize(); } + public void setHeadSize(float size) { entity.setHeadSize(size); } + + public boolean isAttachedToOwner() { return entity.isAttachedToOwner(); } + public void setAttachedToOwner(boolean attached) { entity.setAttachedToOwner(attached); } + + public boolean shouldRenderTailOrb() { return entity.shouldRenderTailOrb(); } + + // ==================== FIRE ==================== + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startFiring(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + entity.startFiring(null); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java new file mode 100644 index 000000000..62dde7979 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java @@ -0,0 +1,75 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityDisc; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyDisc; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyDisc extends ScriptEnergyProjectile implements IEnergyDisc { + + public ScriptEnergyDisc(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_DISC; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_DISC || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 2; + } + + // ==================== DISC-SPECIFIC ==================== + + public float getDiscRadius() { return entity.getDiscRadius(); } + public void setDiscRadius(float radius) { entity.setDiscRadius(radius); } + + public float getDiscThickness() { return entity.getDiscThickness(); } + public void setDiscThickness(float thickness) { entity.setDiscThickness(thickness); } + + public boolean isVertical() { return entity.isVertical(); } + public void setVertical(boolean vertical) { entity.setVertical(vertical); } + + public boolean isBoomerang() { return entity.isBoomerang(); } + public void setBoomerang(boolean boomerang) { entity.setBoomerang(boomerang); } + + public int getBoomerangDelay() { return entity.getBoomerangDelay(); } + public void setBoomerangDelay(int ticks) { entity.setBoomerangDelay(ticks); } + + public boolean isReturning() { return entity.isReturning(); } + + // ==================== FIRE ==================== + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startMoving(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + entity.startMoving(null); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java new file mode 100644 index 000000000..976fd948d --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java @@ -0,0 +1,82 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityLaser; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyLaser; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyLaser extends ScriptEnergyProjectile implements IEnergyLaser { + + public ScriptEnergyLaser(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_LASER; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_LASER || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 3; + } + + // ==================== LASER-SPECIFIC ==================== + + public float getLaserWidth() { return entity.getLaserWidth(); } + public void setLaserWidth(float width) { entity.setLaserWidth(width); } + + public float getExpansionSpeed() { return entity.getExpansionSpeed(); } + public void setExpansionSpeed(float speed) { entity.setExpansionSpeed(speed); } + + public int getLingerTicks() { return entity.getLingerTicks(); } + public void setLingerTicks(int ticks) { entity.setLingerTicks(ticks); } + + public float getCurrentLength() { return entity.getCurrentLength(); } + public boolean isFullyExtended() { return entity.isFullyExtended(); } + + public double getDirX() { return entity.getDirX(); } + public double getDirY() { return entity.getDirY(); } + public double getDirZ() { return entity.getDirZ(); } + public void setDirection(double x, double y, double z) { entity.setDirection(x, y, z); } + + public double getEndX() { return entity.getEndX(); } + public double getEndY() { return entity.getEndY(); } + public double getEndZ() { return entity.getEndZ(); } + + public float getLingerAlpha() { return entity.getLingerAlpha(); } + + public boolean isLockVerticalDirection() { return entity.isLockVerticalDirection(); } + public void setLockVerticalDirection(boolean lock) { entity.setLockVerticalDirection(lock); } + + // ==================== FIRE ==================== + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startMoving(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.setDirection(dx / len, dy / len, dz / len); + } + entity.startMoving(null); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java new file mode 100644 index 000000000..1b6a95fb7 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java @@ -0,0 +1,53 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityOrb; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyOrb; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyOrb extends ScriptEnergyProjectile implements IEnergyOrb { + + public ScriptEnergyOrb(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_ORB; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_ORB || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 0; + } + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startMoving(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java new file mode 100644 index 000000000..f614b8122 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java @@ -0,0 +1,252 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityProjectile; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.EventHooks; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyProjectile extends ScriptEntity implements IEnergyProjectile { + protected T entity; + + public ScriptEnergyProjectile(T entity) { + super(entity); + this.entity = entity; + } + + // ==================== TYPE ==================== + + @Override + public int getType() { + return EntityType.ENERGY_PROJECTILE; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_PROJECTILE || super.typeOf(type); + } + + public int getEnergyType() { + return -1; + } + + // ==================== OWNER & TARGET ==================== + + public int getOwnerEntityId() { + return entity.getOwnerEntityId(); + } + + public IEntity getOwner() { + return entity.getOwner(); + } + + public void setOwner(IEntity owner) { + if (owner != null) { + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + } + } + + public int getTargetEntityId() { + return entity.getTargetEntityId(); + } + + public IEntity getTarget() { + return entity.getTarget(); + } + + public void setTarget(IEntity target) { + if (target != null) { + entity.setTargetEntityId(target.getMCEntity().getEntityId()); + } else { + entity.setTargetEntityId(-1); + } + } + + // ==================== SIZE ==================== + + public float getSize() { + return entity.getSize(); + } + + public void setSize(float size) { + entity.setProjectileSize(size); + } + + // ==================== DISPLAY ==================== + + public int getInnerColor() { return entity.getInnerColor(); } + public void setInnerColor(int color) { entity.setInnerColor(color); } + + public int getOuterColor() { return entity.getOuterColor(); } + public void setOuterColor(int color) { entity.setOuterColor(color); } + + public boolean isOuterColorEnabled() { return entity.isOuterColorEnabled(); } + public void setOuterColorEnabled(boolean enabled) { entity.setOuterColorEnabled(enabled); } + + public float getOuterColorWidth() { return entity.getOuterColorWidth(); } + public void setOuterColorWidth(float width) { entity.setOuterColorWidth(width); } + + public float getOuterColorAlpha() { return entity.getOuterColorAlpha(); } + public void setOuterColorAlpha(float alpha) { entity.setOuterColorAlpha(alpha); } + + public float getRotationSpeed() { return entity.getRotationSpeed(); } + public void setRotationSpeed(float speed) { entity.setRotationSpeed(speed); } + + // ==================== INTERPOLATION ==================== + + public float getInterpolatedRotationX(float partialTicks) { return entity.getInterpolatedRotationX(partialTicks); } + public float getInterpolatedRotationY(float partialTicks) { return entity.getInterpolatedRotationY(partialTicks); } + public float getInterpolatedRotationZ(float partialTicks) { return entity.getInterpolatedRotationZ(partialTicks); } + public float getInterpolatedSize(float partialTicks) { return entity.getInterpolatedSize(partialTicks); } + + // ==================== LIGHTNING ==================== + + public boolean hasLightningEffect() { return entity.hasLightningEffect(); } + public void setLightningEffect(boolean enabled) { entity.setLightningEffect(enabled); } + + public float getLightningDensity() { return entity.getLightningDensity(); } + public void setLightningDensity(float density) { entity.setLightningDensity(density); } + + public float getLightningRadius() { return entity.getLightningRadius(); } + public void setLightningRadius(float radius) { entity.setLightningRadius(radius); } + + public int getLightningFadeTime() { return entity.getLightningFadeTime(); } + public void setLightningFadeTime(int ticks) { entity.setLightningFadeTime(ticks); } + + // ==================== LIFESPAN ==================== + + public float getMaxDistance() { return entity.getMaxDistance(); } + public void setMaxDistance(float distance) { entity.setMaxDistance(distance); } + + public int getMaxLifetime() { return entity.getMaxLifetime(); } + public void setMaxLifetime(int ticks) { entity.setMaxLifetime(ticks); } + + // ==================== COMBAT ==================== + + public float getDamage() { return entity.getDamage(); } + public void setDamage(float damage) { entity.setCombatDamage(damage); } + + public float getKnockback() { return entity.getKnockback(); } + public void setKnockback(float knockback) { entity.setCombatKnockback(knockback); } + + public float getKnockbackUp() { return entity.getKnockbackUp(); } + public void setKnockbackUp(float knockbackUp) { entity.setCombatKnockbackUp(knockbackUp); } + + public boolean isExplosive() { return entity.isExplosive(); } + public void setExplosive(boolean explosive) { entity.setExplosive(explosive); } + + public float getExplosionRadius() { return entity.getExplosionRadius(); } + public void setExplosionRadius(float radius) { entity.setExplosionRadius(radius); } + + public float getExplosionDamageFalloff() { return entity.getExplosionDamageFalloff(); } + public void setExplosionDamageFalloff(float falloff) { entity.setExplosionDamageFalloff(falloff); } + + // ==================== MOVEMENT ==================== + + public float getSpeed() { return entity.getSpeed(); } + public void setSpeed(float speed) { entity.setSpeed(speed); } + + public boolean isHoming() { return entity.isHoming(); } + public void setHoming(boolean homing) { entity.setHomingEnabled(homing); } + + public float getHomingStrength() { return entity.getHomingStrength(); } + public void setHomingStrength(float strength) { entity.setHomingStrength(strength); } + + public float getHomingRange() { return entity.getHomingRange(); } + public void setHomingRange(float range) { entity.setHomingRange(range); } + + // ==================== ANCHOR ==================== + + public int getAnchor() { return entity.getAnchor(); } + public float getAnchorOffsetX() { return entity.getAnchorOffsetX(); } + public float getAnchorOffsetY() { return entity.getAnchorOffsetY(); } + public float getAnchorOffsetZ() { return entity.getAnchorOffsetZ(); } + + // ==================== POSITION ==================== + + public double getStartX() { return entity.getStartX(); } + public double getStartY() { return entity.getStartY(); } + public double getStartZ() { return entity.getStartZ(); } + + // ==================== STATE ==================== + + public boolean hasHit() { return entity.getHasHit(); } + public boolean isCharging() { return entity.isCharging(); } + public float getChargeProgress() { return entity.getChargeProgress(); } + + // ==================== FIRE ==================== + + public void fire(IEntity target) { + if (target != null) { + Entity mcTarget = target.getMCEntity(); + setMotionToward(mcTarget.posX, mcTarget.posY + mcTarget.getEyeHeight(), mcTarget.posZ); + } + ensureSpawned(); + } + + public void fire(double x, double y, double z) { + setMotionToward(x, y, z); + ensureSpawned(); + } + + public void fire(float yaw, float pitch) { + float yawRad = (float) Math.toRadians(yaw); + float pitchRad = (float) Math.toRadians(pitch); + entity.motionX = -Math.sin(yawRad) * Math.cos(pitchRad) * entity.getSpeed(); + entity.motionY = -Math.sin(pitchRad) * entity.getSpeed(); + entity.motionZ = Math.cos(yawRad) * Math.cos(pitchRad) * entity.getSpeed(); + ensureSpawned(); + } + + public void fire(IEntityLivingBase caster) { + if (caster == null) return; + initFromCaster(caster); + fire(caster.getRotation(), caster.getPitch()); + } + + public void fire(IEntityLivingBase caster, IEntity target) { + if (caster == null) return; + initFromCaster(caster); + fire(target); + } + + /** + * Sets owner from caster and positions projectile at caster's eye level. + */ + private void initFromCaster(IEntityLivingBase caster) { + EntityLivingBase mc = (EntityLivingBase) caster.getMCEntity(); + entity.setOwnerEntityId(mc.getEntityId()); + double eyeY = mc.posY + mc.getEyeHeight(); + entity.setPosition(mc.posX, eyeY, mc.posZ); + entity.setStartPosition(mc.posX, eyeY, mc.posZ); + } + + /** + * Calculates and sets motion from the projectile's current position toward a target point. + */ + private void setMotionToward(double x, double y, double z) { + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + } + + protected void ensureSpawned() { + if (!entity.addedToChunk && entity.worldObj != null) { + entity.worldObj.spawnEntityInWorld(entity); + if (!entity.worldObj.isRemote) { + EventHooks.onEnergyProjectileFired(entity); + } + } + } + +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java index caac8d87d..65b2866af 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java @@ -1,5 +1,10 @@ package noppes.npcs.scripted.entity; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityAbilityProjectile; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -526,6 +531,16 @@ public class ScriptEntity implements IEntity { cls = EntityMob.class; else if (type == EntityType.NPC) cls = EntityNPCInterface.class; + else if (type == EntityType.ENERGY_PROJECTILE) + cls = EntityAbilityProjectile.class; + else if (type == EntityType.ENERGY_ORB) + cls = EntityAbilityOrb.class; + else if (type == EntityType.ENERGY_BEAM) + cls = EntityAbilityBeam.class; + else if (type == EntityType.ENERGY_DISC) + cls = EntityAbilityDisc.class; + else if (type == EntityType.ENERGY_LASER) + cls = EntityAbilityLaser.class; List entities = entity.worldObj.getEntitiesWithinAABB(cls, entity.boundingBox.expand(range, range, range)); List list = new ArrayList(); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java index f534f9dbc..2379c2035 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java @@ -7,6 +7,7 @@ import noppes.npcs.api.IPos; import noppes.npcs.api.ITimers; import noppes.npcs.api.ability.IDataAbilities; import noppes.npcs.api.entity.ICustomNpc; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntityLivingBase; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.entity.data.IModelData; @@ -28,6 +29,7 @@ import noppes.npcs.constants.EnumMovingType; import noppes.npcs.constants.EnumNavType; import noppes.npcs.constants.EnumRoleType; import noppes.npcs.constants.EnumStandingType; +import kamkeel.npcs.entity.EntityAbilityProjectile; import noppes.npcs.controllers.FactionController; import noppes.npcs.controllers.data.DialogOption; import noppes.npcs.controllers.data.Line; @@ -1463,4 +1465,13 @@ public class ScriptNpc extends ScriptLiving imp public IDataAbilities getAbilityData() { return new ScriptDataAbilities(npc); } + + public IEnergyProjectile[] getActiveEnergyProjectiles() { + java.util.List entities = EntityAbilityProjectile.getActiveProjectiles(npc.getEntityId()); + IEnergyProjectile[] result = new IEnergyProjectile[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + result[i] = (IEnergyProjectile) NpcAPI.Instance().getIEntity(entities.get(i)); + } + return result; + } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java b/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java index a1b91e1db..3608b9d1e 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java @@ -1,6 +1,7 @@ package noppes.npcs.scripted.entity; import kamkeel.npcs.controllers.AttributeController; +import kamkeel.npcs.entity.EntityAbilityProjectile; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.packets.data.AchievementPacket; import kamkeel.npcs.network.packets.data.ChatAlertPacket; @@ -31,6 +32,7 @@ import noppes.npcs.api.IPos; import noppes.npcs.api.IScreenSize; import noppes.npcs.api.ITimers; import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.gui.ICustomGui; @@ -933,4 +935,13 @@ public class ScriptPlayer extends ScriptLivingBase public String getFormattedCurrencyBalance() { return getData().tradeData.formatBalance(); } + + public IEnergyProjectile[] getActiveEnergyProjectiles() { + List entities = EntityAbilityProjectile.getActiveProjectiles(player.getEntityId()); + IEnergyProjectile[] result = new IEnergyProjectile[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + result[i] = (IEnergyProjectile) NpcAPI.Instance().getIEntity(entities.get(i)); + } + return result; + } } diff --git a/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java b/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java new file mode 100644 index 000000000..4a1fab5a2 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java @@ -0,0 +1,132 @@ +package noppes.npcs.scripted.event; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import noppes.npcs.api.IBlock; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.event.IEnergyProjectileEvent; +import noppes.npcs.constants.EnumScriptType; + +public class EnergyProjectileEvent extends CustomNPCsEvent implements IEnergyProjectileEvent { + public final IEnergyProjectile projectile; + public final IEntity owner; + + public EnergyProjectileEvent(IEnergyProjectile projectile) { + this.projectile = projectile; + this.owner = projectile.getOwner(); + } + + @Override + public IEnergyProjectile getProjectile() { + return projectile; + } + + @Override + public IEntity getOwner() { + return owner; + } + + @Override + public String getHookName() { + return "energyProjectileEvent"; + } + + /** + * energyProjectileFired + */ + public static class FiredEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.FiredEvent { + public FiredEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_FIRED.function; + } + } + + /** + * energyProjectileTick + */ + public static class UpdateEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.UpdateEvent { + public UpdateEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_TICK.function; + } + } + + /** + * energyProjectileEntityImpact + */ + @Cancelable + public static class EntityImpactEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.EntityImpactEvent { + private final IEntity target; + private float damage; + + public EntityImpactEvent(IEnergyProjectile projectile, IEntity target, float damage) { + super(projectile); + this.target = target; + this.damage = damage; + } + + @Override + public IEntity getTarget() { + return target; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT.function; + } + } + + /** + * energyProjectileBlockImpact + */ + public static class BlockImpactEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.BlockImpactEvent { + private final IBlock block; + + public BlockImpactEvent(IEnergyProjectile projectile, IBlock block) { + super(projectile); + this.block = block; + } + + @Override + public IBlock getBlock() { + return block; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT.function; + } + } + + /** + * energyProjectileExpired + */ + public static class ExpiredEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.ExpiredEvent { + public ExpiredEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_EXPIRED.function; + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java b/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java index cb7def405..b99aac1a1 100644 --- a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java +++ b/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java @@ -3,6 +3,8 @@ package noppes.npcs.scripted.event.player; import cpw.mods.fml.common.eventhandler.Cancelable; import kamkeel.npcs.controllers.data.ability.Ability; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.IDamageSource; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.entity.IEntityLivingBase; import noppes.npcs.api.entity.IPlayer; @@ -38,6 +40,108 @@ public class PlayerAbilityEvent extends PlayerEvent implements IPlayerAbilityEve return "playerAbilityEvent"; } + /** + * Fired when a player's ability starts executing (enters WINDUP phase). + */ + @Cancelable + public static class StartEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.StartEvent { + public StartEvent(IPlayer player, Ability ability, EntityLivingBase target) { + super(player, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_START.function; + } + } + + /** + * Fired when a player's ability enters the ACTIVE phase and performs its effect. + */ + @Cancelable + public static class ExecuteEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.ExecuteEvent { + public ExecuteEvent(IPlayer player, Ability ability, EntityLivingBase target) { + super(player, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_EXECUTE.function; + } + } + + /** + * Fired when a player's ability is interrupted by damage. + */ + public static class InterruptEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.InterruptEvent { + private final IDamageSource damageSource; + private final float damage; + + public InterruptEvent(IPlayer player, Ability ability, EntityLivingBase target, DamageSource source, float damage) { + super(player, ability, target); + this.damageSource = source != null ? NpcAPI.Instance().getIDamageSource(source) : null; + this.damage = damage; + } + + @Override + public IDamageSource getDamageSource() { + return damageSource; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_INTERRUPT.function; + } + } + + /** + * Fired when a player's ability completes its full execution cycle. + */ + public static class CompleteEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.CompleteEvent { + public CompleteEvent(IPlayer player, Ability ability, EntityLivingBase target) { + super(player, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_COMPLETE.function; + } + } + + /** + * Fired every tick while a player's ability is executing. + */ + public static class TickEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.TickEvent { + private final int abilityPhase; + private final int tick; + + public TickEvent(IPlayer player, Ability ability, EntityLivingBase target, int phase, int tick) { + super(player, ability, target); + this.abilityPhase = phase; + this.tick = tick; + } + + @Override + public int getAbilityPhase() { + return abilityPhase; + } + + @Override + public int getTick() { + return tick; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_TICK.function; + } + } + /** * Fired when a player's ability hits an entity with damage. * Canceling prevents the damage from being applied. From e7222790090f71bf1d6a9f2ec9eee9c515bb8dae Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 16 Feb 2026 01:03:35 -0500 Subject: [PATCH 72/76] Update API hash to reflect recent changes --- src/api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api b/src/api index 66fff09d2..efa8721d3 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 66fff09d2078a9d85a6ef27ef98c02a5944eb325 +Subproject commit efa8721d3658b45146d58d6731a0b83c4860f02e From 21b1571868b8a7a48c95895b161406b9872bdac7 Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 16 Feb 2026 01:15:52 -0500 Subject: [PATCH 73/76] Add flight checker to prevent abilities from affecting flying players --- .../data/ability/AbilityController.java | 16 ++++++++++++++++ .../noppes/npcs/ScriptPlayerEventHandler.java | 5 ++++- .../noppes/npcs/client/ClientTickHandler.java | 6 ++++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 43af10b7c..545673e70 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -9,8 +9,11 @@ import noppes.npcs.LogWriter; import noppes.npcs.api.handler.IAbilityHandler; import noppes.npcs.util.NBTJsonUtil; +import net.minecraft.entity.player.EntityPlayer; + import java.io.File; import java.util.*; +import java.util.function.Predicate; import java.util.function.Supplier; public class AbilityController implements IAbilityHandler { @@ -26,6 +29,7 @@ public class AbilityController implements IAbilityHandler { private final Map> externalVariants = new LinkedHashMap<>(); private final List fieldProviders = new ArrayList<>(); private final List extenders = new ArrayList<>(); + private final List> flightCheckers = new ArrayList<>(); // ── Derived State ──────────────────────────────────────────────────────── private final Set builtInTypeIds = new HashSet<>(); @@ -382,6 +386,18 @@ public class AbilityController implements IAbilityHandler { return extenders; } + public void registerFlightChecker(Predicate checker) { + flightCheckers.add(checker); + } + + public boolean isPlayerFlying(EntityPlayer player) { + if (player.capabilities.isFlying) return true; + for (Predicate checker : flightCheckers) { + if (checker.test(player)) return true; + } + return false; + } + /** * Fire onAbilityStart on all extenders. Returns false if ANY extender cancels. */ diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 8c9bde6ac..c0405c193 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -9,6 +9,7 @@ import kamkeel.npcs.addon.DBCAddon; import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.SyncController; import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.util.AttributeAttackUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -106,7 +107,9 @@ public class ScriptPlayerEventHandler { Ability current = playerData.abilityData.getCurrentAbility(); if (current == null || !current.hasAbilityMovement()) { player.motionX = 0; - player.motionY = Math.min(player.motionY, 0); // Prevent jumping, allow gravity + if (!AbilityController.Instance.isPlayerFlying(player)) { + player.motionY = Math.min(player.motionY, 0); + } player.motionZ = 0; player.velocityChanged = true; } diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index d12921756..d993762ee 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -6,6 +6,7 @@ import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import kamkeel.npcs.client.renderer.lightning.LightningBolt; +import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.player.CheckPlayerValue; @@ -133,9 +134,10 @@ public class ClientTickHandler { mc.thePlayer.motionZ = 0; } - // Prevent jumping: clamp upward motion when locked (allow gravity) + // Prevent jumping when locked (allow gravity only if not flying) if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) - && !ClientAbilityState.hasAbilityMovement) { + && !ClientAbilityState.hasAbilityMovement + && !AbilityController.Instance.isPlayerFlying(mc.thePlayer)) { mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); } } From cd28f69a0e108f026f693e398c078b547751b3f0 Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 16 Feb 2026 01:39:14 -0500 Subject: [PATCH 74/76] Enhance ability validation: add method to check if an ability can be resolved without deep copy and prune invalid unlocked abilities during load --- .../data/ability/AbilityController.java | 31 +++++++++++++++++++ .../controllers/data/PlayerAbilityData.java | 23 ++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 43af10b7c..ae21a9598 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -340,6 +340,37 @@ public class AbilityController implements IAbilityHandler { return builtAbilities.containsKey(key) || customAbilities.containsKey(key); } + /** + * Check if a key can be resolved to a valid ability without creating a deep copy. + * Uses the same lookup chain as {@link #resolveAbility(String)}. + */ + public boolean canResolveAbility(String key) { + if (key == null || key.isEmpty()) return false; + + // Built-in: exact name + if (builtAbilities.containsKey(key)) return true; + + // Built-in: case-insensitive name + for (String name : builtAbilities.keySet()) { + if (name.equalsIgnoreCase(key)) return true; + } + + // Built-in: registry key / ID + for (Ability ability : builtAbilities.values()) { + if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) return true; + } + + // Custom: exact UUID + if (customAbilities.containsKey(key)) return true; + + // Custom: case-insensitive name + for (Ability ability : customAbilities.values()) { + if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) return true; + } + + return false; + } + // ═══════════════════════════════════════════════════════════════════════════ // EXTENSION POINTS // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 6ced6f68a..d7f543726 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -15,6 +15,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.DamageSource; +import noppes.npcs.LogWriter; import noppes.npcs.api.ability.IPlayerAbilityData; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; @@ -23,6 +24,7 @@ import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; /** @@ -860,9 +862,30 @@ public class PlayerAbilityData implements IPlayerAbilityData { } } selectedIndex = compound.getInteger("PlayerAbilitySelected"); + + // Prune abilities that no longer exist (deleted custom abilities or removed built-ins) + validateUnlockedAbilities(); + if (selectedIndex >= unlockedAbilities.size()) { selectedIndex = Math.max(0, unlockedAbilities.size() - 1); } playingAbilityAnimation = compound.getBoolean("AbilityAnimating"); } + + /** + * Remove any unlocked ability keys that can no longer be resolved. + * Called during load to clean up references to deleted abilities. + */ + private void validateUnlockedAbilities() { + if (AbilityController.Instance == null) return; + + Iterator it = unlockedAbilities.iterator(); + while (it.hasNext()) { + String key = it.next(); + if (!AbilityController.Instance.canResolveAbility(key)) { + it.remove(); + LogWriter.info("Removed invalid ability reference from player data: " + key); + } + } + } } From 6c8e15c0148a1a3f2348b0a9b1f9a6b861ecb7d7 Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 16 Feb 2026 01:40:53 -0500 Subject: [PATCH 75/76] Update api --- src/api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api b/src/api index 66fff09d2..efa8721d3 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 66fff09d2078a9d85a6ef27ef98c02a5944eb325 +Subproject commit efa8721d3658b45146d58d6731a0b83c4860f02e From 01e18e0221c1166c1cae67e500228035c99261fb Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 16 Feb 2026 01:49:57 -0500 Subject: [PATCH 76/76] Beta 3 --- build.gradle | 2 +- src/main/java/noppes/npcs/CustomNpcs.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 7421f7cf7..0babda6bb 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { id 'idea' } -version = "1.11-beta1" +version = "1.11-beta3" group= "kamkeel.customnpc-plus" archivesBaseName = "CustomNPC-Plus" diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 933450557..caf86c7b5 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -118,7 +118,7 @@ import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; -@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta1") +@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta3") public class CustomNpcs { @SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")