diff --git a/src/api b/src/api index 2c2f0c0d8..a27e11595 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit 2c2f0c0d8f21f0ab3a3bc6bea168b3d3b85aa806 +Subproject commit a27e1159508c799c1b7b612ee09574f207bd64e0 diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java index d1b969921..8f87ff331 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java @@ -74,18 +74,20 @@ public class RenderAbilityBeam extends RenderEnergyAbility { // Render tail orb at origin (0,0,0) - only in anchored mode // Don't render if head is too close to origin (would cause overlap/extra orb appearance) if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) { - renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha); + renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, beam.getInnerAlpha()); } + float innerAlpha = beam.getInnerAlpha(); + // Render trail segments with smooth connections (with fading for non-anchored) if (beam.hasFadingTrail()) { - renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth()); + renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha); } else { - renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth()); + renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha); } // Render head at interpolated offset position - renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, partialTicks); + renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks); GL11.glPopMatrix(); @@ -139,7 +141,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { // Render inner core GL11.glScalef(innerScale, innerScale, innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, beam.getInnerAlpha(), 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -149,7 +151,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { * Render the tail orb at the origin (where the beam emanates from). * This orb does not rotate - it's a stable anchor point. */ - private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha) { + private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha, float innerAlpha) { GL11.glPushMatrix(); // Already at origin (0,0,0) @@ -171,7 +173,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { // Render inner core (solid) GL11.glPushMatrix(); GL11.glScalef(size * innerScale, size * innerScale, size * innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, innerAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); @@ -182,7 +184,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { * Uses averaged perpendicular vectors at connection points to prevent gaps. */ private void renderSmoothTrail(List trail, float width, int innerColor, int outerColor, - boolean outerColorEnabled, float outerColorWidth) { + boolean outerColorEnabled, float outerColorWidth, float innerAlpha) { if (trail.size() < 2) return; int trailSize = trail.size(); @@ -205,7 +207,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { } // Render inner core trail - renderTrailTube(trail, perpFrames, innerWidth, innerColor, 0.9f, false); + renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false); } /** @@ -213,7 +215,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { * Older trail points fade out based on their age. */ private void renderFadingTrail(EntityAbilityBeam beam, List trail, float width, int innerColor, int outerColor, - boolean outerColorEnabled, float outerColorWidth) { + boolean outerColorEnabled, float outerColorWidth, float innerAlpha) { if (trail.size() < 2) return; List ages = beam.getTrailPointAges(); @@ -235,7 +237,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { } // Render inner core trail with fading - renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, 0.9f); + renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, innerAlpha); } /** @@ -260,8 +262,8 @@ public class RenderAbilityBeam extends RenderEnergyAbility { // Calculate alpha based on age (older = more faded) float age1 = i < ages.size() ? ages.get(i) : 0; float age2 = (i + 1) < ages.size() ? ages.get(i + 1) : 0; - float fade1 = 1.0f - Math.min(1.0f, age1 / fadeTime); - float fade2 = 1.0f - Math.min(1.0f, age2 / fadeTime); + float fade1 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age1 / fadeTime)) : 0.0f; + float fade2 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age2 / fadeTime)) : 0.0f; float alpha1 = baseAlpha * fade1; float alpha2 = baseAlpha * fade2; @@ -541,7 +543,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { * Coordinates are relative to origin. */ private void renderHead(EntityAbilityBeam beam, double x, double y, double z, - float size, int innerColor, int outerColor, float outerAlpha, float partialTicks) { + float size, int innerColor, int outerColor, float outerAlpha, float innerAlpha, float partialTicks) { GL11.glPushMatrix(); GL11.glTranslated(x, y, z); @@ -580,7 +582,7 @@ public class RenderAbilityBeam extends RenderEnergyAbility { // Render inner core GL11.glScalef(innerScale, innerScale, innerScale); - renderCube(innerColor, 1.0f, 0.5f); + renderCube(innerColor, innerAlpha, 0.5f); GL11.glPopMatrix(); GL11.glPopMatrix(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java index 7f1a2e12c..d013dd306 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java @@ -67,7 +67,7 @@ public class RenderAbilityDisc extends RenderEnergyAbility { } // Render inner square (solid) - renderFlatSquare(disc.getInnerColor(), 1.0f, radius * innerScale, thickness * 1.2f); + renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha(), radius * innerScale, thickness * 1.2f); GL11.glPopMatrix(); GL11.glPopMatrix(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java index 543dba44c..e38764bfb 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java @@ -8,6 +8,9 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; +import java.util.HashMap; +import java.util.Map; + /** * Renders the AbilityLaser entity as a rectangular beam with clear inner/outer colors. *

@@ -16,6 +19,8 @@ import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public class RenderAbilityLaser extends RenderEnergyAbility { + private final Map tipLightningStates = new HashMap<>(); + @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { EntityAbilityLaser laser = (EntityAbilityLaser) entity; @@ -117,7 +122,7 @@ public class RenderAbilityLaser extends RenderEnergyAbility { renderBeamRectangle(renderStartX, renderStartY, renderStartZ, renderEndX, renderEndY, renderEndZ, horzX, horzY, horzZ, vertX, vertY, vertZ, - innerWidth, laser.getInnerColor(), alpha); + innerWidth, laser.getInnerColor(), alpha * laser.getInnerAlpha()); // Render lightning along the laser beam if (laser.hasLightningEffect() && laser.getCurrentLength() > 0.1f) { @@ -218,13 +223,16 @@ public class RenderAbilityLaser extends RenderEnergyAbility { /** * Get or create the tip lightning state for the laser. - * Stored as a secondary object in lightningState2. + * Persisted per entity ID so arcs accumulate and fade properly across frames. */ private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) { - // Use a simple approach - store in a transient field - // Since lightningState is already used, we'll create a new state each time - // This works because we're updating and rendering immediately - return new AttachedLightningRenderer.LightningState(); + int id = laser.getEntityId(); + AttachedLightningRenderer.LightningState state = tipLightningStates.get(id); + if (state == null) { + state = new AttachedLightningRenderer.LightningState(); + tipLightningStates.put(id, state); + } + return state; } /** diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java index 2dbeac3c0..b72be7a7c 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java @@ -70,6 +70,7 @@ public class RenderAbilitySweeper extends Render { /** * Render beam using the same style as the Beam entity trail. * Three layers: outer glow, middle, inner core. + * outerColorWidth is an additive offset from inner width (consistent with other renderers). */ private void renderBeam(float length, float width, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth) { @@ -82,21 +83,28 @@ public class RenderAbilitySweeper extends Render { float innerG = ((innerColor >> 8) & 0xFF) / 255.0f; float innerB = (innerColor & 0xFF) / 255.0f; + // Inner scale defines the core width (consistent with other renderers) + float innerScale = 0.6f; + float innerWidth = width * innerScale; + // Render from origin (0,0,0) to (0,0,length) in local coords // After rotation this extends in the correct world direction - // Outer glow (wider, translucent) - like beam trail - only if enabled + // Outer glow (wider, translucent) - only if enabled + // outerColorWidth is additive offset from inner width if (outerColorEnabled) { + float outerWidth = innerWidth + outerColorWidth * width; GL11.glDepthMask(false); - renderBeamSegment(0, 0, 0, 0, 0, length, width * outerColorWidth, outerR, outerG, outerB, 0.3f); + renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerR, outerG, outerB, 0.3f); GL11.glDepthMask(true); - // Middle layer - renderBeamSegment(0, 0, 0, 0, 0, length, width * 1.3f, outerR, outerG, outerB, 0.6f); + // Middle layer (halfway between inner and outer) + float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f; + renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, outerR, outerG, outerB, 0.6f); } - // Inner core (solid) - like beam trail inner - renderBeamSegment(0, 0, 0, 0, 0, length, width * 0.6f, innerR, innerG, innerB, 1.0f); + // Inner core (solid) + renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerR, innerG, innerB, 1.0f); } /** diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java index ec21a268a..20d31c56d 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java @@ -210,7 +210,7 @@ public class RenderAbilityZone extends Render { 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)]; + AccentStyle style = AccentStyle.values()[Math.max(0, Math.min(c.accentStyle, AccentStyle.values().length - 1))]; switch (style) { case SWAYING: renderSwayingAccents(c, c.ir, c.ig, c.ib, aa, c.height); @@ -314,7 +314,7 @@ public class RenderAbilityZone extends Render { private void spawnDefaultParticles(Ctx c) { int count = Math.round(3 * c.particleDensity); - ParticleMotion motion = ParticleMotion.values()[Math.min(c.particleMotion, ParticleMotion.values().length - 1)]; + ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(c.particleMotion, ParticleMotion.values().length - 1))]; for (int i = 0; i < count; i++) { double[] pos = randomPosInZone(c); double mx, my, mz; @@ -350,7 +350,7 @@ public class RenderAbilityZone extends Render { } private double[] getMotionForStyle(int motionOrdinal) { - ParticleMotion motion = ParticleMotion.values()[Math.min(motionOrdinal, ParticleMotion.values().length - 1)]; + ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(motionOrdinal, ParticleMotion.values().length - 1))]; switch (motion) { case DRIFTING: return new double[]{ diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java index 8653bb27d..871d48461 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java @@ -42,7 +42,6 @@ public class RenderEnergyDome extends RenderEnergyBarrier { float outerAlpha = dome.getOuterColorAlpha() * healthPercent; GL11.glDepthMask(false); renderSphere(dome.getOuterColor(), outerAlpha + flashAlpha, radius * outerScale, 8); - GL11.glDepthMask(true); } // TODO: Skybox Feature @@ -50,9 +49,9 @@ public class RenderEnergyDome extends RenderEnergyBarrier { // renderSkyboxSphere(dome.getSkyboxTexture(), radius, radius * 0.94f, 32, x, y, z); // } - // Render inner dome + GL11.glDepthMask(true); + // Render inner dome (depth write enabled so inner sphere properly occludes) renderSphere(dome.getInnerColor(), dome.getInnerAlpha(), radius * innerScale, 8); - GL11.glPopMatrix(); restoreRenderState(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java index b5ee31568..e2aa0868f 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java @@ -53,8 +53,8 @@ public class RenderEnergySlicer extends RenderEnergyAbility { GL11.glDepthMask(true); } - // Render inner blade (solid core, alpha 1.0 like Orb pattern) - renderBlade(slicer.getInnerColor(), 1.0f, + // Render inner blade (solid core) + renderBlade(slicer.getInnerColor(), slicer.getInnerAlpha(), width * 0.5f * innerScale, thickness, 0.03f); GL11.glPopMatrix(); 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 5e9e2342b..4debb90d6 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -3,7 +3,6 @@ package kamkeel.npcs.client.renderer.lightning; import net.minecraft.client.renderer.Tessellator; import org.lwjgl.opengl.GL11; -import java.awt.Color; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -37,6 +36,7 @@ public class AttachedLightningRenderer { public float getAlphaMultiplier() { // Fade out over lifetime + if (maxAge <= 0) return 0.0f; return 1.0f - ((float) age / (float) maxAge); } @@ -208,10 +208,9 @@ public class AttachedLightningRenderer { private static void renderBoltPath(Tessellator tess, List points, int color, float width, float alpha) { if (alpha <= 0.01f) return; - Color c = new Color(color); - int r = c.getRed(); - int g = c.getGreen(); - int b = c.getBlue(); + int r = (color >> 16) & 0xFF; + int g = (color >> 8) & 0xFF; + int b = color & 0xFF; int a = Math.min(255, Math.max(0, (int) (alpha * 255))); for (int i = 0; i < points.size() - 1; i++) { diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java index e077189ab..beea63fd3 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java @@ -56,7 +56,7 @@ public class LightningBolt { this.numSegments0 = 1; this.length = end.copy().subtract(start).mag(); - this.particleMaxAge = FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2; + this.particleMaxAge = Math.max(1, FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2); this.particleAge = -(int) (length * speed); segments.add(new Segment(start, end)); diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 9c73edc7c..87b4c235f 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -7,6 +7,7 @@ import kamkeel.npcs.controllers.data.ability.ChainedAbility; import kamkeel.npcs.controllers.data.ability.IAbilityAction; import kamkeel.npcs.controllers.data.ability.IAbilityExtender; import kamkeel.npcs.controllers.data.ability.IAbilityFieldProvider; +import kamkeel.npcs.controllers.data.ability.IEffectAction; import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; @@ -14,7 +15,7 @@ import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.ability.type.AbilityHazard; -import kamkeel.npcs.controllers.data.ability.type.AbilityHeal; +import kamkeel.npcs.controllers.data.ability.type.AbilityEffect; import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit; import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile; import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave; @@ -37,6 +38,8 @@ import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; import noppes.npcs.LogWriter; import noppes.npcs.api.handler.IAbilityHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.util.NBTJsonUtil; import java.io.File; @@ -79,6 +82,9 @@ public class AbilityController implements IAbilityHandler { private final Map chainedAbilitiesById = new LinkedHashMap<>(); // UUID → ChainedAbility private int chainedAbilityRevision = 0; + // ── Effect Action Registry ────────────────────────────────────────────── + private final Map effectActions = new LinkedHashMap<>(); + // ── Derived State ──────────────────────────────────────────────────────── private final Set builtInTypeIds = new HashSet<>(); @@ -143,7 +149,7 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:shockwave", AbilityShockwave::new); registerType("cnpc:guard", AbilityGuard::new); - registerType("cnpc:heal", AbilityHeal::new); + registerType("cnpc:effect", AbilityEffect::new); registerType("cnpc:hazard", AbilityHazard::new); registerType("cnpc:trap", AbilityTrap::new); @@ -372,6 +378,23 @@ public class AbilityController implements IAbilityHandler { file.delete(); } + // Clean up online players' unlocked ability lists + if (PlayerDataController.Instance != null) { + for (PlayerData pData : PlayerDataController.Instance.getAllPlayerData()) { + if (pData.abilityData != null) { + boolean changed = false; + if (uuid != null && !uuid.isEmpty() && pData.abilityData.hasUnlockedAbility(uuid)) { + pData.abilityData.lockAbility(uuid); + changed = true; + } + if (pData.abilityData.hasUnlockedAbility(name)) { + pData.abilityData.lockAbility(name); + changed = true; + } + } + } + } + customAbilityRevision++; LogWriter.info("Deleted custom ability: " + name); SyncController.syncAllCustomAbilities(); @@ -538,6 +561,22 @@ public class AbilityController implements IAbilityHandler { file.delete(); } + // Clean up online players' unlocked ability lists (chain keys use "chain:" prefix) + if (PlayerDataController.Instance != null) { + for (PlayerData pData : PlayerDataController.Instance.getAllPlayerData()) { + if (pData.abilityData != null) { + String chainKey = "chain:" + (uuid != null && !uuid.isEmpty() ? uuid : name); + if (pData.abilityData.hasUnlockedAbility(chainKey)) { + pData.abilityData.lockAbility(chainKey); + } + String chainNameKey = "chain:" + name; + if (!chainNameKey.equals(chainKey) && pData.abilityData.hasUnlockedAbility(chainNameKey)) { + pData.abilityData.lockAbility(chainNameKey); + } + } + } + } + chainedAbilityRevision++; LogWriter.info("Deleted chained ability: " + name); SyncController.syncAllChainedAbilities(); @@ -926,6 +965,37 @@ public class AbilityController implements IAbilityHandler { return builtInTypeIds.contains(typeId); } + public boolean isConcurrentCapableType(String typeId) { + Supplier factory = abilityTypes.get(typeId); + if (factory == null) return false; + return factory.get().isConcurrentCapable(); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // EFFECT ACTION REGISTRY + // ═══════════════════════════════════════════════════════════════════════════ + + public void registerEffectAction(IEffectAction action) { + if (action == null || action.getId() == null) return; + effectActions.put(action.getId(), action); + } + + public IEffectAction getEffectAction(String id) { + return effectActions.get(id); + } + + public String[] getEffectActionIds() { + return effectActions.keySet().toArray(new String[0]); + } + + public java.util.Collection getEffectActions() { + return effectActions.values(); + } + + public boolean hasEffectActions() { + return !effectActions.isEmpty(); + } + @Override public boolean hasType(String typeId) { return abilityTypes.containsKey(typeId); 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 9f332e12d..89e059967 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -236,6 +236,15 @@ public abstract class Ability implements IAbility, IAbilityAction { return false; } + /** + * Whether this ability can run concurrently alongside the primary ability in a chain. + * Override to return true for passive/effect abilities that don't need exclusive animations. + * Concurrent abilities skip animations entirely and run their tick/execute logic independently. + */ + public boolean isConcurrentCapable() { + return false; + } + // ═══════════════════════════════════════════════════════════════════ // TOGGLE CALLBACKS (optional overrides for toggleable abilities) // ═══════════════════════════════════════════════════════════════════ @@ -569,8 +578,7 @@ public abstract class Ability implements IAbility, IAbilityAction { defs.add(FieldDef.stringField("gui.displayName", this::getRawDisplayName, this::setDisplayName) .tab("General")); defs.add(FieldDef.labelField("ability.validFor", () -> - StatCollector.translateToLocal("ability.validFor") + ": \u00A7e" - + StatCollector.translateToLocal("ability.userType." + getAllowedBy().name())) + "\u00A7e" + StatCollector.translateToLocal("ability.userType." + getAllowedBy().name())) .tab("General")); defs.add(FieldDef.row( FieldDef.intField("ability.weight", this::getWeight, this::setWeight).range(1, 1000), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java index 830d5d0ec..77370b58c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java @@ -124,9 +124,6 @@ public class AbilityAction { return cachedAction; } Ability resolved = ctrl.resolveAbility(referenceId); - if (resolved != null && enabledOverride != null) { - resolved.setEnabled(enabledOverride); - } cachedAction = resolved; cachedRevision = rev; return cachedAction; @@ -140,9 +137,6 @@ public class AbilityAction { return cachedAction; } ChainedAbility resolved = ctrl.resolveChainedAbility(referenceId); - if (resolved != null && enabledOverride != null) { - resolved.setEnabled(enabledOverride); - } cachedAction = resolved; cachedRevision = rev; return cachedAction; @@ -184,12 +178,22 @@ public class AbilityAction { } } else { this.enabledOverride = enabled; - if (cachedAction != null) { - cachedAction.setEnabled(enabled); - } } } + /** + * Check if this slot is enabled. For inline slots, delegates to the action directly. + * For reference slots, uses enabledOverride if set, otherwise the resolved action's own state. + * This avoids mutating the shared controller instance. + */ + public boolean isSlotEnabled() { + if (enabledOverride != null) { + return enabledOverride; + } + IAbilityAction action = getAction(); + return action != null && action.isEnabled(); + } + // ═══════════════════════════════════════════════════════════════════ // INLINE CONVERSION (ability references only) // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityCustomEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityCustomEffect.java new file mode 100644 index 000000000..22428b704 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityCustomEffect.java @@ -0,0 +1,112 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.util.ValueUtil; + +/** + * Represents a custom effect reference that can be applied by abilities. + * Wraps the CustomEffectController system (player-only effects with script callbacks). + */ +public class AbilityCustomEffect { + + private int effectId = -1; + private int durationTicks = 60; + private byte level = 0; + private int index = 0; + + public AbilityCustomEffect() { + } + + public AbilityCustomEffect(int effectId, int durationTicks, byte level) { + this.effectId = effectId; + this.durationTicks = Math.max(1, durationTicks); + this.level = (byte) Math.max(0, Math.min(10, level)); + this.index = 0; + } + + public AbilityCustomEffect(int effectId, int durationTicks, byte level, int index) { + this(effectId, durationTicks, level); + this.index = index; + } + + public AbilityCustomEffect copy() { + return new AbilityCustomEffect(effectId, durationTicks, level, index); + } + + /** + * Applies this custom effect to the given entity. + * Only works on players (CustomEffectController is player-only). + */ + public void apply(EntityLivingBase entity) { + if (entity == null || effectId <= 0) return; + if (entity instanceof EntityPlayer) { + CustomEffectController.getInstance().applyEffect( + (EntityPlayer) entity, effectId, durationTicks, level, index); + } + } + + public boolean isValid() { + return effectId > 0; + } + + // ── NBT ── + + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setInteger("effectId", effectId); + nbt.setInteger("duration", durationTicks); + nbt.setByte("level", level); + nbt.setInteger("index", index); + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + this.effectId = nbt.getInteger("effectId"); + this.durationTicks = nbt.getInteger("duration"); + this.level = nbt.getByte("level"); + this.index = nbt.getInteger("index"); + } + + public static AbilityCustomEffect fromNBT(NBTTagCompound nbt) { + AbilityCustomEffect e = new AbilityCustomEffect(); + e.readNBT(nbt); + return e; + } + + // ── Getters/Setters ── + + public int getEffectId() { + return effectId; + } + + public void setEffectId(int effectId) { + this.effectId = effectId; + } + + public int getDurationTicks() { + return durationTicks; + } + + public void setDurationTicks(int durationTicks) { + this.durationTicks = Math.max(1, durationTicks); + } + + public byte getLevel() { + return level; + } + + public void setLevel(byte level) { + this.level = (byte) ValueUtil.clamp(level, 0, 10); + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = Math.max(0, index); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffectActionEntry.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffectActionEntry.java new file mode 100644 index 000000000..245d153b2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffectActionEntry.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.controllers.data.ability; + +import kamkeel.npcs.controllers.AbilityController; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; + +/** + * A configured instance of an {@link IEffectAction} stored on an ability. + * Holds the action ID and its configuration NBT. + */ +public class AbilityEffectActionEntry { + + private String actionId = ""; + private NBTTagCompound config = new NBTTagCompound(); + + public AbilityEffectActionEntry() { + } + + public AbilityEffectActionEntry(String actionId) { + this.actionId = actionId != null ? actionId : ""; + IEffectAction action = AbilityController.Instance.getEffectAction(this.actionId); + if (action != null) { + this.config = action.createDefaultConfig(); + } + } + + public AbilityEffectActionEntry copy() { + AbilityEffectActionEntry copy = new AbilityEffectActionEntry(); + copy.actionId = this.actionId; + copy.config = (NBTTagCompound) this.config.copy(); + return copy; + } + + /** + * Apply this action to a target entity. + */ + public void apply(EntityLivingBase caster, EntityLivingBase target) { + if (actionId.isEmpty()) return; + IEffectAction action = AbilityController.Instance.getEffectAction(actionId); + if (action != null) { + action.apply(caster, target, config); + } + } + + public boolean isValid() { + return !actionId.isEmpty() && AbilityController.Instance.getEffectAction(actionId) != null; + } + + // ── NBT ── + + public NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("actionId", actionId); + nbt.setTag("config", config); + return nbt; + } + + public void readNBT(NBTTagCompound nbt) { + this.actionId = nbt.getString("actionId"); + this.config = nbt.hasKey("config") ? nbt.getCompoundTag("config") : new NBTTagCompound(); + } + + public static AbilityEffectActionEntry fromNBT(NBTTagCompound nbt) { + AbilityEffectActionEntry entry = new AbilityEffectActionEntry(); + entry.readNBT(nbt); + return entry; + } + + // ── Getters/Setters ── + + public String getActionId() { + return actionId; + } + + public void setActionId(String actionId) { + this.actionId = actionId != null ? actionId : ""; + } + + public NBTTagCompound getConfig() { + return config; + } + + public void setConfig(NBTTagCompound config) { + this.config = config != null ? config : new NBTTagCompound(); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityTargetHelper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityTargetHelper.java new file mode 100644 index 000000000..b45bd2b02 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityTargetHelper.java @@ -0,0 +1,103 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.controllers.PartyController; +import noppes.npcs.controllers.data.Party; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.entity.EntityNPCInterface; + +/** + * Utility class for determining friend/foe relationships between entities. + * Extracted from EntityEnergyProjectile.shouldIgnoreEntity() for reuse + * across all AoE abilities and AbilityEffect targeting. + */ +public class AbilityTargetHelper { + + /** + * Determines if target is an ally of caster. + *

    + *
  • NPC vs NPC: same faction ID = ally
  • + *
  • NPC vs Player: faction friendly to player = ally
  • + *
  • Player vs NPC: NPC's faction friendly to player = ally
  • + *
  • Player vs Player: same party (if exists) = ally
  • + *
  • Passive NPCs are always considered allies (never enemies)
  • + *
+ */ + public static boolean isAlly(EntityLivingBase caster, Entity target) { + if (target == caster) return true; + + // NPC target checks + if (target instanceof EntityNPCInterface) { + EntityNPCInterface targetNpc = (EntityNPCInterface) target; + + // Passive NPCs are always considered allies + if (targetNpc.faction.isPassive) return true; + + // NPC caster: same faction = ally + if (caster instanceof EntityNPCInterface) { + EntityNPCInterface casterNpc = (EntityNPCInterface) caster; + if (casterNpc.faction.id == targetNpc.faction.id) return true; + } + + // Player caster: friendly faction = ally + if (caster instanceof EntityPlayer) { + if (targetNpc.faction.isFriendlyToPlayer((EntityPlayer) caster)) return true; + } + + return false; + } + + // Player target checks + if (target instanceof EntityPlayer && caster instanceof EntityNPCInterface) { + // NPC caster vs Player target: faction friendly to player = ally + EntityNPCInterface casterNpc = (EntityNPCInterface) caster; + return casterNpc.faction.isFriendlyToPlayer((EntityPlayer) target); + } + + if (target instanceof EntityPlayer && caster instanceof EntityPlayer) { + // Player vs Player: same party = ally + EntityPlayer casterPlayer = (EntityPlayer) caster; + EntityPlayer targetPlayer = (EntityPlayer) target; + PlayerData casterData = PlayerData.get(casterPlayer); + PlayerData targetData = PlayerData.get(targetPlayer); + if (casterData.partyUUID != null && casterData.partyUUID.equals(targetData.partyUUID)) { + Party party = PartyController.Instance().getParty(casterData.partyUUID); + if (party != null && !party.friendlyFire()) return true; + } + return false; + } + + // Unknown entity types: not an ally + return false; + } + + /** + * Determines if a target should be affected by an ability, given the + * filter mode and includeSelf setting. + * + * @param caster The entity using the ability + * @param target The potential target entity + * @param filter ALLIES, ENEMIES, or ALL + * @param includeSelf Whether to include the caster themselves + * @return true if the target should be affected + */ + public static boolean shouldAffect(EntityLivingBase caster, Entity target, + TargetFilter filter, boolean includeSelf) { + if (target == caster) return includeSelf; + if (!(target instanceof EntityLivingBase)) return false; + if (!target.isEntityAlive()) return false; + + switch (filter) { + case ALLIES: + return isAlly(caster, target); + case ENEMIES: + return !isAlly(caster, target); + case ALL: + return true; + default: + return false; + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbilityEntry.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbilityEntry.java index be8528ed0..a5bb7571b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbilityEntry.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbilityEntry.java @@ -31,6 +31,12 @@ public class ChainedAbilityEntry { */ private int delayTicks = 0; + /** + * Whether this entry should execute concurrently (alongside the previous ability) + * rather than sequentially. Only takes effect if the resolved ability isConcurrentCapable(). + */ + private boolean concurrentEnabled = true; + public ChainedAbilityEntry() { } @@ -104,6 +110,14 @@ public class ChainedAbilityEntry { this.delayTicks = Math.max(0, delayTicks); } + public boolean isConcurrentEnabled() { + return concurrentEnabled; + } + + public void setConcurrentEnabled(boolean concurrentEnabled) { + this.concurrentEnabled = concurrentEnabled; + } + // ═══════════════════════════════════════════════════════════════════ // RESOLUTION // ═══════════════════════════════════════════════════════════════════ @@ -157,6 +171,7 @@ public class ChainedAbilityEntry { copy.entryType = this.entryType; copy.abilityReference = this.abilityReference; copy.delayTicks = this.delayTicks; + copy.concurrentEnabled = this.concurrentEnabled; if (this.inlineAbility != null) { copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT()); } @@ -170,6 +185,7 @@ public class ChainedAbilityEntry { public NBTTagCompound writeNBT() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("Delay", delayTicks); + nbt.setBoolean("Concurrent", concurrentEnabled); if (entryType == EntryType.INLINE && inlineAbility != null) { nbt.setTag("InlineAbility", inlineAbility.writeNBT()); @@ -184,6 +200,7 @@ public class ChainedAbilityEntry { ChainedAbilityEntry entry = new ChainedAbilityEntry(); entry.delayTicks = Math.max(0, nbt.getInteger("Delay")); + entry.concurrentEnabled = nbt.hasKey("Concurrent") ? nbt.getBoolean("Concurrent") : true; // Inline entry (new format) if (nbt.hasKey("InlineAbility")) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ConcurrentSlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ConcurrentSlot.java new file mode 100644 index 000000000..cdfead9c0 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ConcurrentSlot.java @@ -0,0 +1,109 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.EntityLivingBase; + +/** + * Wraps a concurrent ability execution with its own independent lifecycle. + * Concurrent abilities skip animations, sounds, and movement/rotation locks. + * They run their execute/tick logic in parallel with the primary ability. + *

+ * Used by the chain system when an entry is concurrent-capable and concurrent-enabled. + */ +public class ConcurrentSlot { + + private final Ability ability; + private boolean started = false; + private boolean completed = false; + + public ConcurrentSlot(Ability ability) { + this.ability = ability; + } + + public Ability getAbility() { + return ability; + } + + public boolean isCompleted() { + return completed; + } + + /** + * Start the concurrent ability. Skips windup — goes straight to ACTIVE. + * Called once when the slot is activated. + */ + public void start(EntityLivingBase caster, EntityLivingBase target) { + // Skip windup for concurrent execution — fire immediately + ability.setWindUpTicks(0); + ability.start(target); + started = true; + + // Ability should now be in ACTIVE phase (0 windup → immediate) + if (ability.getPhase() == AbilityPhase.ACTIVE) { + ability.onExecute(caster, target); + } + + // Check if ability completed during onExecute (instant abilities like signalCompletion) + if (ability.getPhase() == AbilityPhase.IDLE) { + completed = true; + } + } + + /** + * Tick the concurrent ability. Called every game tick from AbstractDataAbilities. + * Handles phase transitions including burst delay → re-execute cycles. + */ + public void tick(EntityLivingBase caster, EntityLivingBase target) { + if (completed || !started) return; + + AbilityPhase oldPhase = ability.getPhase(); + boolean phaseChanged = ability.tick(); + AbilityPhase newPhase = ability.getPhase(); + + switch (newPhase) { + case ACTIVE: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Re-entering ACTIVE after burst delay → re-execute (burst re-fire) + ability.onExecute(caster, target); + if (ability.getPhase() == AbilityPhase.IDLE) { + completed = true; + return; + } + } + // Normal active tick + ability.onActiveTick(caster, target, ability.getCurrentTick()); + if (ability.getPhase() == AbilityPhase.IDLE) { + completed = true; + } + break; + + case BURST_DELAY: + // Waiting between bursts — nothing to do, tick() handles countdown + break; + + case WINDUP: + // Burst replay with windup — for concurrent, skip it by advancing + // (windUpTicks was set to 0 at start, but burst replay may re-enter WINDUP) + // The next tick() call will transition to ACTIVE + break; + + case IDLE: + completed = true; + break; + + case DAZED: + // Concurrent abilities don't get dazed — treat as completed + completed = true; + break; + } + } + + /** + * Force cleanup on interrupt. Called when the NPC is interrupted or combat ends. + */ + public void interrupt() { + if (!completed) { + ability.interrupt(); + completed = true; + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IEffectAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IEffectAction.java new file mode 100644 index 000000000..2f0323c76 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IEffectAction.java @@ -0,0 +1,42 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Interface for mod-registered effect actions that can be applied by AbilityEffect. + *

+ * Mods register implementations via {@code Register.EffectActions} or + * {@code AbilityController.Instance.registerEffectAction()}. + * Each action has a unique ID, display name, and apply logic. + * Actions can optionally provide custom configuration fields for the GUI. + */ +public interface IEffectAction { + + /** + * Unique identifier, e.g. "dbc:kiRestore", "mymod:buffSpeed". + */ + String getId(); + + /** + * Localized display name shown in the GUI selector. + */ + String getDisplayName(); + + /** + * Apply this action to a target entity. + * Called once per affected entity during ability execution. + * + * @param caster The entity that used the ability + * @param target The entity being affected + * @param config Action-specific configuration NBT (from GUI) + */ + void apply(EntityLivingBase caster, EntityLivingBase target, NBTTagCompound config); + + /** + * Create default configuration NBT for a new instance of this action. + */ + default NBTTagCompound createDefaultConfig() { + return new NBTTagCompound(); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/TargetFilter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/TargetFilter.java new file mode 100644 index 000000000..0247cc170 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/TargetFilter.java @@ -0,0 +1,32 @@ +package kamkeel.npcs.controllers.data.ability; + +/** + * Filter for determining which entities an ability should affect in AOE mode. + */ +public enum TargetFilter { + ALLIES, + ENEMIES, + ALL; + + @Override + public String toString() { + switch (this) { + case ALLIES: + return "ability.targetFilter.allies"; + case ENEMIES: + return "ability.targetFilter.enemies"; + case ALL: + return "ability.targetFilter.all"; + default: + return name(); + } + } + + public static TargetFilter fromString(String name) { + try { + return valueOf(name); + } catch (Exception e) { + return ALLIES; + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java index f31466329..ef9bcff57 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java @@ -78,7 +78,7 @@ public class EnergyBarrierData { } public void setMaxHealth(float maxHealth) { - this.maxHealth = Math.max(0, maxHealth); + this.maxHealth = Math.max(1.0f, maxHealth); } public boolean isUseHealth() { 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 2ecbf7cc5..ad3d603e5 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 @@ -75,7 +75,7 @@ public class EnergyCombatData implements IEnergyCombatData { @Override public void setExplosionRadius(float explosionRadius) { - this.explosionRadius = explosionRadius; + this.explosionRadius = Math.max(0, explosionRadius); } @Override @@ -98,12 +98,17 @@ public class EnergyCombatData implements IEnergyCombatData { } public void readNBT(NBTTagCompound nbt) { - damage = nbt.getFloat("damage"); - knockback = nbt.getFloat("knockback"); - knockbackUp = nbt.getFloat("knockbackUp"); - explosive = nbt.getBoolean("explosive"); - explosionRadius = nbt.getFloat("explosionRadius"); - explosionDamageFalloff = nbt.getFloat("explosionDamageFalloff"); + 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; + + // Sanitize + if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 7.0f; + if (Float.isNaN(knockback) || Float.isInfinite(knockback) || knockback < 0) knockback = 1.0f; + if (Float.isNaN(explosionRadius) || Float.isInfinite(explosionRadius) || explosionRadius < 0) explosionRadius = 3.0f; } 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 3b0998602..6363a69cb 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 @@ -128,13 +128,13 @@ public class EnergyDisplayData implements IEnergyDisplayData { } public void readNBT(NBTTagCompound nbt) { - innerColor = nbt.getInteger("innerColor"); - outerColor = nbt.getInteger("outerColor"); - outerColorEnabled = nbt.getBoolean("outerColorEnabled"); - outerColorWidth = nbt.getFloat("outerColorWidth"); - outerColorAlpha = nbt.getFloat("outerColorAlpha"); + 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; innerAlpha = nbt.hasKey("innerAlpha") ? nbt.getFloat("innerAlpha") : 1.0f; - rotationSpeed = nbt.getFloat("rotationSpeed"); + rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; // TODO: Skybox Feature // skyboxEnabled = nbt.hasKey("skyboxEnabled") && nbt.getBoolean("skyboxEnabled"); // skyboxTexture = nbt.hasKey("skyboxTexture") ? nbt.getString("skyboxTexture") : ""; 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 a03e70525..4f75c0841 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 @@ -31,7 +31,7 @@ public class EnergyHomingData implements IEnergyHomingData { @Override public void setSpeed(float speed) { - this.speed = speed; + this.speed = Math.max(0.01f, speed); } @Override @@ -72,10 +72,13 @@ public class EnergyHomingData implements IEnergyHomingData { } public void readNBT(NBTTagCompound nbt) { - speed = nbt.getFloat("speed"); - homing = nbt.getBoolean("homing"); - homingStrength = nbt.getFloat("homingStrength"); - homingRange = nbt.getFloat("homingRange"); + 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; + + // Sanitize speed to prevent stuck projectiles + if (Float.isNaN(speed) || Float.isInfinite(speed) || speed <= 0) speed = 0.5f; } 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 cce2a8283..2c8d1f6a1 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 @@ -26,7 +26,7 @@ public class EnergyLifespanData implements IEnergyLifespanData { @Override public void setMaxDistance(float maxDistance) { - this.maxDistance = maxDistance; + this.maxDistance = Float.isNaN(maxDistance) || maxDistance <= 0 ? 150.0f : maxDistance; } @Override @@ -36,7 +36,7 @@ public class EnergyLifespanData implements IEnergyLifespanData { @Override public void setMaxLifetime(int maxLifetime) { - this.maxLifetime = maxLifetime; + this.maxLifetime = maxLifetime <= 0 ? 200 : maxLifetime; } public void writeNBT(NBTTagCompound nbt) { @@ -47,6 +47,10 @@ public class EnergyLifespanData implements IEnergyLifespanData { public void readNBT(NBTTagCompound nbt) { maxDistance = nbt.getFloat("maxDistance"); maxLifetime = nbt.getInteger("maxLifetime"); + + // Sanitize: ensure minimum values so entities don't die instantly or live forever + if (Float.isNaN(maxDistance) || Float.isInfinite(maxDistance) || maxDistance <= 0) maxDistance = 150.0f; + if (maxLifetime <= 0) maxLifetime = 200; } 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 1eb2b001a..b8423e7aa 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 @@ -61,7 +61,7 @@ public class EnergyLightningData implements IEnergyLightningData { @Override public void setLightningFadeTime(int lightningFadeTime) { - this.lightningFadeTime = lightningFadeTime; + this.lightningFadeTime = Math.max(1, lightningFadeTime); } public void writeNBT(NBTTagCompound nbt) { @@ -72,10 +72,11 @@ public class EnergyLightningData implements IEnergyLightningData { } public void readNBT(NBTTagCompound nbt) { - lightningEffect = nbt.getBoolean("lightningEffect"); - lightningDensity = nbt.getFloat("lightningDensity"); - lightningRadius = nbt.getFloat("lightningRadius"); - lightningFadeTime = nbt.getInteger("lightningFadeTime"); + 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; + if (lightningFadeTime <= 0) lightningFadeTime = 1; } 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 ea7735e11..10014fb5f 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 @@ -187,6 +187,7 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { public void readNBT(NBTTagCompound nbt) { this.currentPath = nbt.getInteger("currentPath"); + trajectory.clear(); int i = 0; while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) { 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 2456b161d..4aa9d54ae 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 @@ -2,9 +2,14 @@ package kamkeel.npcs.controllers.data.ability.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.AbilityCustomEffect; +import kamkeel.npcs.controllers.data.ability.AbilityEffectActionEntry; import kamkeel.npcs.controllers.data.ability.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.IEffectAction; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.builder.FieldType; import noppes.npcs.client.gui.builder.GuiFieldBuilder; @@ -13,23 +18,36 @@ 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 noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.TreeMap; /** * Ability-specific extension of {@link GuiFieldBuilder} that handles - * the EFFECTS_LIST field type. + * the EFFECTS_LIST, CUSTOM_EFFECTS_LIST, and EFFECT_ACTIONS_LIST field types. */ @SideOnly(Side.CLIENT) public class AbilityFieldBuilder extends GuiFieldBuilder { - // Effects list metadata: widgetId -> [effectIndex, action] - // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text) + // Unified metadata: widgetId -> [index, action] + // EFFECTS_LIST actions: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text) + // CUSTOM_EFFECTS_LIST actions: 0=effectName, 1=duration(text), 2=level, 3=delete, 4=add + // EFFECT_ACTIONS_LIST actions: 0=actionSelector, 3=delete, 4=add private final Map effectWidgetMeta = new HashMap<>(); + // Cached sorted custom effect data for GUI selectors + private int[] sortedCustomEffectIds; + private String[] sortedCustomEffectNames; + + // Cached effect action data for GUI selectors + private String[] effectActionIds; + private String[] effectActionDisplayNames; + public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { super(parent, fontRenderer); } @@ -37,6 +55,10 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @Override protected int build(List fields) { effectWidgetMeta.clear(); + sortedCustomEffectIds = null; + sortedCustomEffectNames = null; + effectActionIds = null; + effectActionDisplayNames = null; return super.build(fields); } @@ -45,12 +67,21 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { if (def.getType() == FieldType.EFFECTS_LIST) { return renderEffectsList(def, y); } + if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) { + return renderCustomEffectsList(def, y); + } + if (def.getType() == FieldType.EFFECT_ACTIONS_LIST) { + return renderEffectActionsList(def, y); + } return -1; // not handled } + // ═══════════════════════════════════════════════════════════════════ + // POTION EFFECTS LIST (existing) + // ═══════════════════════════════════════════════════════════════════ + @SuppressWarnings("unchecked") private int renderEffectsList(FieldDef def, int y) { - // Section header y += 3; sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); y += 15; @@ -64,7 +95,6 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { for (int e = 0; e < effects.size() && e < 5; e++) { AbilityPotionEffect effect = effects.get(e); - // 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); @@ -72,7 +102,6 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { effectWidgetMeta.put(widgetId, new int[]{e, 0}); widgetId++; - // Duration text field GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer, colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks())); durField.setIntegersOnly(); @@ -83,17 +112,15 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { 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 + widgetId++; } - // Delete button GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); sw.addButton(delBtn); clearFieldMap.put(clearId, def); @@ -102,7 +129,6 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { 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, @@ -117,7 +143,6 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { } } - // Add button (if < 5 effects) if (effects.size() < 5) { GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); sw.addButton(addBtn); @@ -131,6 +156,195 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { return y; } + // ═══════════════════════════════════════════════════════════════════ + // CUSTOM EFFECTS LIST + // ═══════════════════════════════════════════════════════════════════ + + private void ensureCustomEffectCache() { + if (sortedCustomEffectIds != null) return; + + HashMap allEffects = CustomEffectController.getInstance().getCustomEffects(); + // Sort by name for consistent ordering + TreeMap nameToId = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (CustomEffect ce : allEffects.values()) { + if (ce.getName() != null && !ce.getName().isEmpty()) { + nameToId.put(ce.getName(), ce.id); + } + } + + sortedCustomEffectIds = new int[nameToId.size()]; + sortedCustomEffectNames = new String[nameToId.size()]; + int i = 0; + for (Map.Entry entry : nameToId.entrySet()) { + sortedCustomEffectIds[i] = entry.getValue(); + sortedCustomEffectNames[i] = entry.getKey(); + i++; + } + } + + private String getCustomEffectName(int effectId, int index) { + HashMap allEffects = CustomEffectController.getInstance().getEffectMap(index); + if (allEffects != null) { + CustomEffect ce = allEffects.get(effectId); + if (ce != null && ce.getName() != null && !ce.getName().isEmpty()) { + return ce.getName(); + } + } + // Fallback: check index 0 + if (index != 0) { + return getCustomEffectName(effectId, 0); + } + return "?"; + } + + private boolean hasAnyEffects() { + for (HashMap map : CustomEffectController.getInstance().indexMapper.values()) { + if (map != null && !map.isEmpty()) return true; + } + return false; + } + + @SuppressWarnings("unchecked") + private int renderCustomEffectsList(FieldDef def, int y) { + ensureCustomEffectCache(); + + y += 3; + sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); + y += 15; + + if (!hasAnyEffects()) { + sw.addLabel(new GuiNpcLabel(labelId++, "ability.noCustomEffects", colLLabel, y + 5, 0x888888)); + y += rowHeight; + return y; + } + + List effects = (List) def.getValue(); + if (effects == null) effects = new ArrayList<>(); + + String[] levelValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + + for (int e = 0; e < effects.size() && e < 5; e++) { + AbilityCustomEffect effect = effects.get(e); + + // Effect name button — opens SubGui picker + String effectName = getCustomEffectName(effect.getEffectId(), effect.getIndex()); + GuiNpcButton nameBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, effectName); + sw.addButton(nameBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 0}); + widgetId++; + + // Duration text field + GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks())); + durField.setIntegersOnly(); + durField.setMinMaxDefault(1, 12000, 60); + sw.addTextField(durField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 1}); + widgetId++; + + // Level selector (0-10) + GuiNpcButton lvlBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, levelValues, effect.getLevel()); + sw.addButton(lvlBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 2}); + widgetId++; + + // Delete button + GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); + sw.addButton(delBtn); + clearFieldMap.put(clearId, def); + effectWidgetMeta.put(clearId, new int[]{e, 3}); + clearId++; + + y += rowHeight; + } + + if (effects.size() < 5) { + GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); + sw.addButton(addBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{effects.size(), 4}); + widgetId++; + clearId++; + y += rowHeight; + } + + return y; + } + + // ═══════════════════════════════════════════════════════════════════ + // EFFECT ACTIONS LIST + // ═══════════════════════════════════════════════════════════════════ + + private void ensureEffectActionCache() { + if (effectActionIds != null) return; + + String[] ids = AbilityController.Instance.getEffectActionIds(); + effectActionIds = ids; + effectActionDisplayNames = new String[ids.length]; + for (int i = 0; i < ids.length; i++) { + IEffectAction action = AbilityController.Instance.getEffectAction(ids[i]); + effectActionDisplayNames[i] = action != null ? action.getDisplayName() : ids[i]; + } + } + + private int findEffectActionIndex(String actionId) { + ensureEffectActionCache(); + for (int i = 0; i < effectActionIds.length; i++) { + if (effectActionIds[i].equals(actionId)) return i; + } + return -1; + } + + @SuppressWarnings("unchecked") + private int renderEffectActionsList(FieldDef def, int y) { + ensureEffectActionCache(); + + if (effectActionIds.length == 0) return y; + + y += 3; + sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); + y += 15; + + List entries = (List) def.getValue(); + if (entries == null) entries = new ArrayList<>(); + + for (int e = 0; e < entries.size() && e < 5; e++) { + AbilityEffectActionEntry entry = entries.get(e); + + // Action selector + int selectedIdx = Math.max(0, findEffectActionIndex(entry.getActionId())); + GuiNpcButton actionBtn = new GuiNpcButton(widgetId, colLLabel, y, 180, 20, effectActionDisplayNames, selectedIdx); + sw.addButton(actionBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 0}); + widgetId++; + + // Delete button + GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); + sw.addButton(delBtn); + clearFieldMap.put(clearId, def); + effectWidgetMeta.put(clearId, new int[]{e, 3}); + clearId++; + + y += rowHeight; + } + + if (entries.size() < 5) { + GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); + sw.addButton(addBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{entries.size(), 4}); + widgetId++; + clearId++; + y += rowHeight; + } + + return y; + } + // ═══════════════════════════════════════════════════════════════════ // EVENT HANDLING OVERRIDES // ═══════════════════════════════════════════════════════════════════ @@ -138,36 +352,100 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @Override @SuppressWarnings("unchecked") public boolean handleButtonEvent(int buttonId, GuiButton button) { - // Check effects list buttons via metadata int[] meta = effectWidgetMeta.get(buttonId); if (meta != null) { FieldDef def = buttonFieldMap.get(buttonId); if (def == null) def = clearFieldMap.get(buttonId); - if (def != null && def.getType() == FieldType.EFFECTS_LIST) { + if (def == null) return false; + + int idx = meta[0]; + int action = meta[1]; + + // ── Potion Effects ── + if (def.getType() == FieldType.EFFECTS_LIST) { List effects = (List) def.getValue(); if (effects == null) return false; - int effectIdx = meta[0]; - int action = meta[1]; - switch (action) { - case 0: // Type changed - if (effectIdx < effects.size()) { - effects.get(effectIdx).setType(EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue())); + case 0: + if (idx < effects.size()) + effects.get(idx).setType(EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue())); + return true; + case 2: + if (idx < effects.size()) + effects.get(idx).setAmplifier(((GuiNpcButton) button).getValue()); + return true; + case 3: + if (idx < effects.size()) effects.remove(idx); + return true; + case 4: + if (effects.size() < 5) effects.add(new AbilityPotionEffect(EnumPotionType.Slowness, 60, 0)); + return true; + } + } + + // ── Custom Effects ── + if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects == null) return false; + ensureCustomEffectCache(); + switch (action) { + case 0: // Open effect picker SubGui + if (idx < effects.size()) { + int currentId = effects.get(idx).getEffectId(); + int currentIndex = effects.get(idx).getIndex(); + parent.setSubGuiWithResult(new SubGuiCustomEffectSelect(currentId, currentIndex), sub -> { + SubGuiCustomEffectSelect select = (SubGuiCustomEffectSelect) sub; + int selectedId = select.getSelectedEffectId(); + if (selectedId >= 0 && idx < effects.size()) { + effects.get(idx).setEffectId(selectedId); + effects.get(idx).setIndex(select.getSelectedIndex()); + } + }); } return true; - case 2: // Amp changed - if (effectIdx < effects.size()) { - effects.get(effectIdx).setAmplifier(((GuiNpcButton) button).getValue()); - } + case 2: // Level changed + if (idx < effects.size()) + effects.get(idx).setLevel((byte) ((GuiNpcButton) button).getValue()); return true; case 3: // Delete - if (effectIdx < effects.size()) { - effects.remove(effectIdx); - } + if (idx < effects.size()) effects.remove(idx); return true; case 4: // Add if (effects.size() < 5) { - effects.add(new AbilityPotionEffect(EnumPotionType.Slowness, 60, 0)); + parent.setSubGuiWithResult(new SubGuiCustomEffectSelect(-1), sub -> { + SubGuiCustomEffectSelect select = (SubGuiCustomEffectSelect) sub; + int selectedId = select.getSelectedEffectId(); + if (selectedId >= 0 && effects.size() < 5) { + effects.add(new AbilityCustomEffect(selectedId, 60, (byte) 0, select.getSelectedIndex())); + } + }); + } + return true; + } + } + + // ── Effect Actions ── + if (def.getType() == FieldType.EFFECT_ACTIONS_LIST) { + List entries = (List) def.getValue(); + if (entries == null) return false; + ensureEffectActionCache(); + switch (action) { + case 0: // Action selector changed + if (idx < entries.size()) { + int btnVal = ((GuiNpcButton) button).getValue(); + if (btnVal >= 0 && btnVal < effectActionIds.length) { + entries.get(idx).setActionId(effectActionIds[btnVal]); + IEffectAction ea = AbilityController.Instance.getEffectAction(effectActionIds[btnVal]); + if (ea != null) entries.get(idx).setConfig(ea.createDefaultConfig()); + } + } + return true; + case 3: // Delete + if (idx < entries.size()) entries.remove(idx); + return true; + case 4: // Add + if (entries.size() < 5 && effectActionIds.length > 0) { + entries.add(new AbilityEffectActionEntry(effectActionIds[0])); } return true; } @@ -183,14 +461,26 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { int[] meta = effectWidgetMeta.get(textFieldId); if (meta != null) { FieldDef def = textFieldMap.get(textFieldId); - if (def != null && def.getType() == FieldType.EFFECTS_LIST) { + if (def == null) return false; + + int idx = meta[0]; + int action = meta[1]; + + // ── Potion Effects ── + if (def.getType() == FieldType.EFFECTS_LIST) { List effects = (List) def.getValue(); - if (effects != null && meta[0] < effects.size()) { - 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()); - } + if (effects != null && idx < effects.size()) { + if (action == 1) effects.get(idx).setDurationTicks(field.getInteger()); + else if (action == 5) effects.get(idx).setManualPotionId(field.getInteger()); + } + return true; + } + + // ── Custom Effects ── + if (def.getType() == FieldType.CUSTOM_EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects != null && idx < effects.size()) { + if (action == 1) effects.get(idx).setDurationTicks(field.getInteger()); } return true; } 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 be7b29aa6..d34620c75 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 @@ -2,6 +2,8 @@ package kamkeel.npcs.controllers.data.ability.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityCustomEffect; +import kamkeel.npcs.controllers.data.ability.AbilityEffectActionEntry; import kamkeel.npcs.controllers.data.ability.AbilityPotionEffect; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.builder.FieldType; @@ -24,4 +26,17 @@ public class AbilityFieldDefs { v -> setter.accept((List) v)); } + @SuppressWarnings("unchecked") + public static FieldDef customEffectsListField(String label, Supplier> getter, Consumer> setter) { + return FieldDef.custom(label, FieldType.CUSTOM_EFFECTS_LIST, + () -> getter.get(), + v -> setter.accept((List) v)); + } + + @SuppressWarnings("unchecked") + public static FieldDef effectActionsListField(String label, Supplier> getter, Consumer> setter) { + return FieldDef.custom(label, FieldType.EFFECT_ACTIONS_LIST, + () -> getter.get(), + v -> setter.accept((List) v)); + } } 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 120f6190d..d6d7044f3 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,9 @@ 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.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.Telegraph; @@ -137,6 +139,7 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { if (!(entity instanceof EntityLivingBase)) continue; if (entity == caster) continue; if (hitEntities.contains(entity.getEntityId())) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; EntityLivingBase livingEntity = (EntityLivingBase) entity; 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 bac7cc234..e49e5bb55 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,7 +3,9 @@ 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.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.Telegraph; @@ -247,6 +249,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { for (EntityLivingBase entity : entities) { if (entity == caster) continue; if (hitEntities.contains(entity.getEntityId())) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; // If not piercing, stop after hitting one entity this sweep if (!piercing && !hitEntities.isEmpty()) break; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java new file mode 100644 index 000000000..c81e97ced --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java @@ -0,0 +1,502 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityCustomEffect; +import kamkeel.npcs.controllers.data.ability.AbilityEffectActionEntry; +import kamkeel.npcs.controllers.data.ability.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; +import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +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.nbt.NBTTagList; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.world.World; +import noppes.npcs.api.ability.type.IAbilityEffect; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Effect ability: Apply healing, potion effects, custom effects, and mod-registered + * effect actions to self or nearby entities. + *

+ * Supports: + *

    + *
  • SELF or AOE_SELF targeting modes
  • + *
  • AOE target filtering: ALLIES, ENEMIES, or ALL
  • + *
  • Healing (fixed amount + percentage)
  • + *
  • Potion effects via base Ability.effects list
  • + *
  • Custom effects from CustomEffectController (player-only)
  • + *
  • Mod-registered effect actions via IEffectAction registry
  • + *
  • Burst system for repeated reapplication (auras, debuffs)
  • + *
  • Concurrent execution alongside other abilities in chains
  • + *
+ */ +public class AbilityEffect extends Ability implements IAbilityEffect { + + // Type-specific parameters + private int durationTicks = 60; + private float healAmount = 10.0f; + private float healPercent = 0.0f; + private boolean includeSelf = true; + private float radius = 8.0f; + private boolean instantHeal = true; + private TargetFilter targetFilter = TargetFilter.ALLIES; + + // Custom effects (from CustomEffectController — player-only) + private List customEffects = new ArrayList<>(); + + // Mod-registered effect actions + private List effectActions = new ArrayList<>(); + + // Runtime state + private transient List affectedEntities; + + private List getAffectedEntities() { + if (affectedEntities == null) { + affectedEntities = new ArrayList<>(); + } + return affectedEntities; + } + + public AbilityEffect() { + this.typeId = "ability.cnpc.effect"; + this.name = "Effect"; + this.targetingMode = TargetingMode.SELF; + this.lockMovement = LockMovementType.WINDUP; + this.cooldownTicks = 0; + this.windUpTicks = 30; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + } + + // ==================== ABILITY TYPE OVERRIDES ==================== + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean allowBurst() { + return true; + } + + @Override + public boolean isTargetingModeLocked() { + return false; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.SELF, TargetingMode.AOE_SELF}; + } + + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public float getTelegraphRadius() { + return targetingMode == TargetingMode.AOE_SELF && radius > 0 ? radius : 0; + } + + // ==================== EXECUTION ==================== + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) return; + + if (!isPreview()) { + getAffectedEntities().clear(); + + if (targetingMode == TargetingMode.AOE_SELF && radius > 0) { + findEntitiesInRadius(caster, caster.worldObj); + } else { + if (includeSelf) { + getAffectedEntities().add(caster); + } + } + + if (instantHeal) { + for (EntityLivingBase entity : getAffectedEntities()) { + healEntity(entity); + applyAllEffects(caster, entity); + spawnHealParticles(caster.worldObj, entity); + } + } + } + + if (instantHeal) { + signalCompletion(); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if ((caster.worldObj.isRemote && !isPreview()) || instantHeal) return; + + if (tick % 10 == 0) { + float tickHealFixed = (healAmount / (float) durationTicks) * 10; + + for (EntityLivingBase entity : getAffectedEntities()) { + if (entity.isDead) continue; + + float totalTickHeal = tickHealFixed; + if (healPercent > 0) { + totalTickHeal += (entity.getMaxHealth() * healPercent / (float) durationTicks) * 10; + } + + if (totalTickHeal > 0) { + entity.heal(totalTickHeal); + } + + if (tick % 20 == 0) { + applyAllEffects(caster, entity); + spawnHealParticles(caster.worldObj, entity); + } + } + } + + if (tick >= durationTicks) { + signalCompletion(); + } + } + + // ==================== EFFECT APPLICATION ==================== + + /** + * Applies all configured effect types to a single entity: + * vanilla potion effects, custom effects, and mod-registered effect actions. + */ + private void applyAllEffects(EntityLivingBase caster, EntityLivingBase entity) { + applyEffects(entity); + applyCustomEffects(entity); + applyEffectActions(caster, entity); + } + + private void applyCustomEffects(EntityLivingBase entity) { + for (AbilityCustomEffect ce : customEffects) { + if (ce.isValid()) { + ce.apply(entity); + } + } + } + + private void applyEffectActions(EntityLivingBase caster, EntityLivingBase entity) { + for (AbilityEffectActionEntry ea : effectActions) { + if (ea.isValid()) { + ea.apply(caster, entity); + } + } + } + + // ==================== TARGET GATHERING ==================== + + @SuppressWarnings("unchecked") + private void findEntitiesInRadius(EntityLivingBase caster, World world) { + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox( + caster.posX - radius, caster.posY - 2, caster.posZ - radius, + caster.posX + radius, caster.posY + 3, caster.posZ + radius + ); + + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, aabb); + + for (Entity entity : entities) { + if (!(entity instanceof EntityLivingBase)) continue; + EntityLivingBase living = (EntityLivingBase) entity; + + float dist = caster.getDistanceToEntity(living); + if (dist > radius) continue; + + if (!AbilityTargetHelper.shouldAffect(caster, living, targetFilter, includeSelf)) continue; + + getAffectedEntities().add(living); + } + } + + private void healEntity(EntityLivingBase entity) { + float totalHeal = healAmount; + if (healPercent > 0) { + totalHeal += entity.getMaxHealth() * healPercent; + } + if (totalHeal > 0) { + entity.heal(totalHeal); + } + } + + private void spawnHealParticles(World world, EntityLivingBase entity) { + for (int i = 0; i < 10; i++) { + double offsetX = (world.rand.nextDouble() - 0.5) * entity.width; + double offsetY = world.rand.nextDouble() * entity.height; + double offsetZ = (world.rand.nextDouble() - 0.5) * entity.width; + world.spawnParticle("happyVillager", + entity.posX + offsetX, + entity.posY + offsetY, + entity.posZ + offsetZ, + 0, 0.1, 0); + } + } + + // ==================== LIFECYCLE ==================== + + @Override + public void resetForBurst() { + getAffectedEntities().clear(); + } + + @Override + public void cleanup() { + getAffectedEntities().clear(); + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.selfHeal", a -> { + AbilityEffect e = (AbilityEffect) a; + a.setName("Self Heal"); + e.setTargetingMode(TargetingMode.SELF); + e.setIncludeSelf(true); + e.setInstantHeal(true); + }), + new AbilityVariant("ability.variant.healingAura", a -> { + AbilityEffect e = (AbilityEffect) a; + a.setName("Healing Aura"); + e.setTargetingMode(TargetingMode.AOE_SELF); + e.setTargetFilter(TargetFilter.ALLIES); + e.setIncludeSelf(true); + e.setRadius(8.0f); + e.setBurstEnabled(true); + e.setBurstAmount(5); + e.setBurstDelay(20); + }), + new AbilityVariant("ability.variant.poisonDebuff", a -> { + AbilityEffect e = (AbilityEffect) a; + a.setName("Poison Debuff"); + e.setTargetingMode(TargetingMode.AOE_SELF); + e.setTargetFilter(TargetFilter.ENEMIES); + e.setIncludeSelf(false); + e.setHealAmount(0); + e.setHealPercent(0); + e.setRadius(6.0f); + e.setBurstEnabled(true); + e.setBurstAmount(3); + e.setBurstDelay(40); + }) + ); + } + + // ==================== NBT ==================== + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setFloat("healAmount", healAmount); + nbt.setFloat("healPercent", healPercent); + nbt.setBoolean("includeSelf", includeSelf); + nbt.setFloat("radius", radius); + nbt.setBoolean("instantHeal", instantHeal); + nbt.setString("targetFilter", targetFilter.name()); + + // Custom effects + NBTTagList ceList = new NBTTagList(); + for (AbilityCustomEffect ce : customEffects) { + ceList.appendTag(ce.writeNBT()); + } + nbt.setTag("customEffects", ceList); + + // Effect actions + NBTTagList eaList = new NBTTagList(); + for (AbilityEffectActionEntry ea : effectActions) { + eaList.appendTag(ea.writeNBT()); + } + nbt.setTag("effectActions", eaList); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + this.durationTicks = nbt.getInteger("durationTicks"); + this.healAmount = nbt.getFloat("healAmount"); + this.healPercent = nbt.getFloat("healPercent"); + this.includeSelf = nbt.getBoolean("includeSelf"); + this.radius = nbt.getFloat("radius"); + this.instantHeal = nbt.getBoolean("instantHeal"); + this.targetFilter = TargetFilter.fromString(nbt.getString("targetFilter")); + + // Custom effects + customEffects.clear(); + if (nbt.hasKey("customEffects")) { + NBTTagList ceList = nbt.getTagList("customEffects", 10); + for (int i = 0; i < ceList.tagCount(); i++) { + AbilityCustomEffect ce = AbilityCustomEffect.fromNBT(ceList.getCompoundTagAt(i)); + if (ce.isValid()) customEffects.add(ce); + } + } + + // Effect actions + effectActions.clear(); + if (nbt.hasKey("effectActions")) { + NBTTagList eaList = nbt.getTagList("effectActions", 10); + for (int i = 0; i < eaList.tagCount(); i++) { + AbilityEffectActionEntry ea = AbilityEffectActionEntry.fromNBT(eaList.getCompoundTagAt(i)); + effectActions.add(ea); + } + } + } + + // ==================== GUI ==================== + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.boolField("ability.instantHeal", this::isInstantHeal, this::setInstantHeal) + .hover("ability.hover.instant"), + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) + .range(1, 1000).visibleWhen(() -> !this.isInstantHeal()), + FieldDef.section("ability.section.healing"), + FieldDef.row( + FieldDef.floatField("ability.healAmount", this::getHealAmount, this::setHealAmount), + FieldDef.floatField("ability.healPercent", this::getHealPercent, this::setHealPercent) + ), + FieldDef.section("ability.section.targeting") + .tab("Target").visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF), + FieldDef.enumField("ability.targetFilter", TargetFilter.class, + this::getTargetFilter, this::setTargetFilter) + .tab("Target").visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF), + FieldDef.row( + FieldDef.boolField("ability.includeSelf", this::isIncludeSelf, this::setIncludeSelf) + .visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF), + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius) + .visibleWhen(() -> this.targetingMode == TargetingMode.AOE_SELF) + ).tab("Target"), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), + AbilityFieldDefs.customEffectsListField("ability.customEffects", this::getCustomEffects, this::setCustomEffects), + AbilityFieldDefs.effectActionsListField("ability.effectActions", this::getEffectActionEntries, this::setEffectActionEntries) + .visibleWhen(() -> AbilityController.Instance.hasEffectActions()) + )); + } + + // ==================== GETTERS & SETTERS ==================== + + @Override + public int getDurationTicks() { + return durationTicks; + } + + @Override + public void setDurationTicks(int durationTicks) { + this.durationTicks = Math.max(1, durationTicks); + } + + @Override + public float getHealAmount() { + return healAmount; + } + + @Override + public void setHealAmount(float healAmount) { + this.healAmount = healAmount; + } + + @Override + public float getHealPercent() { + return healPercent; + } + + @Override + public void setHealPercent(float healPercent) { + this.healPercent = healPercent; + } + + @Override + public boolean isIncludeSelf() { + return includeSelf; + } + + @Override + public void setIncludeSelf(boolean includeSelf) { + this.includeSelf = includeSelf; + } + + @Override + public float getRadius() { + return radius; + } + + @Override + public void setRadius(float radius) { + this.radius = radius; + } + + @Override + public boolean isInstantHeal() { + return instantHeal; + } + + @Override + public void setInstantHeal(boolean instantHeal) { + this.instantHeal = instantHeal; + } + + public TargetFilter getTargetFilter() { + return targetFilter; + } + + public void setTargetFilter(TargetFilter targetFilter) { + this.targetFilter = targetFilter; + } + + @Override + public int getTargetFilterType() { + return targetFilter.ordinal(); + } + + @Override + public void setTargetFilterType(int filter) { + TargetFilter[] values = TargetFilter.values(); + if (filter >= 0 && filter < values.length) { + this.targetFilter = values[filter]; + } + } + + public List getCustomEffects() { + return customEffects; + } + + public void setCustomEffects(List customEffects) { + this.customEffects = customEffects != null ? customEffects : new ArrayList<>(); + } + + @Override + public int getCustomEffectCount() { + return customEffects.size(); + } + + public List getEffectActionEntries() { + return effectActions; + } + + public void setEffectActionEntries(List effectActions) { + this.effectActions = effectActions != null ? effectActions : new ArrayList<>(); + } + + @Override + public int getEffectActionCount() { + return effectActions.size(); + } +} 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 a23e38963..a9c505a56 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 @@ -32,6 +32,11 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { this.activeAnimationName = "Ability_Zone_Active"; } + @Override + public boolean isConcurrentCapable() { + return true; + } + @Override public float getZoneRadius() { return radius; 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 deleted file mode 100644 index 89cfd2dbf..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ /dev/null @@ -1,316 +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.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -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.AxisAlignedBB; -import net.minecraft.world.World; -import noppes.npcs.api.ability.type.IAbilityHeal; -import noppes.npcs.client.gui.builder.FieldDef; -import noppes.npcs.entity.EntityNPCInterface; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Heal ability: Restore health to self or allies. - * Can heal a fixed amount or percentage of max health. - */ -public class AbilityHeal extends Ability implements IAbilityHeal { - - // Type-specific parameters - private int durationTicks = 60; - private float healAmount = 10.0f; - private float healPercent = 0.0f; - private boolean healSelf = true; - private boolean healAllies = false; - private float healRadius = 0.0f; - private boolean instantHeal = true; - - // Runtime state - private transient List healedAllies; - - private List getHealedAllies() { - if (healedAllies == null) { - healedAllies = new ArrayList<>(); - } - return healedAllies; - } - - public AbilityHeal() { - this.typeId = "ability.cnpc.heal"; - this.name = "Heal"; - this.targetingMode = TargetingMode.SELF; - this.lockMovement = LockMovementType.WINDUP; - this.cooldownTicks = 0; - this.windUpTicks = 30; - // No telegraph for heal - it's a self/ally buff - this.telegraphType = TelegraphType.NONE; - this.showTelegraph = false; - } - - @Override - public boolean hasDamage() { - return false; - } - - @Override - public boolean allowBurst() { - return false; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.SELF}; - } - - @Override - 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, caster.worldObj); - } - - if (instantHeal) { - // Instant heal - apply all healing now - if (healSelf) { - healEntity(caster); - spawnHealParticles(caster.worldObj, caster); - } - - for (EntityLivingBase ally : getHealedAllies()) { - healEntity(ally); - spawnHealParticles(caster.worldObj, ally); - } - } - } - - if (instantHeal) { - // Instant heal completes immediately - signalCompletion(); - } - // If not instant, HoT healing is applied in onActiveTick - } - - @Override - 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) { - // Calculate tick-based heal for fixed amount - float tickHeal = (healAmount / (float) durationTicks) * 10; - - if (healSelf) { - float selfTickHeal = tickHeal; - // Add percentage-based heal portion - if (healPercent > 0) { - selfTickHeal += (caster.getMaxHealth() * healPercent / (float) durationTicks) * 10; - } - caster.heal(selfTickHeal); - if (tick % 20 == 0) { - spawnHealParticles(caster.worldObj, caster); - } - } - - if (healAllies && healRadius > 0) { - for (EntityLivingBase ally : getHealedAllies()) { - if (!ally.isDead) { - float allyTickHeal = tickHeal; - // Add percentage-based heal portion for each ally - if (healPercent > 0) { - allyTickHeal += (ally.getMaxHealth() * healPercent / (float) durationTicks) * 10; - } - ally.heal(allyTickHeal); - if (tick % 20 == 0) { - spawnHealParticles(caster.worldObj, ally); - } - } - } - } - } - - // Check if heal duration has ended - if (tick >= durationTicks) { - signalCompletion(); - } - } - - /** - * Find all allies in radius and add them to healedAllies list. - */ - private void findAlliesInRadius(EntityLivingBase caster, World world) { - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox( - caster.posX - healRadius, caster.posY - 2, caster.posZ - healRadius, - caster.posX + healRadius, caster.posY + 3, caster.posZ + healRadius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, aabb); - - for (Entity entity : entities) { - if (!(entity instanceof EntityLivingBase)) continue; - if (entity == caster) continue; - - EntityLivingBase living = (EntityLivingBase) entity; - - // Only heal other NPCs (allies) - if (living instanceof EntityNPCInterface) { - float dist = caster.getDistanceToEntity(living); - if (dist <= healRadius) { - getHealedAllies().add(living); - } - } - } - } - - private void healEntity(EntityLivingBase entity) { - float totalHeal = healAmount; - if (healPercent > 0) { - totalHeal += entity.getMaxHealth() * healPercent; - } - entity.heal(totalHeal); - } - - private void spawnHealParticles(World world, EntityLivingBase entity) { - for (int i = 0; i < 10; i++) { - double offsetX = (world.rand.nextDouble() - 0.5) * entity.width; - double offsetY = world.rand.nextDouble() * entity.height; - double offsetZ = (world.rand.nextDouble() - 0.5) * entity.width; - world.spawnParticle("happyVillager", - entity.posX + offsetX, - entity.posY + offsetY, - entity.posZ + offsetZ, - 0, 0.1, 0); - } - } - - @Override - public void cleanup() { - getHealedAllies().clear(); - } - - @Override - public float getTelegraphRadius() { - return healRadius > 0 ? healRadius : 0; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); - nbt.setFloat("healAmount", healAmount); - nbt.setFloat("healPercent", healPercent); - nbt.setBoolean("healSelf", healSelf); - nbt.setBoolean("healAllies", healAllies); - nbt.setFloat("healRadius", healRadius); - nbt.setBoolean("instantHeal", instantHeal); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - 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 - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } - - public float getHealAmount() { - return healAmount; - } - - public void setHealAmount(float healAmount) { - this.healAmount = healAmount; - } - - public float getHealPercent() { - return healPercent; - } - - public void setHealPercent(float healPercent) { - this.healPercent = healPercent; - } - - public boolean isHealSelf() { - return healSelf; - } - - public void setHealSelf(boolean healSelf) { - this.healSelf = healSelf; - } - - public boolean isHealAllies() { - return healAllies; - } - - public void setHealAllies(boolean healAllies) { - this.healAllies = healAllies; - } - - public float getHealRadius() { - return healRadius; - } - - public void setHealRadius(float healRadius) { - this.healRadius = healRadius; - } - - public boolean isInstantHeal() { - return instantHeal; - } - - public void setInstantHeal(boolean instantHeal) { - this.instantHeal = instantHeal; - } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - FieldDef.boolField("ability.instantHeal", this::isInstantHeal, this::setInstantHeal) - .hover("ability.hover.instant"), - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) - .range(1, 1000).visibleWhen(() -> !this.isInstantHeal()), - FieldDef.section("ability.section.healing"), - FieldDef.row( - FieldDef.floatField("ability.healAmount", this::getHealAmount, this::setHealAmount), - FieldDef.floatField("ability.healPercent", this::getHealPercent, this::setHealPercent) - ), - FieldDef.floatField("ability.healRadius", this::getHealRadius, this::setHealRadius), - FieldDef.row( - FieldDef.boolField("ability.healSelf", this::isHealSelf, this::setHealSelf) - .hover("ability.hover.healSelf"), - FieldDef.boolField("ability.healAllies", this::isHealAllies, this::setHealAllies) - .hover("ability.hover.healAllies") - ) - )); - } -} 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 d7314b707..740f97be8 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 @@ -3,7 +3,9 @@ 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.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; @@ -106,6 +108,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { for (Entity entity : entities) { if (!(entity instanceof EntityLivingBase) || entity == caster) continue; EntityLivingBase livingTarget = (EntityLivingBase) entity; + if (!AbilityTargetHelper.shouldAffect(caster, livingTarget, TargetFilter.ENEMIES, false)) continue; double dx = livingTarget.posX - caster.posX; double dz = livingTarget.posZ - caster.posZ; 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 4cca57508..d600e006d 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 @@ -3,7 +3,9 @@ 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.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; @@ -72,6 +74,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { for (EntityLivingBase entity : entities) { if (entity == caster) continue; if (entity.isDead) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; double dist = caster.getDistanceToEntity(entity); if (dist > pushRadius) continue; 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 1e844271f..9f1c64ff5 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 @@ -3,7 +3,9 @@ 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.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.Telegraph; @@ -360,13 +362,17 @@ public class AbilitySlam extends Ability implements IAbilitySlam { for (Entity entity : entities) { if (entity instanceof EntityLivingBase && entity != caster) { EntityLivingBase livingTarget = (EntityLivingBase) entity; + if (!AbilityTargetHelper.shouldAffect(caster, livingTarget, TargetFilter.ENEMIES, false)) continue; // Check if actually within radius (bounding box is a cube, we want a circle) double dx = livingTarget.posX - caster.posX; double dz = livingTarget.posZ - caster.posZ; if (dx * dx + dz * dz <= radius * radius) { // Apply damage with scripted event support - applyAbilityDamage(caster, livingTarget, damage, knockbackStrength); + boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockbackStrength); + if (wasHit) { + applyEffects(livingTarget); + } } } } 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 d875353f6..64e3e5b46 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 @@ -38,6 +38,11 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { this.activeAnimationName = "Ability_Zone_Active"; } + @Override + public boolean isConcurrentCapable() { + return true; + } + @Override public float getZoneRadius() { return triggerRadius; 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 d5f68e013..59d2a280f 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 @@ -3,7 +3,9 @@ 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.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; @@ -91,6 +93,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { for (EntityLivingBase entity : entities) { if (entity == caster) continue; if (entity.isDead) continue; + if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; double dist = caster.getDistanceToEntity(entity); if (dist <= pullRadius) { 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 0b233a637..b5cc53a9e 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 @@ -519,6 +519,30 @@ public abstract class AbilityZone extends Ability { colorData.outerColorEnabled = enabled; } + public float getInnerAlpha() { + return colorData.innerAlpha; + } + + public void setInnerAlpha(float alpha) { + colorData.innerAlpha = alpha; + } + + public float getOuterColorWidth() { + return colorData.outerColorWidth; + } + + public void setOuterColorWidth(float width) { + colorData.outerColorWidth = width; + } + + public float getOuterColorAlpha() { + return colorData.outerColorAlpha; + } + + public void setOuterColorAlpha(float alpha) { + colorData.outerColorAlpha = alpha; + } + public boolean isGroundFill() { return groundFill; } @@ -711,12 +735,20 @@ public abstract class AbilityZone extends Ability { .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.row( + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor), + FieldDef.floatField("ability.innerAlpha", this::getInnerAlpha, this::setInnerAlpha).range(0, 1) + ).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) + .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") )); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java index ca1e1ac47..10643e7f2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java @@ -184,12 +184,12 @@ public class AbilityBeam extends AbilityEnergyProjectile impl 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) + FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth).range(0.1f, 100.0f), + FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize).range(0.1f, 100.0f) )); defs.add(FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) )); defs.add(FieldDef.section("ability.section.homing")); defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java index 0fd8b494c..1a9194282 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java @@ -208,14 +208,14 @@ public class AbilityDisc extends AbilityEnergyProjectile impl 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) + FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius).range(0.1f, 100.0f), + FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness).range(0.05f, 100.0f) )); 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) + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) )); defs.add(FieldDef.section("ability.section.homing")); defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java index 2fe0c4572..78a317cc2 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -132,7 +132,7 @@ public class AbilityDome extends AbilityEnergyBarrier { @Override protected void addBarrierTypeDefinitions(List defs) { defs.add(FieldDef.floatField("ability.domeRadius", this::getDomeRadius, this::setDomeRadius) - .range(1.0f, 30.0f)); + .range(1.0f, 50.0f)); defs.add(FieldDef.boolField("ability.followCaster", this::isFollowCaster, this::setFollowCaster) .hover("ability.hover.followCaster")); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java index 3319b7dc6..f78cf5654 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java @@ -247,7 +247,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { .visibleWhen(this::isUseHealth)); defs.add(FieldDef.boolField("ability.useDuration", this::isUseDuration, this::setUseDuration)); defs.add(FieldDef.intField("ability.duration", this::getBarrierDuration, this::setBarrierDuration) - .range(1, 6000).visibleWhen(this::isUseDuration)); + .range(1, 12000).visibleWhen(this::isUseDuration)); defs.add(FieldDef.floatField("ability.defaultMultiplier", this::getDefaultMultiplier, this::setDefaultMultiplier)); // Knockback section diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java index 2286919d6..da3e95c81 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java @@ -277,17 +277,22 @@ public abstract class AbilityEnergyProjectile } } + @Override + public void resetForBurst() { + // Non-overlap: kill old entities before next burst creates new ones + if (!burstOverlap) { + cleanup(); + } + // Clear reference so the next iteration creates fresh entities. + // For overlap mode, old entities stay alive (tracked in burstEntities). + entities = null; + } + @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target) { - // Create fresh entities if needed: - // - entities == null: windup was skipped (burst without replay animations) - // - isBurstRefire(): previous burst entities may still be alive, - // so we must create new ones for each burst iteration - if (entities == null || isBurstRefire()) { - // Non-overlap burst refire: kill old entities before creating new ones - if (isBurstRefire() && !burstOverlap && entities != null) { - cleanup(); - } + // Create entities if they don't exist yet. + // They'll already exist if onWindUpTick ran (windup replay), otherwise we create here. + if (entities == null) { entities = createAllEntities(caster, target); // If there's a fire delay, put unfired entities in charging state diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaserShot.java index 4639901d4..0ffa52946 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaserShot.java @@ -218,14 +218,14 @@ public class AbilityLaserShot extends AbilityEnergyProjectile implem FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) )); defs.add(FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), + FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize).range(0.1f, 100.0f), 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) + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) )); defs.add(FieldDef.section("ability.section.homing")); defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java index 5d78e8c1d..f19f9844f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java @@ -145,8 +145,8 @@ public class AbilityShield extends AbilityEnergyBarrier { @Override protected void addBarrierTypeDefinitions(List defs) { defs.add(FieldDef.row( - FieldDef.floatField("gui.width", this::getShieldWidth, this::setShieldWidth).range(0.5f, 10.0f), - FieldDef.floatField("gui.height", this::getShieldHeight, this::setShieldHeight).range(0.5f, 10.0f) + FieldDef.floatField("gui.width", this::getShieldWidth, this::setShieldWidth).range(0.5f, 100.0f), + FieldDef.floatField("gui.height", this::getShieldHeight, this::setShieldHeight).range(0.5f, 100.0f) )); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java index b6e08e83b..202938655 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySlicer.java @@ -183,14 +183,14 @@ public class AbilitySlicer extends AbilityEnergyProjectile { defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); defs.add(FieldDef.section("ability.section.slicer")); defs.add(FieldDef.row( - FieldDef.floatField("gui.width", this::getSliceWidth, this::setSliceWidth).range(0.5f, 20.0f), - FieldDef.floatField("gui.thickness", this::getSliceThickness, this::setSliceThickness).range(0.05f, 2.0f) + FieldDef.floatField("gui.width", this::getSliceWidth, this::setSliceWidth).range(0.5f, 100.0f), + FieldDef.floatField("gui.thickness", this::getSliceThickness, this::setSliceThickness).range(0.05f, 100.0f) )); defs.add(FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing) .hover("ability.hover.piercing")); defs.add(FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) )); defs.add(FieldDef.section("ability.section.explosive")); defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java index 1e0302522..5c9a9fe37 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -260,14 +260,14 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { ), FieldDef.section("ability.section.beam"), FieldDef.row( - FieldDef.floatField("gui.length", this::getBeamLength, this::setBeamLength), - FieldDef.floatField("gui.width", this::getBeamWidth, this::setBeamWidth) + FieldDef.floatField("gui.length", this::getBeamLength, this::setBeamLength).range(0.5f, 100.0f), + FieldDef.floatField("gui.width", this::getBeamWidth, this::setBeamWidth).range(0.1f, 100.0f) ), FieldDef.row( - FieldDef.floatField("gui.height", this::getBeamHeight, this::setBeamHeight), - FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed) + FieldDef.floatField("gui.height", this::getBeamHeight, this::setBeamHeight).range(0.1f, 100.0f), + FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed).range(0.1f, 30.0f) ), - FieldDef.intField("ability.rotations", this::getNumberOfRotations, this::setNumberOfRotations), + FieldDef.intField("ability.rotations", this::getNumberOfRotations, this::setNumberOfRotations).range(1, 20), FieldDef.row( FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing) .hover("ability.hover.piercing"), diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java index 60680888f..4320177c1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java @@ -205,8 +205,8 @@ public class AbilityWall extends AbilityEnergyBarrier { protected void addBarrierTypeDefinitions(List defs) { defs.add(FieldDef.section("ability.section.panel")); defs.add(FieldDef.row( - FieldDef.floatField("gui.width", this::getPanelWidth, this::setPanelWidth).range(0.5f, 20.0f), - FieldDef.floatField("gui.height", this::getPanelHeight, this::setPanelHeight).range(0.5f, 20.0f) + FieldDef.floatField("gui.width", this::getPanelWidth, this::setPanelWidth).range(0.5f, 100.0f), + FieldDef.floatField("gui.height", this::getPanelHeight, this::setPanelHeight).range(0.5f, 100.0f) )); defs.add(FieldDef.floatField("ability.heightOffset", this::getHeightOffset, this::setHeightOffset) .min(Float.NEGATIVE_INFINITY)); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 87cddc415..b80926aab 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -694,8 +694,8 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f; - this.headSize = nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f; + this.beamWidth = sanitize(nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f, 0.3f, MAX_ENTITY_SIZE); + this.headSize = sanitize(nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f, 0.5f, MAX_ENTITY_SIZE); this.headOffsetX = nbt.hasKey("HeadOffsetX") ? nbt.getDouble("HeadOffsetX") : 0; this.headOffsetY = nbt.hasKey("HeadOffsetY") ? nbt.getDouble("HeadOffsetY") : 0; this.headOffsetZ = nbt.hasKey("HeadOffsetZ") ? nbt.getDouble("HeadOffsetZ") : 0; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index 2b8a99d07..d16fc7709 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -38,6 +38,9 @@ public class EntityAbilityDisc extends EntityEnergyProjectile { // Disc shape properties private float discRadius = 1.0f; // Width of disc private float discThickness = 0.2f; // Height of disc + + // Boomerang owner-gone tracking + private int returnOwnerNullTicks = 0; private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) // Charging state (disc-specific target sizes) @@ -115,6 +118,8 @@ public class EntityAbilityDisc extends EntityEnergyProjectile { this.discRadius = 0.01f; this.discThickness = 0.01f; this.size = 0.01f; + this.renderCurrentSize = 0.01f; + this.prevRenderSize = 0.01f; // Initial position at anchor point Vec3 pos = AnchorPointHelper.calculateAnchorPosition(owner, anchorData); @@ -274,6 +279,7 @@ public class EntityAbilityDisc extends EntityEnergyProjectile { if (returning) { Entity owner = getOwnerEntity(); if (owner != null) { + returnOwnerNullTicks = 0; double distToOwner = Math.sqrt( (posX - owner.posX) * (posX - owner.posX) + (posY - owner.posY) * (posY - owner.posY) + @@ -281,8 +287,9 @@ public class EntityAbilityDisc extends EntityEnergyProjectile { ); return distToOwner < 1.5; } - // Owner gone but returning - keep going toward last known position - return false; + // Owner gone while returning - grace period then die + returnOwnerNullTicks++; + return returnOwnerNullTicks > 100; } // Not returning yet - don't die from distance (we'll trigger return above) @@ -487,8 +494,8 @@ public class EntityAbilityDisc extends EntityEnergyProjectile { protected void readProjectileNBT(NBTTagCompound nbt) { this.boomerang = nbt.hasKey("Boomerang") && nbt.getBoolean("Boomerang"); 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.discRadius = sanitize(nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f, 1.0f, MAX_ENTITY_SIZE); + this.discThickness = sanitize(nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f, 0.2f, MAX_ENTITY_SIZE); this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false; this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning"); // Charging state (common fields handled by base) diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 22880c1ec..38808cad9 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -466,17 +466,22 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { */ public float getLingerAlpha() { if (!fullyExtended) return 1.0f; - return 1.0f - ((float) ticksSinceFullExtension / lingerTicks); + if (lingerTicks <= 0) return 0.0f; + return Math.max(0.0f, 1.0f - ((float) ticksSinceFullExtension / lingerTicks)); } // ==================== NBT ==================== @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.laserWidth = nbt.hasKey("LaserWidth") ? nbt.getFloat("LaserWidth") : 0.2f; + this.laserWidth = sanitize(nbt.hasKey("LaserWidth") ? nbt.getFloat("LaserWidth") : 0.2f, 0.2f, MAX_ENTITY_SIZE); this.expansionSpeed = nbt.hasKey("ExpansionSpeed") ? nbt.getFloat("ExpansionSpeed") : 2.0f; + if (Float.isNaN(expansionSpeed) || Float.isInfinite(expansionSpeed) || expansionSpeed <= 0) expansionSpeed = 2.0f; this.lingerTicks = nbt.hasKey("LingerTicks") ? nbt.getInteger("LingerTicks") : 10; + if (lingerTicks <= 0) lingerTicks = 1; this.dieOnImpact = nbt.getBoolean("DieOnImpact"); + this.lockVerticalDirection = nbt.getBoolean("LockVerticalDir"); + this.ticksSinceFullExtension = nbt.getInteger("TicksSinceExtended"); this.dirX = nbt.getDouble("DirX"); this.dirY = nbt.getDouble("DirY"); this.dirZ = nbt.getDouble("DirZ"); @@ -495,6 +500,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { nbt.setFloat("ExpansionSpeed", expansionSpeed); nbt.setInteger("LingerTicks", lingerTicks); nbt.setBoolean("DieOnImpact", dieOnImpact); + nbt.setBoolean("LockVerticalDir", lockVerticalDirection); + nbt.setInteger("TicksSinceExtended", ticksSinceFullExtension); nbt.setDouble("DirX", dirX); nbt.setDouble("DirY", dirY); nbt.setDouble("DirZ", dirZ); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index f215ca6d6..fd739876d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -12,6 +12,9 @@ import net.minecraft.util.DamageSource; import net.minecraft.world.World; import noppes.npcs.LogWriter; import noppes.npcs.NpcDamageSource; +import noppes.npcs.controllers.PartyController; +import noppes.npcs.controllers.data.Party; +import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; import java.util.HashSet; @@ -129,6 +132,12 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { return; } + // Absolute hard lifetime cap (safety net) + if (ticksExisted > HARD_LIFETIME_CAP) { + this.setDead(); + return; + } + Entity owner = getOwnerEntity(); if (owner != null && owner.isDead) { this.setDead(); @@ -154,9 +163,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { if (currentAngle >= 360) { currentAngle -= 360; completedRotations++; - if (!worldObj.isRemote) { - LogWriter.info("[Sweeper] Completed rotation " + completedRotations + "/" + numberOfRotations); - } + // Rotation completed } // Server handles damage @@ -210,6 +217,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { if (!(entity instanceof EntityLivingBase)) continue; if (entity == owner) continue; if (hitThisTick.contains(entity.getEntityId())) continue; + if (shouldIgnoreEntity((EntityLivingBase) entity, owner)) continue; EntityLivingBase livingEntity = (EntityLivingBase) entity; @@ -258,6 +266,32 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { return entityFeetY < beamTopY; } + /** + * Check if an entity should be ignored for sweep damage. + * Same logic as EntityEnergyProjectile.shouldIgnoreEntity but adapted for sweeper. + */ + private boolean shouldIgnoreEntity(EntityLivingBase entity, Entity owner) { + if (entity instanceof EntityNPCInterface) { + EntityNPCInterface targetNpc = (EntityNPCInterface) entity; + if (targetNpc.faction.isPassive) return true; + if (owner instanceof EntityNPCInterface) { + if (((EntityNPCInterface) owner).faction.id == targetNpc.faction.id) return true; + } + if (owner instanceof EntityPlayer) { + if (targetNpc.faction.isFriendlyToPlayer((EntityPlayer) owner)) return true; + } + } + if (owner instanceof EntityPlayer && entity instanceof EntityPlayer) { + PlayerData ownerData = PlayerData.get((EntityPlayer) owner); + PlayerData targetData = PlayerData.get((EntityPlayer) entity); + if (ownerData.partyUUID != null && ownerData.partyUUID.equals(targetData.partyUUID)) { + Party party = PartyController.Instance().getParty(ownerData.partyUUID); + if (party != null && !party.friendlyFire()) return true; + } + } + return false; + } + private void applyDamage(EntityLivingBase target, Entity owner) { if (owner instanceof EntityNPCInterface) { target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), damage); @@ -330,20 +364,26 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { readEnergyBaseNBT(nbt); - this.beamLength = nbt.getFloat("BeamLength"); - this.beamWidth = nbt.getFloat("BeamWidth"); - this.beamHeight = nbt.getFloat("BeamHeight"); - this.sweepSpeed = nbt.getFloat("SweepSpeed"); - this.numberOfRotations = nbt.getInteger("NumRotations"); + this.beamLength = sanitize(nbt.getFloat("BeamLength"), 10.0f, MAX_ENTITY_SIZE); + this.beamWidth = sanitize(nbt.getFloat("BeamWidth"), 0.3f, MAX_ENTITY_SIZE); + this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 0.8f, MAX_ENTITY_SIZE); + this.sweepSpeed = nbt.hasKey("SweepSpeed") ? nbt.getFloat("SweepSpeed") : 3.0f; + if (Float.isNaN(sweepSpeed) || Float.isInfinite(sweepSpeed) || sweepSpeed <= 0) sweepSpeed = 3.0f; + this.numberOfRotations = nbt.hasKey("NumRotations") ? nbt.getInteger("NumRotations") : 2; + if (numberOfRotations <= 0) numberOfRotations = 1; this.completedRotations = nbt.getInteger("CompletedRotations"); - this.maxTicks = nbt.getInteger("MaxTicks"); + this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 400; + if (maxTicks <= 0) maxTicks = 400; this.targetEntityId = nbt.getInteger("TargetId"); this.currentAngle = nbt.getFloat("CurrentAngle"); + this.prevAngle = currentAngle; this.baseYaw = nbt.getFloat("BaseYaw"); this.deathWorldTime = nbt.getLong("DeathWorldTime"); - this.damage = nbt.getFloat("Damage"); - this.damageInterval = nbt.getInteger("DamageInterval"); - this.piercing = nbt.getBoolean("Piercing"); + this.damage = nbt.hasKey("Damage") ? nbt.getFloat("Damage") : 5.0f; + if (Float.isNaN(damage) || Float.isInfinite(damage)) damage = 5.0f; + this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 5; + if (damageInterval <= 0) damageInterval = 1; + this.piercing = !nbt.hasKey("Piercing") || nbt.getBoolean("Piercing"); this.lockOnTarget = nbt.getBoolean("LockOnTarget"); } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java index ac42b3b1d..a3aa494b4 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -7,6 +7,8 @@ import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityPotionEffect; +import kamkeel.npcs.controllers.data.ability.AbilityTargetHelper; +import kamkeel.npcs.controllers.data.ability.TargetFilter; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -357,6 +359,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD if (owner != null && entity == owner) continue; if (entity.isDead) continue; if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; + if (owner instanceof EntityLivingBase && !AbilityTargetHelper.shouldAffect((EntityLivingBase) owner, entity, TargetFilter.ENEMIES, false)) continue; double dx = entity.posX - posX; double dz = entity.posZ - posZ; @@ -391,6 +394,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD for (EntityLivingBase entity : entities) { if (owner != null && entity == owner) continue; + if (owner instanceof EntityLivingBase && !AbilityTargetHelper.shouldAffect((EntityLivingBase) owner, entity, TargetFilter.ENEMIES, false)) continue; double dx = entity.posX - posX; double dz = entity.posZ - posZ; if (shape == ZoneShape.SQUARE) { @@ -464,6 +468,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD for (EntityLivingBase entity : entities) { if (owner != null && entity == owner && !affectsCaster) continue; if (damagedThisTick.contains(entity.getEntityId())) continue; + if (entity != owner && owner instanceof EntityLivingBase && !AbilityTargetHelper.shouldAffect((EntityLivingBase) owner, entity, TargetFilter.ENEMIES, false)) continue; if (!isInZone(entity)) continue; if (damagePerSecond > 0) { @@ -711,7 +716,8 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - this.zoneType = ZoneType.values()[nbt.getInteger("ZoneType")]; + int zoneTypeOrd = nbt.getInteger("ZoneType"); + this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; try { this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); } catch (Exception e) { @@ -719,17 +725,17 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD } 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.getFloat("ZoneHeight"); - this.particleDensity = nbt.getFloat("ParticleDensity"); - this.particleScale = nbt.getFloat("ParticleScale"); - this.animSpeed = nbt.getFloat("AnimSpeed"); - this.lightningDensity = nbt.getFloat("LightningDensity"); + this.radius = nbt.hasKey("Radius") ? nbt.getFloat("Radius") : 4.0f; + this.durationTicks = nbt.hasKey("Duration") ? nbt.getInteger("Duration") : 200; + this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 200; + this.innerColor = nbt.hasKey("InnerColor") ? nbt.getInteger("InnerColor") : 0xFF6600; + this.outerColor = nbt.hasKey("OuterColor") ? nbt.getInteger("OuterColor") : 0xFF0000; + this.outerColorEnabled = !nbt.hasKey("OuterColorEnabled") || nbt.getBoolean("OuterColorEnabled"); + this.zoneHeight = nbt.hasKey("ZoneHeight") ? nbt.getFloat("ZoneHeight") : 2.0f; + this.particleDensity = nbt.hasKey("ParticleDensity") ? nbt.getFloat("ParticleDensity") : 1.0f; + this.particleScale = nbt.hasKey("ParticleScale") ? nbt.getFloat("ParticleScale") : 1.0f; + this.animSpeed = nbt.hasKey("AnimSpeed") ? nbt.getFloat("AnimSpeed") : 1.0f; + this.lightningDensity = nbt.hasKey("LightningDensity") ? nbt.getFloat("LightningDensity") : 1.0f; this.deathWorldTime = nbt.getLong("DeathWorldTime"); // Visual layer fields @@ -759,8 +765,9 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.visible = nbt.getBoolean("Visible"); // Hazard - this.damagePerSecond = nbt.getFloat("DamagePerSecond"); - this.damageInterval = nbt.getInteger("DamageInterval"); + this.damagePerSecond = nbt.hasKey("DamagePerSecond") ? nbt.getFloat("DamagePerSecond") : 1.0f; + this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 20; + if (damageInterval <= 0) damageInterval = 1; this.ignoreInvulnFrames = nbt.getBoolean("IgnoreInvuln"); this.affectsCaster = nbt.getBoolean("AffectsCaster"); @@ -888,7 +895,8 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override public void readSpawnData(ByteBuf buffer) { - this.zoneType = ZoneType.values()[buffer.readInt()]; + int zoneTypeOrd = buffer.readInt(); + this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; String shapeName = ByteBufUtils.readUTF8String(buffer); try { this.shape = ZoneShape.valueOf(shapeName); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java index 9721fb60e..2546fb8a2 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java @@ -18,6 +18,13 @@ import net.minecraft.world.World; */ public abstract class EntityEnergyAbility extends Entity implements IEntityAdditionalSpawnData { + // ==================== SAFETY CONSTANTS ==================== + protected static final int CHARGE_TIMEOUT_GRACE = 60; // Ticks of grace after charge should have ended + protected static final int HARD_LIFETIME_CAP = 1200; // 60 seconds absolute max for projectiles/sweepers + protected static final int BARRIER_HARD_LIFETIME_CAP = 12000; // 10 minutes absolute max for barriers + protected static final float MAX_ENTITY_SIZE = 100.0f; // Max size/width/length for any energy entity + protected static final float MAX_ENTITY_RADIUS = 50.0f; // Max radius for dome barriers + // ==================== VISUAL PROPERTIES ==================== protected EnergyDisplayData displayData = new EnergyDisplayData(); protected EnergyLightningData lightningData = new EnergyLightningData(); @@ -272,6 +279,17 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit return 0.0f; } + // ==================== SAFETY HELPERS ==================== + + /** + * Sanitize a float value loaded from NBT or external sources. + * Guards against NaN, Infinity, negative values, and values exceeding a max. + */ + protected static float sanitize(float value, float fallback, float max) { + if (Float.isNaN(value) || Float.isInfinite(value) || value < 0) return fallback; + return Math.min(value, max); + } + // ==================== NBT HELPERS ==================== /** diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java index 7ff4b04c2..af6766b15 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -174,6 +174,13 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return true; } + // Absolute hard lifetime cap (safety net for barriers with no duration) + if (ticksAlive > BARRIER_HARD_LIFETIME_CAP) { + onBarrierDestroyed(); + this.setDead(); + return true; + } + // Reset hit flash if (getHitFlash() > 0) { setHitFlash((byte) (getHitFlash() - 1)); @@ -272,6 +279,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { readEnergyBaseNBT(nbt); this.ticksAlive = nbt.getInteger("TicksAlive"); this.currentHealth = nbt.getFloat("CurrentHealth"); + if (Float.isNaN(currentHealth) || Float.isInfinite(currentHealth) || currentHealth < 0) currentHealth = barrierData.maxHealth; this.charging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); this.chargeTick = nbt.getInteger("ChargeTick"); this.chargeDuration = nbt.getInteger("ChargeDuration"); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 6ba436914..782413435 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -9,6 +9,7 @@ import net.minecraft.entity.Entity; 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 java.util.List; @@ -28,20 +29,20 @@ public class EntityEnergyDome extends EntityEnergyBarrier { public EntityEnergyDome(World world) { super(world); - this.setSize(1.0f, 1.0f); // Hitbox doesn't really matter, we use radius checks + this.setSize(1.0f, 1.0f); } public EntityEnergyDome(World world, EntityLivingBase owner, double x, double y, double z, float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, EnergyBarrierData barrier) { this(world); - this.setPosition(x, y, z); this.ownerEntityId = owner.getEntityId(); this.domeRadius = domeRadius; this.displayData = display; this.lightningData = lightning; this.barrierData = barrier; this.currentHealth = barrier.maxHealth; + this.setPosition(x, y, z); } @Override @@ -103,14 +104,25 @@ public class EntityEnergyDome extends EntityEnergyBarrier { double dx = projectile.posX - this.posX; double dy = projectile.posY - this.posY; double dz = projectile.posZ - this.posZ; - double distSq = dx * dx + dy * dy + dz * dz; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - // Check if projectile is within dome radius - if (distSq > domeRadius * domeRadius) return false; + // Check if projectile is outside dome radius + if (dist > domeRadius) return false; - // Check if projectile is moving inward (dot product of velocity and position relative to center) + // Approximate the projectile's position before last tick's movement. + // checkBarrierCollision runs BEFORE updateProjectile, so posX is post-last-movement. + // posX - motionX gives the pre-movement position (works for moveEntity and setPosition). + double prevDx = (projectile.posX - projectile.motionX) - this.posX; + double prevDy = (projectile.posY - projectile.motionY) - this.posY; + double prevDz = (projectile.posZ - projectile.motionZ) - this.posZ; + double prevDist = Math.sqrt(prevDx * prevDx + prevDy * prevDy + prevDz * prevDz); + + // Only block projectiles that crossed the dome boundary from outside. + // Projectiles spawned inside (prevDist < radius) pass through freely. + if (prevDist < domeRadius) return false; + + // Projectile entered from outside — check it's still moving inward double dot = dx * projectile.motionX + dy * projectile.motionY + dz * projectile.motionZ; - // Negative dot = moving toward center = incoming return dot < 0; } @@ -172,17 +184,37 @@ public class EntityEnergyDome extends EntityEnergyBarrier { } } + // ==================== MELEE (spherical check) ==================== + + /** + * Reject melee hits that land on the cubic bounding box but are outside the actual sphere. + */ + @Override + public boolean attackEntityFrom(DamageSource source, float amount) { + if (source.getEntity() != null) { + Entity attacker = source.getEntity(); + double dx = attacker.posX - this.posX; + double dy = (attacker.posY + attacker.height * 0.5) - this.posY; + double dz = attacker.posZ - this.posZ; + double distSq = dx * dx + dy * dy + dz * dz; + // Allow hit only if attacker is within sphere + melee reach margin + double maxDist = domeRadius + 5.0; + if (distSq > maxDist * maxDist) return false; + } + return super.attackEntityFrom(source, amount); + } + // ==================== BOUNDING BOX ==================== + /** + * Expands the ray-trace targeting area so players can melee-hit the dome + * from anywhere near its surface, not just the tiny 1x1 center. + * This is used by EntityRenderer.getMouseOver() to expand the entity BB + * for crosshair targeting without modifying the actual bounding box. + */ @Override - public AxisAlignedBB getBoundingBox() { - if (barrierData.meleeEnabled) { - return AxisAlignedBB.getBoundingBox( - posX - domeRadius, posY - domeRadius, posZ - domeRadius, - posX + domeRadius, posY + domeRadius, posZ + domeRadius - ); - } - return null; + public float getCollisionBorderSize() { + return domeRadius; } @Override @@ -193,6 +225,27 @@ public class EntityEnergyDome extends EntityEnergyBarrier { return distance < d * d; } + // ==================== DISTANCE (for render sorting) ==================== + + /** + * Returns squared distance from the given point to the nearest point on the dome sphere surface. + * Uses absolute distance to surface: |centerDist - radius|. + *

+ * Inside: nearest surface is (radius - centerDist) away. + * Outside: nearest surface is (centerDist - radius) away. + * This ensures entities inside the dome sort correctly relative to the dome shell. + */ + @Override + public double getDistanceSq(double x, double y, double z) { + double dx = this.posX - x; + double dy = this.posY - y; + double dz = this.posZ - z; + double centerDist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + double surfaceDist = Math.abs(centerDist - domeRadius); + return surfaceDist * surfaceDist; + } + // ==================== GETTERS ==================== public float getDomeRadius() { @@ -216,8 +269,8 @@ public class EntityEnergyDome extends EntityEnergyBarrier { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { readBarrierBaseNBT(nbt); - this.domeRadius = nbt.getFloat("DomeRadius"); - this.targetDomeRadius = nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius; + this.domeRadius = sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS); + this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index 98145836e..d3665e319 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -167,6 +167,8 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), panelData.launchDamage); } else if (owner instanceof EntityPlayer) { target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), panelData.launchDamage); + } else { + target.attackEntityFrom(DamageSource.generic, panelData.launchDamage); } } @@ -188,6 +190,7 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { // Max lifetime check if (ticksAlive > 200) { + onBarrierDestroyed(); this.setDead(); } } @@ -341,6 +344,47 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { return distance < d * d; } + // ==================== DISTANCE (for render sorting) ==================== + + /** + * Returns squared distance from the given point to the closest point on the panel surface. + * Accounts for panel rotation (panelYaw), width, height, and thickness. + * This ensures correct transparency render ordering when the camera is near or behind the panel. + */ + @Override + public double getDistanceSq(double x, double y, double z) { + double dx = x - this.posX; + double dy = y - this.posY; + double dz = z - this.posZ; + + float yawRad = (float) Math.toRadians(panelYaw); + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + + // Transform to panel-local space + // Panel normal (forward): (-sin, 0, cos) + // Panel right (width axis): (cos, 0, sin) + double localForward = dx * (-sin) + dz * cos; + double localRight = dx * cos + dz * sin; + double localUp = dy; + + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float halfThickness = 0.25f; + + // Clamp to panel bounds to find closest point on the panel volume + double clampedForward = Math.max(-halfThickness, Math.min(halfThickness, localForward)); + double clampedRight = Math.max(-halfW, Math.min(halfW, localRight)); + double clampedUp = Math.max(-halfH, Math.min(halfH, localUp)); + + // Distance from point to closest point on panel + double df = localForward - clampedForward; + double dr = localRight - clampedRight; + double du = localUp - clampedUp; + + return df * df + dr * dr + du * du; + } + // ==================== GETTERS ==================== public PanelMode getMode() { @@ -365,8 +409,10 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { this.mode = (modeOrdinal >= 0 && modeOrdinal < PanelMode.values().length) ? PanelMode.values()[modeOrdinal] : PanelMode.PLACED; panelData.readNBT(nbt); - this.targetPanelWidth = nbt.hasKey("TargetPanelWidth") ? nbt.getFloat("TargetPanelWidth") : panelData.panelWidth; - this.targetPanelHeight = nbt.hasKey("TargetPanelHeight") ? nbt.getFloat("TargetPanelHeight") : panelData.panelHeight; + panelData.panelWidth = sanitize(panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); + panelData.panelHeight = sanitize(panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); + this.targetPanelWidth = sanitize(nbt.hasKey("TargetPanelWidth") ? nbt.getFloat("TargetPanelWidth") : panelData.panelWidth, 3.0f, MAX_ENTITY_SIZE); + this.targetPanelHeight = sanitize(nbt.hasKey("TargetPanelHeight") ? nbt.getFloat("TargetPanelHeight") : panelData.panelHeight, 3.0f, MAX_ENTITY_SIZE); } @Override diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index b65439f83..4f0c16e50 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -219,6 +219,18 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { } } + // Charging timeout - if charge phase exceeded with grace period, force kill + if (isCharging() && chargeTick > chargeDuration + CHARGE_TIMEOUT_GRACE) { + this.setDead(); + return; + } + + // Absolute hard lifetime cap (safety net for any stuck state) + if (ticksExisted > HARD_LIFETIME_CAP) { + this.setDead(); + return; + } + // Set death time on first tick if not already set (handles chunk load/unload) // Skip during charging phase - lifetime starts when the entity actually fires if (deathWorldTime < 0 && worldObj != null && !isCharging()) { @@ -306,8 +318,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { * @return true if projectile was absorbed (caller should stop processing) */ protected boolean checkBarrierCollision() { - // Search area for barriers - must cover large domes (up to 30 radius) - double searchRange = 32.0; + // Search range must cover the largest possible barrier (dome radius up to MAX_ENTITY_RADIUS) + double searchRange = MAX_ENTITY_RADIUS + 5; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( posX - searchRange, posY - searchRange, posZ - searchRange, posX + searchRange, posY + searchRange, posZ + searchRange @@ -446,13 +458,15 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { protected void doExplosion() { if (previewMode) return; // Skip explosion in preview mode + float explosionRad = getExplosionRadius(); + if (Float.isNaN(explosionRad) || explosionRad <= 0) return; worldObj.playSoundEffect(posX, posY, posZ, "random.explode", 1.0f, 1.0f); Entity owner = getOwnerEntity(); AxisAlignedBB explosionBox = AxisAlignedBB.getBoundingBox( - posX - getExplosionRadius(), posY - getExplosionRadius(), posZ - getExplosionRadius(), - posX + getExplosionRadius(), posY + getExplosionRadius(), posZ + getExplosionRadius() + posX - explosionRad, posY - explosionRad, posZ - explosionRad, + posX + explosionRad, posY + explosionRad, posZ + explosionRad ); @SuppressWarnings("unchecked") @@ -467,9 +481,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { Math.pow(target.posZ - posZ, 2) ); - float radius = getExplosionRadius(); - if (radius > 0 && dist <= radius) { - float falloff = 1.0f - (float) (dist / radius) * getExplosionDamageFalloff(); + if (dist <= explosionRad) { + float falloff = 1.0f - (float) (dist / explosionRad) * getExplosionDamageFalloff(); applyDamage(target, getDamage() * falloff, getKnockback() * falloff); } } @@ -911,7 +924,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { protected void readBaseNBT(NBTTagCompound nbt) { readEnergyBaseNBT(nbt); - this.size = nbt.getFloat("Size"); + this.size = sanitize(nbt.getFloat("Size"), 1.0f, MAX_ENTITY_SIZE); // Read effects list this.effects.clear(); @@ -954,14 +967,12 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { nbt.setFloat("Size", size); - // Write effects list - if (!effects.isEmpty()) { - NBTTagList effectsList = new NBTTagList(); - for (AbilityPotionEffect effect : effects) { - effectsList.appendTag(effect.writeNBT()); - } - nbt.setTag("Effects", effectsList); + // Write effects list (always write, even if empty, so readBaseNBT finds the key) + NBTTagList effectsList = new NBTTagList(); + for (AbilityPotionEffect effect : effects) { + effectsList.appendTag(effect.writeNBT()); } + nbt.setTag("Effects", effectsList); nbt.setLong("DeathWorldTime", deathWorldTime); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java b/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java index 34fc986e6..29d0ac39a 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergySlicer.java @@ -328,11 +328,11 @@ public class EntityEnergySlicer extends EntityEnergyProjectile { @Override protected void readProjectileNBT(NBTTagCompound nbt) { readChargingNBT(nbt); - this.sliceWidth = nbt.hasKey("SliceWidth") ? nbt.getFloat("SliceWidth") : 3.0f; - this.sliceThickness = nbt.hasKey("SliceThickness") ? nbt.getFloat("SliceThickness") : 0.15f; + this.sliceWidth = sanitize(nbt.hasKey("SliceWidth") ? nbt.getFloat("SliceWidth") : 3.0f, 3.0f, MAX_ENTITY_SIZE); + this.sliceThickness = sanitize(nbt.hasKey("SliceThickness") ? nbt.getFloat("SliceThickness") : 0.15f, 0.15f, MAX_ENTITY_SIZE); this.piercing = !nbt.hasKey("Piercing") || nbt.getBoolean("Piercing"); - this.targetSliceWidth = nbt.hasKey("TargetSliceWidth") ? nbt.getFloat("TargetSliceWidth") : sliceWidth; - this.targetSliceThickness = nbt.hasKey("TargetSliceThickness") ? nbt.getFloat("TargetSliceThickness") : sliceThickness; + this.targetSliceWidth = sanitize(nbt.hasKey("TargetSliceWidth") ? nbt.getFloat("TargetSliceWidth") : sliceWidth, sliceWidth, MAX_ENTITY_SIZE); + this.targetSliceThickness = sanitize(nbt.hasKey("TargetSliceThickness") ? nbt.getFloat("TargetSliceThickness") : sliceThickness, sliceThickness, MAX_ENTITY_SIZE); } @Override 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 index 6de87cb22..256a38299 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java @@ -30,6 +30,7 @@ public final class PlayerAbilityStatePacket extends AbstractPacket { 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; + public static final byte FLAG_WAS_FLYING_AT_LOCK = 16; private byte flags; private float lockedYaw; diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index 5c28d5e1d..eab517ce9 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -3,6 +3,7 @@ package kamkeel.npcs.util; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import kamkeel.npcs.controllers.data.ability.IEffectAction; import noppes.npcs.LogWriter; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; @@ -173,4 +174,37 @@ public class Register { return new Register.Animations(modClass, animationsPath, namespace); } } + + public static class EffectActions extends Register { + + private EffectActions(String namespace) { + super("effect_action", namespace); + } + + public IEffectAction register(String name, IEffectAction action) { + String key = namespace + ":" + name.trim().toLowerCase().replaceAll(" ", "_"); + entries.put(key, () -> action); + return action; + } + + public void register() { + for (Map.Entry> entry : entries.entrySet()) { + AbilityController.Instance.registerEffectAction(entry.getValue().get()); + } + } + + public static Register.EffectActions create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("effect_action")) + REGISTERED_NAMESPACES.put("effect_action", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("effect_action").contains(namespace)) { + LogWriter.error("REGISTER EFFECT ACTIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("effect_action").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.EffectActions(namespace); + } + } } diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java index 717c6c0c9..240714738 100644 --- a/src/main/java/noppes/npcs/AbstractDataAbilities.java +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -5,6 +5,7 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityPhase; import kamkeel.npcs.controllers.data.ability.ChainedAbility; import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry; +import kamkeel.npcs.controllers.data.ability.ConcurrentSlot; import kamkeel.npcs.controllers.data.ability.ToggleEntry; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import net.minecraft.entity.EntityLivingBase; @@ -13,6 +14,7 @@ import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; import java.util.ArrayList; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -57,6 +59,7 @@ public abstract class AbstractDataAbilities { * Position lock state */ protected boolean positionLocked = false; + protected boolean wasFlyingAtLock = false; protected double lockedPosX = 0; protected double lockedPosY = 0; protected double lockedPosZ = 0; @@ -73,6 +76,12 @@ public abstract class AbstractDataAbilities { */ protected boolean interruptCooldownRolled = false; + /** + * Concurrent ability execution slots. Ticked independently alongside the primary ability. + * Concurrent abilities skip animations, sounds, and movement/rotation locks. + */ + protected List concurrentSlots = new ArrayList<>(); + // ═══════════════════════════════════════════════════════════════════ // ABSTRACT METHODS - Subclasses must implement // ═══════════════════════════════════════════════════════════════════ @@ -530,6 +539,13 @@ public abstract class AbstractDataAbilities { lockedPosY = entity.posY; lockedPosZ = entity.posZ; positionLocked = true; + + // Record flight state at lock time so airborne players stay at their height + // even if their flight system deactivates during input suppression + wasFlyingAtLock = entity instanceof net.minecraft.entity.player.EntityPlayer + && AbilityController.Instance != null + && AbilityController.Instance.isPlayerFlying((net.minecraft.entity.player.EntityPlayer) entity); + onPositionLockChanged(true); } @@ -538,9 +554,17 @@ public abstract class AbstractDataAbilities { */ protected void releaseLockedPosition() { positionLocked = false; + wasFlyingAtLock = false; onPositionLockChanged(false); } + /** + * Whether the entity was flying when the position lock was captured. + */ + public boolean wasFlyingAtLock() { + return wasFlyingAtLock; + } + /** * Hook for subclass to react to position lock state changes (e.g., NPC sets data watcher flag). */ @@ -590,8 +614,12 @@ public abstract class AbstractDataAbilities { return; } } - startChainEntry(chainTarget); + if (startChainEntry(chainTarget)) { + launchConsecutiveConcurrentEntries(chainTarget); + } } + // Tick concurrent slots even during chain delay + tickConcurrentSlots(); return; } @@ -731,6 +759,9 @@ public abstract class AbstractDataAbilities { // Post-phase hook (NPC: hit scan + movement control) onPostPhaseTick(currentAbility, target); + + // Tick concurrent slots independently + tickConcurrentSlots(); } // ═══════════════════════════════════════════════════════════════════ @@ -768,6 +799,10 @@ public abstract class AbstractDataAbilities { int delay = completedEntry.getDelayTicks(); chainEntryIndex++; + + // Skip any consecutive concurrent entries — launch them to concurrent slots + launchConsecutiveConcurrentEntries(target); + if (chainEntryIndex < currentChain.getEntries().size()) { // Check if target died and retarget if (target != null && target.isDead) { @@ -868,6 +903,9 @@ public abstract class AbstractDataAbilities { chainDelayRemaining = -1; } + // Interrupt all concurrent slots + interruptConcurrentSlots(); + // Let subclass handle cleanup onInterruptComplete(); } @@ -899,7 +937,11 @@ public abstract class AbstractDataAbilities { chainDelayRemaining = -1; // AFTER semantics: no delay before first entry (delay applies after each entry completes) - return startChainEntry(target); + boolean started = startChainEntry(target); + if (started) { + launchConsecutiveConcurrentEntries(target); + } + return started; } /** @@ -967,8 +1009,74 @@ public abstract class AbstractDataAbilities { return true; } + // ═══════════════════════════════════════════════════════════════════ + // CONCURRENT SLOT MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Tick all active concurrent slots. Remove completed ones. + * Called from tickCurrentAbility() and during chain delay countdown. + */ + protected void tickConcurrentSlots() { + if (concurrentSlots.isEmpty()) return; + + EntityLivingBase entity = getEntity(); + EntityLivingBase target = getTarget(); + + Iterator it = concurrentSlots.iterator(); + while (it.hasNext()) { + ConcurrentSlot slot = it.next(); + slot.tick(entity, target); + if (slot.isCompleted()) { + it.remove(); + } + } + } + + /** + * After starting a primary chain entry, scan forward and launch any consecutive + * concurrent entries (with delay=0) to concurrent slots immediately. + * This enables simultaneous execution of Effect abilities alongside the primary. + */ + protected void launchConsecutiveConcurrentEntries(EntityLivingBase target) { + if (currentChain == null) return; + + List entries = currentChain.getEntries(); + while (chainEntryIndex + 1 < entries.size()) { + ChainedAbilityEntry nextEntry = entries.get(chainEntryIndex + 1); + Ability resolved = nextEntry.resolve(); + if (resolved == null || !resolved.isConcurrentCapable() + || !nextEntry.isConcurrentEnabled()) break; + + // Only auto-launch concurrent entries with 0 delay + if (nextEntry.getDelayTicks() > 0) break; + + // Advance past this entry in the chain (it runs concurrently, not sequentially) + chainEntryIndex++; + + // Deep copy the ability so it has its own state + Ability concurrentCopy = AbilityController.Instance.fromNBT(resolved.writeNBT()); + if (concurrentCopy == null) continue; + + ConcurrentSlot slot = new ConcurrentSlot(concurrentCopy); + concurrentSlots.add(slot); + slot.start(getEntity(), target); + } + } + + /** + * Interrupt all active concurrent slots. Called on ability interrupt or combat reset. + */ + protected void interruptConcurrentSlots() { + for (ConcurrentSlot slot : concurrentSlots) { + slot.interrupt(); + } + concurrentSlots.clear(); + } + /** * Complete the chain execution. Rolls chain cooldown and clears all chain state. + * NOTE: Does NOT clear concurrent slots — they outlive the chain and tick independently. */ protected void completeChain() { if (currentChain != null) { diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 988a2f073..44fb852c6 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -326,10 +326,11 @@ public class DataAbilities extends AbstractDataAbilities { if (rotationLocked || hitScanActive) releaseRotationControl(); if (positionLocked) releaseLockedPosition(); } - // Clear chain state + // Clear chain and concurrent state currentChain = null; chainEntryIndex = -1; chainDelayRemaining = -1; + interruptConcurrentSlots(); return; } @@ -392,7 +393,7 @@ public class DataAbilities extends AbstractDataAbilities { for (AbilityAction slot : actionSlots) { IAbilityAction action = slot.getAction(); - if (action != null && isActionEligible(action, target)) { + if (action != null && isActionEligible(slot, action, target)) { eligible.add(action); weights.add(action.getWeight()); totalWeight += action.getWeight(); @@ -450,11 +451,11 @@ public class DataAbilities extends AbstractDataAbilities { /** * Check if an action (ability or chain) is eligible for use. */ - private boolean isActionEligible(IAbilityAction action, EntityLivingBase target) { + private boolean isActionEligible(AbilityAction slot, IAbilityAction action, EntityLivingBase target) { if (!action.getAllowedBy().allowsNpc()) { return false; } - if (!action.isEnabled()) { + if (!slot.isSlotEnabled()) { return false; } @@ -724,6 +725,7 @@ public class DataAbilities extends AbstractDataAbilities { public void reset() { stopCurrentAbility(); clearActiveToggles(); + interruptConcurrentSlots(); // Roll cooldown so NPC doesn't immediately attack after reset rollCooldownOnReset(); diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 81ff9ed6b..2cadbfd9f 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -106,9 +106,14 @@ public class ScriptPlayerEventHandler { if (playerData.abilityData.isMovementLocked()) { Ability current = playerData.abilityData.getCurrentAbility(); if (current == null || !current.hasAbilityMovement()) { + boolean sFlying = playerData.abilityData.wasFlyingAtLock() + || AbilityController.Instance.isPlayerFlying(player); + player.motionX = 0; - if (!AbilityController.Instance.isPlayerFlying(player)) { + if (!sFlying) { player.motionY = Math.min(player.motionY, 0); + } else { + player.motionY = 0; } player.motionZ = 0; player.velocityChanged = true; @@ -650,10 +655,12 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { - // Cancel any executing ability on respawn + // Reset ability state for reconstructed entity and re-sync to client. + // The death handler already interrupted the ability (with events/cooldowns), + // so this just cleans up transient state and syncs the new entity. PlayerData playerData = PlayerData.get(event.player); if (playerData != null) { - playerData.abilityData.interruptCurrentAbility(); + playerData.abilityData.resetOnRespawn(); } PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(event.player); diff --git a/src/main/java/noppes/npcs/client/ClientAbilityState.java b/src/main/java/noppes/npcs/client/ClientAbilityState.java index 8092a69a3..c737024fd 100644 --- a/src/main/java/noppes/npcs/client/ClientAbilityState.java +++ b/src/main/java/noppes/npcs/client/ClientAbilityState.java @@ -15,6 +15,7 @@ public class ClientAbilityState { public static boolean rotationLocked = false; public static boolean hasAbilityMovement = false; public static boolean positionLocked = false; + public static boolean wasFlyingAtLock = false; public static float lockedYaw = 0; public static float lockedPitch = 0; @@ -26,6 +27,7 @@ public class ClientAbilityState { rotationLocked = (flags & PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED) != 0; hasAbilityMovement = (flags & PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT) != 0; positionLocked = (flags & PlayerAbilityStatePacket.FLAG_POSITION_LOCKED) != 0; + wasFlyingAtLock = (flags & PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK) != 0; lockedYaw = yaw; lockedPitch = pitch; } @@ -53,6 +55,7 @@ public class ClientAbilityState { rotationLocked = false; hasAbilityMovement = false; positionLocked = false; + wasFlyingAtLock = 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 5a59461b7..36ad964e9 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -81,8 +81,6 @@ public class ClientTickHandler { // 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); @@ -91,7 +89,6 @@ public class ClientTickHandler { 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; @@ -128,17 +125,20 @@ public class ClientTickHandler { mc.thePlayer.movementInput.jump = false; mc.thePlayer.movementInput.sneak = false; - // Zero horizontal motion (unless ability provides its own movement) + // Zero all motion — position lock holds the player in place (server is authoritative) if (!ClientAbilityState.hasAbilityMovement) { mc.thePlayer.motionX = 0; mc.thePlayer.motionZ = 0; } - // Prevent jumping when locked (allow gravity only if not flying) + // Zero vertical motion: grounded players can't jump, flying players are frozen in air if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) - && !ClientAbilityState.hasAbilityMovement - && !AbilityController.Instance.isPlayerFlying(mc.thePlayer)) { - mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + && !ClientAbilityState.hasAbilityMovement) { + if (ClientAbilityState.wasFlyingAtLock) { + mc.thePlayer.motionY = 0; + } else { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + } } } 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 0a83895ed..85ef3e5d8 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -34,6 +34,7 @@ import noppes.npcs.constants.EnumScrollData; import noppes.npcs.entity.EntityNPCInterface; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -187,7 +188,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } availableTypesScroll.guiLeft = guiLeft + 5; availableTypesScroll.guiTop = y + 12; - availableTypesScroll.setList(getFilteredTypeList()); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); addScroll(availableTypesScroll); // Search bar for types @@ -218,14 +219,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // On/Off toggle for selected slot (under Load button) — chains and abilities if (selectedSlotIndex >= 0 && selectedSlotIndex < npcSlots.size() && selectedEntryIndex == -1) { AbilityAction selectedSlot = npcSlots.get(selectedSlotIndex); - boolean isEnabled = false; - if (selectedSlot.isChain()) { - ChainedAbility chain = selectedSlot.isInlineChain() ? selectedSlot.getInlineChain() : selectedSlot.getChainedAbility(); - isEnabled = chain != null && chain.isEnabled(); - } else { - Ability ability = selectedSlot.getAbility(); - isEnabled = ability != null && ability.isEnabled(); - } + boolean isEnabled = selectedSlot.isSlotEnabled(); GuiNpcButton toggleBtn = new GuiNpcButton(BTN_TOGGLE_SLOT, centerX, y + 112, 40, 20, new String[]{"gui.off", "gui.on"}, isEnabled ? 1 : 0); addButton(toggleBtn); @@ -241,6 +235,14 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Ability a = sel.getAbility(); if (a != null && a.isBuiltIn()) selectedIsBuiltIn = true; } + // Chain entries referencing built-in abilities are not editable + if (selectedIsChainEntry && sel.isChain()) { + ChainedAbility biChain = sel.isInlineChain() ? sel.getInlineChain() : sel.getChainedAbility(); + if (biChain != null && selectedEntryIndex < biChain.getEntries().size()) { + Ability resolved = biChain.getEntries().get(selectedEntryIndex).resolve(); + if (resolved != null && resolved.isBuiltIn()) selectedIsBuiltIn = true; + } + } // Sub-entries of reference chains are not directly editable from the NPC list if (selectedIsChainEntry && sel.isChainReference()) { selectedIsRefChainEntry = true; @@ -369,6 +371,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); if (chain != null && selectedEntryIndex < chain.getEntries().size()) { ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); + // Built-in abilities are always references — no editing allowed + Ability resolvedEntry = entry.resolve(); + if (resolvedEntry != null && resolvedEntry.isBuiltIn()) return; + if (entry.isInline() && slot.isInlineChain()) { // Inline entry in inline chain — edit directly Ability a = entry.getInlineAbility(); @@ -460,7 +466,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC pendingSaveEntryIdx = -1; } - if (abilityToSave != null) { + if (abilityToSave != null && !abilityToSave.isBuiltIn()) { if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) { abilityToSave.setNpcInlineEdit(true); setSubGui(abilityToSave.createConfigGui(this)); @@ -541,7 +547,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC filteredAbilityTypes.putAll(getFilteredData(allAbilityTypes)); if (availableTypesScroll != null) { - availableTypesScroll.setList(getFilteredTypeList()); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); } } else if (type == EnumScrollData.CUSTOM_ABILITIES) { existingPresetNames.clear(); @@ -605,7 +611,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (search.equals(getTextField(TF_SEARCH).getText())) return; search = getTextField(TF_SEARCH).getText().toLowerCase(); - availableTypesScroll.setList(getFilteredTypeList()); + availableTypesScroll.setUnsortedList(getFilteredTypeList()); availableTypesScroll.resetScroll(); } } @@ -640,16 +646,21 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC displayNameToTypeId.clear(); for (String typeId : filteredAbilityTypes.keySet()) { 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)) { + // Search matches either the display name or the typeId (strip color codes for matching) + String stripped = displayName.replaceAll("\u00A7.", ""); + if (search.isEmpty() || stripped.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) { + // Yellow for concurrent-capable types, gray for other built-in types + if (AbilityController.Instance.isConcurrentCapableType(typeId)) { + displayName = "\u00A7e" + displayName; + } else if (AbilityController.Instance.isBuiltInType(typeId)) { displayName = "\u00A77" + displayName; } list.add(displayName); displayNameToTypeId.put(displayName, typeId); } } + Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare( + a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", ""))); return list; } @@ -707,7 +718,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String typeName = getDisplayName(ability.getTypeId()); String customName = ability.getName(); - String colorPrefix = ability.isEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; + String colorPrefix = slot.isSlotEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; String nameDisplay; if (customName != null && !customName.isEmpty() && !customName.equals(typeName)) { @@ -728,8 +739,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC private String getChainHeaderEntry(int index, AbilityAction slot) { ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); String chainName = chain != null ? chain.getDisplayName() : "???"; - boolean enabled = chain != null && chain.isEnabled(); - String colorPrefix = enabled ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; + String colorPrefix = slot.isSlotEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r "; if (slot.isChainReference()) { return colorPrefix + (index + 1) + ". \u00A7e> [Chain] " + chainName + "\u00A7r"; } @@ -974,6 +984,13 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } } else if (slot.isChain() && selectedEntryIndex >= 0) { // Chain entry reference + // Block all editing for built-in abilities + ChainedAbility resolveChain = slot.isInlineChain() ? slot.getInlineChain() : slot.getChainedAbility(); + if (resolveChain != null && selectedEntryIndex < resolveChain.getEntries().size()) { + Ability entryResolved = resolveChain.getEntries().get(selectedEntryIndex).resolve(); + if (entryResolved != null && entryResolved.isBuiltIn()) return; + } + if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { if (slot.isChainReference()) { slot.convertToInline(); @@ -983,7 +1000,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); if (entry.convertToInline()) { Ability a = entry.getInlineAbility(); - if (a != null) { + if (a != null && !a.isBuiltIn()) { editingChainEntry = true; editChainSlotIdx = selectedSlotIndex; editChainEntryIdx = selectedEntryIndex; @@ -999,7 +1016,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (chain != null && selectedEntryIndex < chain.getEntries().size()) { ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex); Ability resolved = entry.resolve(); - if (resolved != null) { + if (resolved != null && !resolved.isBuiltIn()) { editingChainEntryParent = true; setSubGui(resolved.createConfigGui(this)); } @@ -1007,9 +1024,11 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } } else if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { // Standalone ability reference → convert to inline + Ability preCheck = slot.getAbility(); + if (preCheck != null && preCheck.isBuiltIn()) return; if (slot.convertToInline()) { Ability ability = slot.getAbility(); - if (ability != null) { + if (ability != null && !ability.isBuiltIn()) { ability.setId(UUID.randomUUID().toString()); ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); @@ -1019,7 +1038,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { Ability ability = slot.getAbility(); - if (ability != null) { + if (ability != null && !ability.isBuiltIn()) { setSubGui(ability.createConfigGui(this)); } } @@ -1084,39 +1103,29 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC * Called from SubGuiAbilityConfig when ability is saved. */ public void onAbilitySaved(Ability ability) { - // Check if we were editing a global parent ability via "Modify Parent" on a chain entry + // Editing a global parent ability via "Modify Parent" on a chain entry if (editingChainEntryParent) { PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); - editingChainEntryParent = false; return; } - // Check if we were editing an ability inside a chain entry - if (editingChainEntry && editChainSlotIdx >= 0 && editChainSlotIdx < npcSlots.size()) { - AbilityAction slot = npcSlots.get(editChainSlotIdx); - ChainedAbility chain = slot.isInlineChain() ? slot.getInlineChain() : null; - if (chain != null && editChainEntryIdx >= 0 && editChainEntryIdx < chain.getEntries().size()) { - // Update the inline ability on the entry — it's already the same object reference, - // but refresh the list and save to persist - } - editingChainEntry = false; - editChainSlotIdx = -1; - editChainEntryIdx = -1; - updateNpcAbilitiesList(); - save(); + // Editing an ability inside a chain entry — already same object reference. + // handleAbilityConfigClosed() will call updateNpcAbilitiesList() + save(). + if (editingChainEntry) { return; } if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { AbilityAction slot = npcSlots.get(selectedAbilityIndex); if (slot.isReference()) { + // Modify Parent on standalone reference — save to global preset PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); } else { + // Inline ability — update slot data npcSlots.set(selectedAbilityIndex, AbilityAction.inline(ability)); } - updateNpcAbilitiesList(); - save(); } + // updateNpcAbilitiesList() + save() deferred to handleAbilityConfigClosed() } @Override diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index f662da835..3aa153f59 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -144,9 +144,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi int y = 5; int labelCounter = LABEL_ID_START; - // General tab: type label at top — need to reserve space before building + // General tab: type label + optional concurrent label at top — reserve space if (activeTab == TAB_GENERAL) { y += ROW_H; + if (ability.isConcurrentCapable()) { + y += 15; + } } // Build declarative fields into an auto-created scroll window @@ -157,10 +160,15 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); - // General tab: add type label at top of scroll window + // General tab: add type label + optional concurrent label at top of scroll window if (activeTab == TAB_GENERAL) { - sw.addLabel(new GuiNpcLabel(builder.getNextLabelId(), "gui.type", 5, 5 + 5, 0xFFFFFF)); - sw.addLabel(new GuiNpcLabel(builder.getNextLabelId() + 1, ability.getTypeId(), 55, 5 + 5, 0xFFFFFF)); + int baseId = builder.getNextLabelId(); + sw.addLabel(new GuiNpcLabel(baseId, "gui.type", 5, 10, 0xFFFFFF)); + sw.addLabel(new GuiNpcLabel(baseId + 1, ability.getTypeId(), 55, 10, 0xFFFFFF)); + if (ability.isConcurrentCapable()) { + sw.addLabel(new GuiNpcLabel(baseId + 2, + StatCollector.translateToLocal("ability.concurrentInfo"), 5, 25, 0x55FF55)); + } } // Conditions on target tab — appended after field defs diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java index a1d235d51..70faa9059 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySelect.java @@ -18,18 +18,32 @@ import java.util.List; import java.util.Vector; /** - * Simple ability name picker. Shows all abilities (custom + built-in) in a - * single scroll list with search. Returns the selected ability name. + * Simple ability name picker with optional filter mode. + * Shows custom, built-in, or all abilities in a scroll list with search. + * Returns the selected ability name. */ public class SubGuiAbilitySelect extends SubGuiInterface implements ICustomScrollListener, IScrollData { + /** Show all abilities (custom + built-in). */ + public static final int FILTER_ALL = 0; + /** Show only custom abilities. */ + public static final int FILTER_CUSTOM_ONLY = 1; + /** Show only built-in abilities. */ + public static final int FILTER_BUILTIN_ONLY = 2; + private GuiCustomScroll scroll; private HashMap customData = new HashMap<>(); private HashMap builtInData = new HashMap<>(); private String selectedName = null; private String search = ""; + private final int filterMode; public SubGuiAbilitySelect() { + this(FILTER_ALL); + } + + public SubGuiAbilitySelect(int filterMode) { + this.filterMode = filterMode; setBackground("menubg.png"); xSize = 220; ySize = 216; @@ -72,8 +86,12 @@ public class SubGuiAbilitySelect extends SubGuiInterface implements ICustomScrol private List getFilteredList() { HashMap merged = new HashMap<>(); - merged.putAll(customData); - merged.putAll(builtInData); + if (filterMode != FILTER_BUILTIN_ONLY) { + merged.putAll(customData); + } + if (filterMode != FILTER_CUSTOM_ONLY) { + merged.putAll(builtInData); + } if (search.isEmpty()) { return new ArrayList<>(merged.keySet()); 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 99d1fff54..b0c03a811 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -1,6 +1,7 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import noppes.npcs.client.gui.util.GuiCustomScroll; @@ -11,6 +12,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -20,6 +22,11 @@ import java.util.Map; */ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + private static final int BTN_ADD = 0; + private static final int BTN_CANCEL = 1; + private static final int BTN_SCROLL_TYPE = 2; + private static final int TF_SEARCH = 10; + private GuiCustomScroll scroll; private final HashMap displayNameToTypeId = new HashMap<>(); private final HashMap allDisplayNameToTypeId = new HashMap<>(); @@ -36,62 +43,135 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS public void initGui() { super.initGui(); - addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); + int y = guiTop + 5; + // Scroll type filter button + addButton(new GuiNpcButton(BTN_SCROLL_TYPE, guiLeft + 5, y, 190, 20, GuiNPCAbilities.scrollType.toString())); + y += 24; + + // Search bar + addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 5, y, 190, 18, search)); + y += 20; + + // Scroll list (shortened to fit filter button within original ySize) if (scroll == null) { scroll = new GuiCustomScroll(this, 0); - scroll.setSize(190, 145); + scroll.setSize(190, 121); } scroll.guiLeft = guiLeft + 5; - scroll.guiTop = guiTop + 26; + scroll.guiTop = y; addScroll(scroll); buildAllTypes(); - scroll.setList(getFilteredTypeList()); + scroll.setUnsortedList(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")); + addButton(new GuiNpcButton(BTN_ADD, guiLeft + 5, guiTop + 188, 90, 20, "gui.add")); + getButton(BTN_ADD).setEnabled(scroll.hasSelected()); + addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); } private void buildAllTypes() { allDisplayNameToTypeId.clear(); String[] types = AbilityController.Instance.getTypes(); for (String typeId : types) { + // Never show built-in types — they are immutable and cannot be created + if (AbilityController.Instance.isBuiltInType(typeId)) + continue; + + // Apply scroll type filter + if (!matchesScrollType(typeId)) + continue; + String displayName = I18n.format(typeId); + if (AbilityController.Instance.isConcurrentCapableType(typeId)) { + displayName = "\u00A7e" + displayName; + } allDisplayNameToTypeId.put(displayName, typeId); } } + private boolean matchesScrollType(String typeId) { + GuiNPCAbilities.ScrollType type = GuiNPCAbilities.scrollType; + if (type == GuiNPCAbilities.ScrollType.ALL) { + return true; + } else if (type == GuiNPCAbilities.ScrollType.CNPC) { + return typeId.startsWith("ability.cnpc."); + } else if (type == GuiNPCAbilities.ScrollType.MODDED) { + if (!Register.isEmpty("ability")) { + List registerList = Register.REGISTERED_NAMESPACES.get("ability"); + if (!registerList.isEmpty()) { + String namespace = registerList.get(GuiNPCAbilities.modIndex); + return typeId.startsWith("ability." + namespace + "."); + } + } + return false; + } + return true; + } + 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)) { + String stripped = displayName.replaceAll("\u00A7.", ""); + if (search.isEmpty() || stripped.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) { list.add(displayName); displayNameToTypeId.put(displayName, entry.getValue()); } } + Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare( + a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", ""))); return list; } @Override public void buttonEvent(GuiButton guibutton) { - if (guibutton.id == 0 && scroll.hasSelected()) { + int id = guibutton.id; + + if (id == BTN_ADD && scroll.hasSelected()) { String displayName = scroll.getSelected(); selectedTypeId = displayNameToTypeId.get(displayName); close(); - } else if (guibutton.id == 1) { + } else if (id == BTN_CANCEL) { selectedTypeId = null; close(); + } else if (id == BTN_SCROLL_TYPE) { + cycleScrollType(); + if (scroll != null) { + scroll.resetScroll(); + } + initGui(); + } + } + + private void cycleScrollType() { + if (GuiNPCAbilities.scrollType != GuiNPCAbilities.ScrollType.MODDED) { + GuiNPCAbilities.ScrollType[] values = GuiNPCAbilities.ScrollType.values(); + GuiNPCAbilities.ScrollType next = values[(GuiNPCAbilities.scrollType.ordinal() + 1) % values.length]; + if (next == GuiNPCAbilities.ScrollType.MODDED && Register.isEmpty("ability")) { + next = GuiNPCAbilities.ScrollType.ALL; + } + GuiNPCAbilities.scrollType = next; + } else { + List list = Register.REGISTERED_NAMESPACES.get("ability"); + if (list != null && !list.isEmpty()) { + if (GuiNPCAbilities.modIndex == list.size() - 1) { + GuiNPCAbilities.scrollType = GuiNPCAbilities.ScrollType.ALL; + } else { + GuiNPCAbilities.modIndex = (GuiNPCAbilities.modIndex + 1) % list.size(); + } + } else { + GuiNPCAbilities.modIndex = 0; + GuiNPCAbilities.scrollType = GuiNPCAbilities.ScrollType.ALL; + } } } @Override public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { if (guiCustomScroll.id == 0) { - getButton(0).setEnabled(scroll.hasSelected()); + getButton(BTN_ADD).setEnabled(scroll.hasSelected()); } } @@ -106,9 +186,9 @@ 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(); + if (getTextField(TF_SEARCH) != null && getTextField(TF_SEARCH).isFocused()) { + if (!search.equals(getTextField(TF_SEARCH).getText())) { + search = getTextField(TF_SEARCH).getText().toLowerCase(); scroll.setList(getFilteredTypeList()); scroll.resetScroll(); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index ba3bfb955..da71dec70 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -144,7 +144,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText // Computed "Valid For" label (derived from child abilities) fieldDefs.add(FieldDef.labelField("ability.validFor", () -> { UserType ut = computeAllowedBy(); - return StatCollector.translateToLocal("ability.validFor") + ": \u00A7e" + StatCollector.translateToLocal("ability.userType." + ut.name()); + return "\u00A7e" + StatCollector.translateToLocal("ability.userType." + ut.name()); }).tab("General")); fieldDefs.add(FieldDef.boolField("gui.enabled", chain::isEnabled, chain::setEnabled).tab("General")); fieldDefs.add(FieldDef.intField("ability.weight", chain::getWeight, chain::setWeight).range(1, 100).tab("General")); @@ -325,12 +325,22 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText sw.addButton(entryBtn); if (!readOnlyEntries) { + // Check if this entry is concurrent-active (delay disabled) + Ability resolvedAbility = entry.resolve(); + boolean isConcurrentActive = resolvedAbility != null + && resolvedAbility.isConcurrentCapable() + && entry.isConcurrentEnabled(); + // Delay label + field - sw.addLabel(new GuiNpcLabel(labelCounter++, "ability.delay", L_LABEL_X + 160, y + 5, 0xAAAAAA)); + sw.addLabel(new GuiNpcLabel(labelCounter++, "ability.delay", L_LABEL_X + 160, y + 5, + isConcurrentActive ? 0x555555 : 0xAAAAAA)); GuiNpcTextField delayField = new GuiNpcTextField(ENTRY_BASE + i * ENTRY_STRIDE + 1, this, fontRendererObj, L_LABEL_X + 195, y, 40, 20, String.valueOf(entry.getDelayTicks())); delayField.setIntegersOnly(); delayField.setMinMaxDefault(0, 6000, 0); + if (isConcurrentActive) { + delayField.setEnabled(false); + } sw.addTextField(delayField); // Up button @@ -343,8 +353,16 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 3, L_LABEL_X + 263, y, 20, 20, "\u2193")); } + // Concurrent toggle (only shown if resolved ability is concurrent-capable, never for first entry) + if (i > 0 && resolvedAbility != null && resolvedAbility.isConcurrentCapable()) { + String cLabel = entry.isConcurrentEnabled() ? "\u00A7aC" : "\u00A77C"; + GuiNpcButton cBtn = new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 5, L_LABEL_X + 288, y, 20, 20, cLabel); + cBtn.setHoverText("ability.hover.concurrent"); + sw.addButton(cBtn); + } + // Delete button - sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 4, L_LABEL_X + 288, y, 20, 20, "X")); + sw.addButton(new GuiNpcButton(ENTRY_BASE + i * ENTRY_STRIDE + 4, L_LABEL_X + 313, y, 20, 20, "X")); } else { // Read-only: show delay as label only int delay = entry.getDelayTicks(); @@ -538,17 +556,26 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText case 0: // Entry name button — reference: clone/modify dialog; inline: edit config ChainedAbilityEntry clickedEntry = entries.get(entryIndex); if (clickedEntry.isReference()) { + // Built-in abilities are always references — no editing allowed + Ability refResolved = clickedEntry.resolve(); + if (refResolved != null && refResolved.isBuiltIn()) return true; editingEntryIndex = entryIndex; setSubGui(new SubGuiAbilityEditMode()); } else if (clickedEntry.isInline() && clickedEntry.getInlineAbility() != null) { + Ability inlineAbility = clickedEntry.getInlineAbility(); + if (inlineAbility.isBuiltIn()) return true; editingEntryIndex = entryIndex; - setSubGui(new SubGuiAbilityConfig(clickedEntry.getInlineAbility(), this)); + setSubGui(new SubGuiAbilityConfig(inlineAbility, this)); } return true; case 2: // Up if (entryIndex > 0) { ChainedAbilityEntry entry = entries.remove(entryIndex); entries.add(entryIndex - 1, entry); + // Can't be concurrent at position 0 + if (entryIndex - 1 == 0) { + entry.setConcurrentEnabled(false); + } initGui(); } return true; @@ -563,6 +590,15 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText entries.remove(entryIndex); initGui(); return true; + case 5: // Concurrent toggle + ChainedAbilityEntry toggleEntry = entries.get(entryIndex); + boolean newState = !toggleEntry.isConcurrentEnabled(); + toggleEntry.setConcurrentEnabled(newState); + if (newState) { + toggleEntry.setDelayTicks(0); + } + initGui(); + return true; } } @@ -695,9 +731,11 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText if (source == SubGuiChainedEntrySource.SOURCE_NPC_SLOTS) { setSubGui(new SubGuiNpcSlotPicker(npcSlots)); } else if (source == SubGuiChainedEntrySource.SOURCE_LOAD_PRESET) { - setSubGui(new SubGuiAbilitySelect()); + setSubGui(new SubGuiAbilitySelect(SubGuiAbilitySelect.FILTER_CUSTOM_ONLY)); } else if (source == SubGuiChainedEntrySource.SOURCE_CREATE_NEW) { setSubGui(new SubGuiAbilityTypeSelect()); + } else if (source == SubGuiChainedEntrySource.SOURCE_BUILT_IN) { + setSubGui(new SubGuiAbilitySelect(SubGuiAbilitySelect.FILTER_BUILTIN_ONLY)); } // Don't initGui — we're opening another SubGui } @@ -728,7 +766,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText return; } Ability newAbility = AbilityController.Instance.create(typeId); - if (newAbility != null) { + if (newAbility != null && !newAbility.isBuiltIn()) { if (variants.size() == 1) { variants.get(0).apply(newAbility); } @@ -744,7 +782,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText int idx = gui.getSelectedIndex(); if (idx >= 0 && pendingTypeId != null) { Ability newAbility = AbilityController.Instance.create(pendingTypeId); - if (newAbility != null) { + if (newAbility != null && !newAbility.isBuiltIn()) { gui.getVariants().get(idx).apply(newAbility); newAbility.setId(java.util.UUID.randomUUID().toString()); entries.add(ChainedAbilityEntry.inline(newAbility, 0)); @@ -766,10 +804,17 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText ChainedAbilityEntry entry = entries.get(editingEntryIndex); + // Block all editing for built-in abilities + Ability preCheck = entry.resolve(); + if (preCheck != null && preCheck.isBuiltIn()) { + editingEntryIndex = -1; + return; + } + if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) { if (entry.convertToInline()) { Ability a = entry.getInlineAbility(); - if (a != null) { + if (a != null && !a.isBuiltIn()) { a.setId(java.util.UUID.randomUUID().toString()); setSubGui(new SubGuiAbilityConfig(a, this)); return; @@ -778,7 +823,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText editingEntryIndex = -1; } else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) { Ability resolved = entry.resolve(); - if (resolved != null) { + if (resolved != null && !resolved.isBuiltIn()) { editingParentAbility = true; setSubGui(resolved.createConfigGui(this)); return; diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java index 2c544a937..b40753410 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedEntrySource.java @@ -6,7 +6,7 @@ import noppes.npcs.client.gui.util.GuiNpcLabel; /** * Choice dialog for adding an entry to a chain. - * Options: From NPC Slots (optional), Load Preset, Create New. + * Options: By Reference, Create New, Built-in, From NPC Slots (optional). */ public class SubGuiChainedEntrySource extends SubGuiSimpleChoice { @@ -14,6 +14,7 @@ public class SubGuiChainedEntrySource extends SubGuiSimpleChoice { public static final int SOURCE_NPC_SLOTS = 0; public static final int SOURCE_LOAD_PRESET = 1; public static final int SOURCE_CREATE_NEW = 2; + public static final int SOURCE_BUILT_IN = 3; private final boolean showNpcOption; @@ -25,7 +26,7 @@ public class SubGuiChainedEntrySource extends SubGuiSimpleChoice { this.showNpcOption = showNpcOption; setBackground("menubg.png"); xSize = 200; - ySize = showNpcOption ? 110 : 88; + ySize = showNpcOption ? 132 : 110; } @Override @@ -36,21 +37,24 @@ public class SubGuiChainedEntrySource extends SubGuiSimpleChoice { addLabel(new GuiNpcLabel(0, "ability.entrySource", guiLeft + 10, y)); y += 20; - if (showNpcOption) { - addButton(new GuiNpcButton(0, guiLeft + 10, y, 180, 20, "ability.fromNpc")); - y += 22; - } - - addButton(new GuiNpcButton(1, guiLeft + 10, y, 180, 20, "ability.byReference")); + addButton(new GuiNpcButton(SOURCE_LOAD_PRESET, guiLeft + 10, y, 180, 20, "ability.byReference")); y += 22; - addButton(new GuiNpcButton(2, guiLeft + 10, y, 180, 20, "ability.createNew")); + addButton(new GuiNpcButton(SOURCE_CREATE_NEW, guiLeft + 10, y, 180, 20, "ability.createNew")); + + y += 22; + addButton(new GuiNpcButton(SOURCE_BUILT_IN, guiLeft + 10, y, 180, 20, "gui.builtin")); + + if (showNpcOption) { + y += 22; + addButton(new GuiNpcButton(SOURCE_NPC_SLOTS, guiLeft + 10, y, 180, 20, "ability.fromNpc")); + } } @Override public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - if (id >= 0 && id <= 2) { + if (id >= 0 && id <= 3) { setResult(id); close(); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java new file mode 100644 index 000000000..411d03351 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiCustomEffectSelect.java @@ -0,0 +1,220 @@ +package noppes.npcs.client.gui.advanced; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * SubGui for selecting a custom effect from CustomEffectController. + * Supports switching between effect maps (index 0 = custom, addon indices via toggle button). + */ +@SideOnly(Side.CLIENT) +public class SubGuiCustomEffectSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + + private GuiCustomScroll scroll; + private final HashMap displayNameToId = new HashMap<>(); + private final HashMap allDisplayNameToId = new HashMap<>(); + private int selectedEffectId = -1; + private int selectedIndex = 0; + private String search = ""; + private final int preselectedId; + private final int preselectedIndex; + + /** The effect map index currently being viewed */ + private int viewIndex = 0; + + /** Ordered list of available indices for toggling */ + private List availableIndices; + + public SubGuiCustomEffectSelect(int preselectedId) { + this(preselectedId, 0); + } + + public SubGuiCustomEffectSelect(int preselectedId, int preselectedIndex) { + this.preselectedId = preselectedId; + this.preselectedIndex = preselectedIndex; + this.viewIndex = preselectedIndex; + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + buildAvailableIndices(); + + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); + + // Toggle button for switching between effect lists (only if addon indices exist) + if (availableIndices.size() > 1) { + String label = getViewLabel(); + addButton(new GuiNpcButton(2, guiLeft + 5, guiTop + 26, 190, 20, label)); + } + + int scrollTop = availableIndices.size() > 1 ? guiTop + 49 : guiTop + 26; + int scrollHeight = availableIndices.size() > 1 ? 122 : 145; + + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + } + scroll.setSize(190, scrollHeight); + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = scrollTop; + addScroll(scroll); + + buildAllEffects(); + List filtered = getFilteredList(); + scroll.setUnsortedList(filtered); + + // Pre-select current effect (only if viewing the same index) + if (preselectedId >= 0 && viewIndex == preselectedIndex && !scroll.hasSelected()) { + for (String name : filtered) { + Integer id = displayNameToId.get(name); + if (id != null && id == preselectedId) { + scroll.setSelected(name); + break; + } + } + } + + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); + getButton(0).setEnabled(scroll.hasSelected()); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + private void buildAvailableIndices() { + availableIndices = new ArrayList<>(); + CustomEffectController controller = CustomEffectController.getInstance(); + + // Always include index 0 + availableIndices.add(0); + + // Add any addon indices that have registered labels + HashMap labels = controller.getIndexLabels(); + for (int idx : labels.keySet()) { + if (idx != 0 && controller.getEffectMap(idx) != null) { + availableIndices.add(idx); + } + } + Collections.sort(availableIndices); + + // Ensure viewIndex is valid + if (!availableIndices.contains(viewIndex)) { + viewIndex = 0; + } + } + + private String getViewLabel() { + if (viewIndex == 0) { + return "Custom Effects"; + } + HashMap labels = CustomEffectController.getInstance().getIndexLabels(); + String label = labels.get(viewIndex); + return label != null ? label : "Index " + viewIndex; + } + + private void buildAllEffects() { + allDisplayNameToId.clear(); + HashMap effects = CustomEffectController.getInstance().getEffectMap(viewIndex); + if (effects == null) return; + for (CustomEffect ce : effects.values()) { + if (ce.getName() != null && !ce.getName().isEmpty()) { + allDisplayNameToId.put(ce.getName(), ce.id); + } + } + } + + private List getFilteredList() { + List list = new ArrayList<>(); + displayNameToId.clear(); + for (Map.Entry entry : allDisplayNameToId.entrySet()) { + String name = entry.getKey(); + if (search.isEmpty() || name.toLowerCase().contains(search)) { + list.add(name); + displayNameToId.put(name, entry.getValue()); + } + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0 && scroll.hasSelected()) { + String name = scroll.getSelected(); + Integer id = displayNameToId.get(name); + selectedEffectId = id != null ? id : -1; + selectedIndex = viewIndex; + close(); + } else if (guibutton.id == 1) { + selectedEffectId = -1; + close(); + } else if (guibutton.id == 2) { + // Toggle to next available index + int currentPos = availableIndices.indexOf(viewIndex); + int nextPos = (currentPos + 1) % availableIndices.size(); + viewIndex = availableIndices.get(nextPos); + search = ""; + scroll = null; + initGui(); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0) { + getButton(0).setEnabled(scroll.hasSelected()); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && selection != null) { + Integer id = displayNameToId.get(selection); + selectedEffectId = id != null ? id : -1; + selectedIndex = viewIndex; + close(); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + String newSearch = getTextField(10).getText().toLowerCase(); + if (!search.equals(newSearch)) { + search = newSearch; + scroll.setUnsortedList(getFilteredList()); + scroll.resetScroll(); + } + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + } + + public int getSelectedEffectId() { + return selectedEffectId; + } + + public int getSelectedIndex() { + return selectedIndex; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldType.java b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java index 052e2f4cd..c00ff1855 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldType.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java @@ -15,5 +15,7 @@ public enum FieldType { SECTION_HEADER, LABEL, EFFECTS_LIST, + CUSTOM_EFFECTS_LIST, + EFFECT_ACTIONS_LIST, ROW } 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 63e78dd11..f6562e7a5 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -497,7 +497,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private void handleChainConfigClosed() { if (pendingSaveChain != null) { PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT())); - PacketClient.sendClient(new ChainedAbilitiesGetPacket()); selected = pendingSaveChain.getName(); pendingSaveChain = null; } @@ -570,7 +569,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface return true; } else { PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); - PacketClient.sendClient(new CustomAbilitiesGetPacket()); pendingSaveAbility = null; } } else if (pendingSaveAbility != null) { @@ -597,12 +595,12 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface return true; } PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); - PacketClient.sendClient(new CustomAbilitiesGetPacket()); pendingSaveAbility = null; return false; } private void openConfig(Ability ability) { + if (ability.isBuiltIn()) return; // Built-in abilities are immutable selectedAbility = ability; selected = ability.getName(); previewExecutor.stop(); 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 e6e02d10e..ffe6718ee 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java @@ -22,15 +22,15 @@ public class GuiNpcTextField extends GuiTextField { private ITextfieldListener listener; public int id; public int min = 0, max = Integer.MAX_VALUE, def = 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; + public double minDouble = 0, maxDouble = Double.MAX_VALUE, defDouble = 0; + public float minFloat = 0, maxFloat = Float.MAX_VALUE, defFloat = 0; protected static GuiNpcTextField activeTextfield = null; public boolean canEdit = true; public String hoverableText = ""; private boolean wasHovered = false; private int hoverCount = 0; - private final int[] allowedSpecialChars = {14, 211, 203, 205}; + private final int[] allowedSpecialChars = {14, 211, 203, 205, 199, 207}; public GuiNpcTextField(int id, GuiScreen parent, FontRenderer fontRenderer, int i, int j, int k, int l, String s) { super(fontRenderer, i, j, k, l); @@ -69,11 +69,35 @@ public class GuiNpcTextField extends GuiTextField { @Override public boolean textboxKeyTyped(char c, int i) { - if (!charAllowed(c, i) || !canEdit) + if (!canEdit || !isFocused()) + return false; + // Allow Ctrl shortcuts (select all, copy, paste, cut) to bypass char filter + if (GuiScreen.isCtrlKeyDown()) { + // For Ctrl+V (paste) on numeric fields, filter clipboard to valid chars + if (i == 47 && isNumericField()) { + String clipboard = GuiScreen.getClipboardString(); + if (clipboard != null) { + StringBuilder filtered = new StringBuilder(); + for (char ch : clipboard.toCharArray()) { + if (Character.isDigit(ch) || ch == '-' || ((doublesOnly || floatsOnly) && ch == '.')) + filtered.append(ch); + } + if (filtered.length() > 0) + writeText(filtered.toString()); + } + return true; + } + return super.textboxKeyTyped(c, i); + } + if (!charAllowed(c, i)) return false; return super.textboxKeyTyped(c, i); } + private boolean isNumericField() { + return integersOnly || doublesOnly || floatsOnly; + } + public boolean isEmpty() { return getText().trim().length() == 0; } diff --git a/src/main/java/noppes/npcs/controllers/CustomEffectController.java b/src/main/java/noppes/npcs/controllers/CustomEffectController.java index d1036dc70..c5a1f9948 100644 --- a/src/main/java/noppes/npcs/controllers/CustomEffectController.java +++ b/src/main/java/noppes/npcs/controllers/CustomEffectController.java @@ -37,6 +37,7 @@ public class CustomEffectController implements ICustomEffectHandler { public static CustomEffectController Instance = new CustomEffectController(); public HashMap> indexMapper = new HashMap<>(); + private HashMap indexLabels = new HashMap<>(); public HashMap customEffectsSync = new HashMap<>(); @@ -59,6 +60,14 @@ public class CustomEffectController implements ICustomEffectHandler { indexMapper.put(index, (HashMap) effectHashMap); } + public void registerEffectMapLabel(int index, String label) { + indexLabels.put(index, label); + } + + public HashMap getIndexLabels() { + return indexLabels; + } + public HashMap getCustomEffects() { return indexMapper.get(0); } @@ -354,10 +363,7 @@ public class CustomEffectController implements ICustomEffectHandler { } public HashMap getEffectMap(int index) { - if (indexMapper.containsKey(index)) { - return getEffectMap(index); - } - return null; + return indexMapper.get(index); } private File getDir() { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index f06c21686..d2afe1c64 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -607,17 +607,25 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } // ═══════════════════════════════════════════════════════════════════ - // DIMENSION CHANGE RESET + // ENTITY RECONSTRUCTION RESET // ═══════════════════════════════════════════════════════════════════ /** - * Fully reset ability state when changing dimensions. - * Unlike interruptCurrentAbility(), this does NOT roll any cooldowns - * and ensures the player can immediately use abilities in the new dimension. - * Also re-syncs to client since the entity may be re-created. + * Handle entity reconstruction events (dimension change, death/respawn, etc.). + * Cleans up any executing ability state without firing script events (those were + * already fired on the original entity), clears transient runtime state, and + * re-syncs ability data to the client on the new entity. + *

+ * This should be called whenever the player's entity object is recreated by Forge, + * since the client-side entity loses all synced ability state. + * + * @param clearCooldowns true to fully reset cooldowns (dimension change), + * false to preserve cooldowns (death/respawn — interrupt already rolled them) + * @param clearToggles true to clear active toggles (death/respawn), + * false to keep them (dimension change) */ - public void resetOnDimensionChange() { - // Clean up any executing ability without rolling cooldowns + public void onEntityReconstructed(boolean clearCooldowns, boolean clearToggles) { + // Clean up any executing ability silently (no script events — already fired on old entity) if (currentAbility != null && currentAbility.isExecuting()) { removeTelegraph(currentAbility); currentAbility.cleanup(); @@ -627,30 +635,57 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA releaseLockedPosition(); } - // Clear chain state + // Clear chain and concurrent state currentChain = null; chainEntryIndex = -1; chainDelayRemaining = -1; + interruptConcurrentSlots(); // Clear all transient state currentAbility = null; currentAbilityKey = null; currentTarget = null; - // Reset cooldowns completely - cooldownEndTime = 0; + if (clearCooldowns) { + cooldownEndTime = 0; + } interruptCooldownRolled = false; - // Sync cleared state to client - EntityPlayer player = playerData.player; - if (player != null) { - syncAbilityStateClear(player); + if (clearToggles) { + clearActiveToggles(); } - // Re-sync ability data (unlocked list, selection) to client + // Force-send cleared lock state to client. We must always send this + // (not gated by lastSyncedFlags != 0) because the NEW entity's client + // may have stale lock state from before the reconstruction. + lastSyncedFlags = 0; + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0); + } + + // Re-sync full ability data (unlocked list, selection, toggles) to client syncToClient(); } + /** + * Fully reset ability state when changing dimensions. + * Clears cooldowns so the player can immediately use abilities in the new dimension. + * Keeps active toggles (dimension change shouldn't reset ongoing effects). + */ + public void resetOnDimensionChange() { + onEntityReconstructed(true, false); + } + + /** + * Reset ability state after death/respawn. + * Preserves cooldowns (interrupt on death already rolled them) but clears + * active toggles (death should end ongoing effects). + */ + public void resetOnRespawn() { + onEntityReconstructed(false, true); + } + // ═══════════════════════════════════════════════════════════════════ // DAMAGE HANDLING // ═══════════════════════════════════════════════════════════════════ @@ -764,23 +799,12 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA private void applyPositionLock(EntityPlayer player) { if (!positionLocked) return; - boolean flying = AbilityController.Instance != null - && AbilityController.Instance.isPlayerFlying(player); - - if (flying) { - // Flying players: lock X/Z only, preserve Y freedom - player.setPosition(lockedPosX, player.posY, lockedPosZ); - player.prevPosX = lockedPosX; - player.prevPosZ = lockedPosZ; - } else { - // Grounded players: full position lock including Y - player.setPosition(lockedPosX, lockedPosY, lockedPosZ); - player.prevPosX = lockedPosX; - player.prevPosY = lockedPosY; - player.prevPosZ = lockedPosZ; - player.motionY = 0; - } + player.setPosition(lockedPosX, lockedPosY, lockedPosZ); + player.prevPosX = lockedPosX; + player.prevPosY = lockedPosY; + player.prevPosZ = lockedPosZ; player.motionX = 0; + player.motionY = 0; player.motionZ = 0; } @@ -807,6 +831,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA if (positionLocked) { flags |= PlayerAbilityStatePacket.FLAG_POSITION_LOCKED; } + if (wasFlyingAtLock) { + flags |= PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK; + } return flags; } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 6574f71bc..b963e5d34 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -1650,7 +1650,7 @@ ability.cnpc.teleport=Teleport ability.cnpc.vortex=Vortex ability.cnpc.shockwave=Shockwave ability.cnpc.guard=Guard -ability.cnpc.heal=Heal +ability.cnpc.effect=Effect ability.cnpc.hazard=Hazard ability.cnpc.trap=Trap ability.cnpc.disc=Disc @@ -1843,13 +1843,25 @@ ability.pushStrength=Push Strength ability.damageReduction=Damage Reduction ability.counterWindow=Counter Ticks -# Heal -ability.instantHeal=Instant Heal +# Effect +ability.instantHeal=Instant ability.healAmount=Heal Amount ability.healPercent=Heal Percent -ability.healRadius=Heal Radius -ability.healSelf=Heal Self -ability.healAllies=Heal Allies +ability.targetFilter=Target Filter +ability.targetFilter.allies=Allies +ability.targetFilter.enemies=Enemies +ability.targetFilter.all=All +ability.includeSelf=Include Self +ability.section.targeting=Targeting +ability.concurrent=Concurrent +ability.concurrentInfo=This ability allows Concurrency in Chains +ability.hover.concurrent=When enabled, this ability fires at the same time as the ability above it in the chain +ability.customEffects=Custom Effects +ability.effectActions=Effect Actions +ability.noCustomEffects=No custom effects defined +ability.variant.selfHeal=Self Heal +ability.variant.healingAura=Healing Aura +ability.variant.poisonDebuff=Poison Debuff # Hazard ability.shape=Shape