diff --git a/src/api b/src/api index a27e11595..a9c77d20e 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit a27e1159508c799c1b7b612ee09574f207bd64e0 +Subproject commit a9c77d20eb83be6a3168480c0d62fa78419e9469 diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java similarity index 92% rename from src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java index 871d48461..beebe98f3 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityDome; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; @@ -13,11 +13,11 @@ import org.lwjgl.opengl.GL11; * Optional skybox texture rendered on the interior surface. */ @SideOnly(Side.CLIENT) -public class RenderEnergyDome extends RenderEnergyBarrier { +public class RenderAbilityDome extends RenderEnergyBarrier { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { - EntityEnergyDome dome = (EntityEnergyDome) entity; + EntityAbilityDome dome = (EntityAbilityDome) entity; float radius = dome.getDomeRadius(); float healthPercent = dome.getHealthPercent(); @@ -34,7 +34,7 @@ public class RenderEnergyDome extends RenderEnergyBarrier { // Hit flash effect float flashAlpha = computeFlashAlpha(dome); - float innerScale = 0.95f; + float innerScale = 1.0f; // Render outer dome (translucent glow) if (dome.isOuterColorEnabled()) { @@ -51,7 +51,7 @@ public class RenderEnergyDome extends RenderEnergyBarrier { GL11.glDepthMask(true); // Render inner dome (depth write enabled so inner sphere properly occludes) - renderSphere(dome.getInnerColor(), dome.getInnerAlpha(), radius * innerScale, 8); + renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8); GL11.glPopMatrix(); restoreRenderState(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java similarity index 85% rename from src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java index 279c6902d..1261aaf1e 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; @@ -13,17 +13,25 @@ import org.lwjgl.opengl.GL11; * Voxel-blocky style with inner/outer layers. */ @SideOnly(Side.CLIENT) -public class RenderEnergyPanel extends RenderEnergyBarrier { +public class RenderAbilityPanel extends RenderEnergyBarrier { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { - EntityEnergyPanel panel = (EntityEnergyPanel) entity; + EntityAbilityPanel panel = (EntityAbilityPanel) entity; float width = panel.getPanelData().panelWidth; float height = panel.getPanelData().panelHeight; - float panelYaw = panel.getPanelYaw(); float healthPercent = panel.getHealthPercent(); + // Interpolate panel yaw for smooth rotation between ticks + float prevYaw = panel.getPrevPanelYaw(); + float currentYaw = panel.getPanelYaw(); + float yawDelta = currentYaw - prevYaw; + // Wrap angle delta to -180..180 for shortest rotation path + while (yawDelta > 180.0f) yawDelta -= 360.0f; + while (yawDelta < -180.0f) yawDelta += 360.0f; + float renderYaw = prevYaw + yawDelta * partialTicks; + setupRenderState(); GL11.glPushMatrix(); @@ -34,8 +42,8 @@ public class RenderEnergyPanel extends RenderEnergyBarrier { renderAttachedLightning(panel, 0.9f, Math.max(width, height) * 0.5f); } - // Rotate panel to face the correct direction - GL11.glRotatef(-panelYaw, 0.0f, 1.0f, 0.0f); + // Rotate panel to face the correct direction (interpolated) + GL11.glRotatef(-renderYaw, 0.0f, 1.0f, 0.0f); // Hit flash float flashAlpha = computeFlashAlpha(panel); @@ -48,7 +56,7 @@ public class RenderEnergyPanel extends RenderEnergyBarrier { GL11.glPushMatrix(); GL11.glScalef(scale, scale, scale); - float innerScale = 0.9f; + float innerScale = 1.0f; float panelThickness = 0.1f; // Render outer panel (translucent glow) diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java index b72be7a7c..fc7bc33c7 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java @@ -25,6 +25,7 @@ public class RenderAbilitySweeper extends Render { float beamLength = sweeper.getBeamLength(); float beamWidth = sweeper.getBeamWidth(); + float beamHeight = sweeper.getBeamHeight(); int innerColor = sweeper.getInnerColor(); int outerColor = sweeper.getOuterColor(); boolean outerColorEnabled = sweeper.isOuterColorEnabled(); @@ -38,7 +39,7 @@ public class RenderAbilitySweeper extends Render { GL11.glRotatef(-angle, 0, 1, 0); // Negative for correct direction // Render the beam extending in the +Z direction (like beam trail segments) - renderBeam(beamLength, beamWidth, innerColor, outerColor, outerColorEnabled, outerColorWidth); + renderBeam(beamLength, beamWidth, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth); GL11.glPopMatrix(); @@ -71,8 +72,9 @@ public class RenderAbilitySweeper extends Render { * Render beam using the same style as the Beam entity trail. * Three layers: outer glow, middle, inner core. * outerColorWidth is an additive offset from inner width (consistent with other renderers). + * Width and height control the rectangular cross-section independently. */ - private void renderBeam(float length, float width, int innerColor, int outerColor, + private void renderBeam(float length, float width, float height, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth) { // Extract colors float outerR = ((outerColor >> 16) & 0xFF) / 255.0f; @@ -83,37 +85,40 @@ public class RenderAbilitySweeper extends Render { float innerG = ((innerColor >> 8) & 0xFF) / 255.0f; float innerB = (innerColor & 0xFF) / 255.0f; - // Inner scale defines the core width (consistent with other renderers) + // Inner scale defines the core size (consistent with other renderers) float innerScale = 0.6f; float innerWidth = width * innerScale; + float innerHeight = height * innerScale; // Render from origin (0,0,0) to (0,0,length) in local coords // After rotation this extends in the correct world direction // Outer glow (wider, translucent) - only if enabled - // outerColorWidth is additive offset from inner width + // outerColorWidth is additive offset from inner size if (outerColorEnabled) { float outerWidth = innerWidth + outerColorWidth * width; + float outerHeight = innerHeight + outerColorWidth * height; GL11.glDepthMask(false); - renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerR, outerG, outerB, 0.3f); + renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f); GL11.glDepthMask(true); // Middle layer (halfway between inner and outer) float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f; - renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, outerR, outerG, outerB, 0.6f); + float midHeight = innerHeight + (outerHeight - innerHeight) * 0.5f; + renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, midHeight, outerR, outerG, outerB, 0.6f); } // Inner core (solid) - renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerR, innerG, innerB, 1.0f); + renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f); } /** - * Render a beam segment as a 3D rectangular prism. + * Render a beam segment as a 3D rectangular prism with independent width and height. * Uses the same approach as RenderAbilityBeam.renderBeamRectangle. */ private void renderBeamSegment(double x1, double y1, double z1, double x2, double y2, double z2, - float width, float r, float g, float b, float a) { + float width, float height, float r, float g, float b, float a) { // Calculate direction double dx = x2 - x1; double dy = y2 - y1; @@ -151,39 +156,40 @@ public class RenderAbilitySweeper extends Render { double vertZ = dx * horzY - dy * horzX; float halfWidth = width * 0.5f; + float halfHeight = height * 0.5f; - // Calculate 8 corners of the box - double s1x = x1 - horzX * halfWidth - vertX * halfWidth; - double s1y = y1 - horzY * halfWidth - vertY * halfWidth; - double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth; + // Calculate 8 corners of the box (horz scaled by halfWidth, vert scaled by halfHeight) + double s1x = x1 - horzX * halfWidth - vertX * halfHeight; + double s1y = y1 - horzY * halfWidth - vertY * halfHeight; + double s1z = z1 - horzZ * halfWidth - vertZ * halfHeight; - double s2x = x1 + horzX * halfWidth - vertX * halfWidth; - double s2y = y1 + horzY * halfWidth - vertY * halfWidth; - double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth; + double s2x = x1 + horzX * halfWidth - vertX * halfHeight; + double s2y = y1 + horzY * halfWidth - vertY * halfHeight; + double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight; - double s3x = x1 + horzX * halfWidth + vertX * halfWidth; - double s3y = y1 + horzY * halfWidth + vertY * halfWidth; - double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth; + double s3x = x1 + horzX * halfWidth + vertX * halfHeight; + double s3y = y1 + horzY * halfWidth + vertY * halfHeight; + double s3z = z1 + horzZ * halfWidth + vertZ * halfHeight; - double s4x = x1 - horzX * halfWidth + vertX * halfWidth; - double s4y = y1 - horzY * halfWidth + vertY * halfWidth; - double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth; + double s4x = x1 - horzX * halfWidth + vertX * halfHeight; + double s4y = y1 - horzY * halfWidth + vertY * halfHeight; + double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight; - double e1x = x2 - horzX * halfWidth - vertX * halfWidth; - double e1y = y2 - horzY * halfWidth - vertY * halfWidth; - double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth; + double e1x = x2 - horzX * halfWidth - vertX * halfHeight; + double e1y = y2 - horzY * halfWidth - vertY * halfHeight; + double e1z = z2 - horzZ * halfWidth - vertZ * halfHeight; - double e2x = x2 + horzX * halfWidth - vertX * halfWidth; - double e2y = y2 + horzY * halfWidth - vertY * halfWidth; - double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth; + double e2x = x2 + horzX * halfWidth - vertX * halfHeight; + double e2y = y2 + horzY * halfWidth - vertY * halfHeight; + double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight; - double e3x = x2 + horzX * halfWidth + vertX * halfWidth; - double e3y = y2 + horzY * halfWidth + vertY * halfWidth; - double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth; + double e3x = x2 + horzX * halfWidth + vertX * halfHeight; + double e3y = y2 + horzY * halfWidth + vertY * halfHeight; + double e3z = z2 + horzZ * halfWidth + vertZ * halfHeight; - double e4x = x2 - horzX * halfWidth + vertX * halfWidth; - double e4y = y2 - horzY * halfWidth + vertY * halfWidth; - double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth; + double e4x = x2 - horzX * halfWidth + vertX * halfHeight; + double e4y = y2 - horzY * halfWidth + vertY * halfHeight; + double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight; Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java index 6f4e1e89f..676440035 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityAbilityBarrier; /** * Intermediate renderer base for energy barrier entities (Dome, Panel). @@ -15,7 +15,7 @@ public abstract class RenderEnergyBarrier extends RenderEnergyAbility { * Compute the alpha boost from a hit flash effect. * Flash value decays from 4 to 0, producing alpha from 0.3 to 0. */ - protected float computeFlashAlpha(EntityEnergyBarrier barrier) { + protected float computeFlashAlpha(EntityAbilityBarrier barrier) { byte flash = barrier.getHitFlash(); if (flash <= 0) return 0.0f; return flash / 4.0f * 0.3f; diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index 87b4c235f..55baf60e6 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -1,15 +1,12 @@ package kamkeel.npcs.controllers; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AbilityPhase; -import kamkeel.npcs.controllers.data.ability.AbilityVariant; -import kamkeel.npcs.controllers.data.ability.ChainedAbility; -import kamkeel.npcs.controllers.data.ability.IAbilityAction; -import kamkeel.npcs.controllers.data.ability.IAbilityExtender; -import kamkeel.npcs.controllers.data.ability.IAbilityFieldProvider; -import kamkeel.npcs.controllers.data.ability.IEffectAction; -import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; -import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.*; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionItem; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect; +import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; @@ -43,14 +40,7 @@ import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.util.NBTJsonUtil; import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -70,6 +60,7 @@ public class AbilityController implements IAbilityHandler { private final List fieldProviders = new ArrayList<>(); private final List chainedFieldProviders = new ArrayList<>(); private final List extenders = new ArrayList<>(); + private final Map> conditionTypes = new HashMap<>(); private final List> flightCheckers = new ArrayList<>(); // ── Legacy Migration ───────────────────────────────────────────────────── @@ -90,6 +81,7 @@ public class AbilityController implements IAbilityHandler { public AbilityController() { registerBuiltinTypes(); + registerBuiltinConditionTypes(); } // ═══════════════════════════════════════════════════════════════════════════ @@ -132,19 +124,23 @@ public class AbilityController implements IAbilityHandler { private void registerBuiltinTypes() { registerType("cnpc:slam", AbilitySlam::new); + registerType("cnpc:charge", AbilityCharge::new); + registerType("cnpc:heavy_hit", AbilityHeavyHit::new); registerType("cnpc:cutter", AbilityCutter::new); + // registerType("cnpc:projectile", AbilityProjectile::new); + registerType("cnpc:sweeper", AbilitySweeper::new); - registerType("cnpc:projectile", AbilityProjectile::new); registerType("cnpc:orb", AbilityOrb::new); registerType("cnpc:disc", AbilityDisc::new); registerType("cnpc:laser_shot", AbilityLaserShot::new); registerType("cnpc:beam", AbilityBeam::new); + // registerType("cnpc:slicer", AbilitySlicer::new); - registerType("cnpc:charge", AbilityCharge::new); registerType("cnpc:dash", AbilityDash::new); registerType("cnpc:teleport", AbilityTeleport::new); + registerType("cnpc:vortex", AbilityVortex::new); registerType("cnpc:shockwave", AbilityShockwave::new); @@ -157,7 +153,14 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:dome", AbilityDome::new); registerType("cnpc:wall", AbilityWall::new); registerType("cnpc:shield", AbilityShield::new); - registerType("cnpc:slicer", AbilitySlicer::new); + } + + private void registerBuiltinConditionTypes() { + registerCondition(ConditionHPThreshold::new); + registerCondition(ConditionHitCount::new); + registerCondition(ConditionItem::new); + registerCondition(ConditionQuestCompleted::new); + registerCondition(ConditionHasEffect::new); } // ═══════════════════════════════════════════════════════════════════════════ @@ -890,6 +893,45 @@ public class AbilityController implements IAbilityHandler { return extenders; } + public void registerCondition(Supplier conditionFactory) { + AbilityCondition temp = conditionFactory.get(); + String typeId = temp.getTypeId(); + if (conditionTypes.containsKey(typeId)) { + LogWriter.info("AbilityController: Overwriting Condition type: " + typeId); + } + conditionTypes.put(typeId, conditionFactory); + } + + public Supplier getConditionType(String key) { + return conditionTypes.get(key); + } + + public String[] getConditionTypes() { + return conditionTypes.keySet().toArray(new String[0]); + } + + public List getConditionNamespaces() { + LinkedHashSet seen = new LinkedHashSet<>(); + for (String typeId : conditionTypes.keySet()) { + String[] parts = typeId.split("\\.", 3); + if (parts.length >= 2) { + seen.add(parts[1]); + } + } + return new ArrayList<>(seen); + } + + public String[] getConditionTypesByNamespace(String namespace) { + String prefix = "condition." + namespace + "."; + List result = new ArrayList<>(); + for (String typeId : conditionTypes.keySet()) { + if (typeId.startsWith(prefix)) { + result.add(typeId); + } + } + return result.toArray(new String[0]); + } + public void registerFlightChecker(Predicate checker) { flightCheckers.add(checker); } @@ -952,6 +994,40 @@ public class AbilityController implements IAbilityHandler { return false; } + /** + * Fire modifyProjectileDamage on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { + float damage = baseDamage; + for (IAbilityExtender ext : extenders) { + damage = ext.modifyProjectileDamage(ability, caster, damage); + } + return damage; + } + + /** + * Fire modifyBarrierHealth on all extenders. Cumulative — each extender's output feeds the next. + */ + public float fireModifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) { + float health = baseHealth; + for (IAbilityExtender ext : extenders) { + health = ext.modifyBarrierHealth(ability, caster, health); + } + return health; + } + + /** + * Fire onAbilityHeal on all extenders. Chain of responsibility — first true wins. + */ + public boolean fireOnAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) { + for (IAbilityExtender ext : extenders) { + if (ext.onAbilityHeal(ability, caster, target, healAmount)) { + return true; + } + } + return false; + } + // ═══════════════════════════════════════════════════════════════════════════ // IAbilityHandler // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 89e059967..9d61188c5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -3,9 +3,13 @@ package kamkeel.npcs.controllers.data.ability; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.telegraph.Telegraph; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -15,7 +19,9 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; +import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; +import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.DataAbilities; import noppes.npcs.NpcDamageSource; @@ -53,7 +59,7 @@ public abstract class Ability implements IAbility, IAbilityAction { // Selection protected int weight = 10; protected boolean enabled = true; - protected List conditions = new ArrayList<>(); + protected List conditions = new ArrayList<>(); // Targeting protected TargetingMode targetingMode = TargetingMode.AGGRO_TARGET; @@ -104,6 +110,14 @@ public abstract class Ability implements IAbility, IAbilityAction { // Cooldown override protected boolean ignoreCooldown = false; + // Per-ability cooldown: if true, this ability has its own independent cooldown + // instead of sharing the global cooldown with other abilities + protected boolean perAbilityCooldown = false; + + // Free on Cast: if true, ability enters cooldown immediately after entities are spawned, + // allowing the caster to use other abilities while summoned entities remain active + protected boolean freeOnCast = false; + // ═══════════════════════════════════════════════════════════════════ // BUILT-IN (set in constructor via configureAsBuiltIn, NOT persisted) // ═══════════════════════════════════════════════════════════════════ @@ -245,6 +259,22 @@ public abstract class Ability implements IAbility, IAbilityAction { return false; } + /** + * Whether this ability type supports the Free on Cast option. + * Override to return true for abilities that spawn persistent entities (projectiles, barriers, zones, sweeper). + */ + public boolean allowFreeOnCast() { + return false; + } + + /** + * Detach all spawned entities (let them live independently) without killing them. + * Called during signalCompletion() when freeOnCast is enabled. + * Override in subclasses to null entity references without calling setDead(). + */ + public void detach() { + } + // ═══════════════════════════════════════════════════════════════════ // TOGGLE CALLBACKS (optional overrides for toggleable abilities) // ═══════════════════════════════════════════════════════════════════ @@ -598,8 +628,14 @@ public abstract class Ability implements IAbility, IAbilityAction { FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) .hover("ability.hover.sync") ).tab("General").visibleWhen(() -> hasWindUpAnimation() && isSyncWindupWithAnimation())); - defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks) - .tab("General").range(0, 10000)); + defs.add(FieldDef.row( + FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks).range(0, 10000), + FieldDef.boolField("ability.perAbilityCooldown", this::isPerAbilityCooldown, this::setPerAbilityCooldown) + ).tab("General")); + if (allowFreeOnCast()) { + defs.add(FieldDef.boolField("ability.freeOnCast", this::isFreeOnCast, this::setFreeOnCast) + .tab("General").hover("ability.hover.freeOnCast")); + } defs.add(FieldDef.section("ability.section.movement").tab("General")); defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), () -> this.getLockMovement().getDisplayKey(), @@ -734,6 +770,25 @@ public abstract class Ability implements IAbility, IAbilityAction { } } + // ── Icon tab (native) ───────────────────────────────────── + if (!isNpcInlineEdit()) { + AbilityIconData icon = AbilityIconData.fromAbility(this); + defs.add(FieldDef.stringField("gui.texture", icon::getTexture, icon::setTexture) + .tab("Icon")); + defs.add(FieldDef.section("ability.icon.section.uv").tab("Icon")); + defs.add(FieldDef.intField("ability.icon.x", icon::getIconX, icon::setIconX) + .tab("Icon").range(0, 4096)); + defs.add(FieldDef.intField("ability.icon.y", icon::getIconY, icon::setIconY) + .tab("Icon").range(0, 4096)); + defs.add(FieldDef.section("gui.size").tab("Icon")); + defs.add(FieldDef.intField("gui.width", icon::getWidth, icon::setWidth) + .tab("Icon").range(1, 256)); + defs.add(FieldDef.intField("gui.height", icon::getHeight, icon::setHeight) + .tab("Icon").range(1, 256)); + defs.add(FieldDef.floatField("gui.scale", icon::getScale, icon::setScale) + .tab("Icon").range(0.1f, 10.0f)); + } + // External field providers (e.g., DBC Addon injecting a "DBC" tab) for (IAbilityFieldProvider provider : AbilityController.Instance.getFieldProviders()) { provider.addFieldDefinitions(this, defs); @@ -832,11 +887,17 @@ public abstract class Ability implements IAbility, IAbilityAction { // AOE_SELF abilities: telegraph follows caster during windup instance.setEntityIdToFollow(caster.getEntityId()); - // For LINE/CONE telegraphs: track target direction during windup + // For LINE/CONE telegraphs: track direction during windup // Only track if rotation is NOT locked during windup (NPC can still turn) - if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { + if (telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) { if (!isRotationLockedDuringWindup()) { - instance.setTargetEntityId(target.getEntityId()); + if (target != null) { + // Face the target entity + instance.setTargetEntityId(target.getEntityId()); + } else { + // No target (AOE_SELF etc.): track caster's own rotationYaw + instance.setTrackFollowedEntityYaw(true); + } } // If rotation is locked, yaw stays fixed at creation time } @@ -1035,7 +1096,12 @@ public abstract class Ability implements IAbility, IAbilityAction { // Final completion - let burst entities die naturally (don't force-kill) burstEntities.clear(); - cleanup(); + if (freeOnCast) { + // Free on Cast: detach entities (let them live independently) instead of killing + detach(); + } else { + cleanup(); + } phase = AbilityPhase.IDLE; currentTick = 0; return true; @@ -1064,6 +1130,20 @@ public abstract class Ability implements IAbility, IAbilityAction { telegraphInstances.clear(); } + /** + * Cancel this ability (voluntary player action). Goes directly to IDLE, skipping DAZED. + * Entities are killed via cleanup(). Unlike interrupt(), this never enters DAZED phase. + */ + public void cancel() { + cleanupBurstEntities(); + cleanup(); + phase = AbilityPhase.IDLE; + currentTick = 0; + burstIndex = 0; + currentTarget = null; + telegraphInstances.clear(); + } + /** * Check if executing */ @@ -1201,7 +1281,8 @@ public abstract class Ability implements IAbility, IAbilityAction { // ═══════════════════════════════════════════════════════════════════ public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsNpc()) continue; if (!c.check(caster, target)) return false; } return true; @@ -1211,7 +1292,8 @@ public abstract class Ability implements IAbility, IAbilityAction { * Check conditions for a player caster, skipping target-requiring conditions. */ public boolean checkConditionsForPlayer(EntityLivingBase caster) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { + if (!c.getUserType().allowsPlayer()) continue; if (c.requiresTarget()) continue; if (!c.check(caster, null)) return false; } @@ -1258,6 +1340,8 @@ public abstract class Ability implements IAbility, IAbilityAction { nbt.setTag("customData", (NBTTagCompound) customData.copy()); nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); + nbt.setBoolean("perAbilityCooldown", perAbilityCooldown); + nbt.setBoolean("freeOnCast", freeOnCast); // Toggle nbt.setInteger("toggleStates", toggleStates); @@ -1279,7 +1363,7 @@ public abstract class Ability implements IAbility, IAbilityAction { // Conditions NBTTagList condList = new NBTTagList(); - for (Condition c : conditions) condList.appendTag(c.writeNBT()); + for (AbilityCondition c : conditions) condList.appendTag(c.writeNBT()); nbt.setTag("conditions", condList); // Effects @@ -1325,7 +1409,7 @@ public abstract class Ability implements IAbility, IAbilityAction { activeSound = nbt.getString("activeSound"); windUpAnimationId = nbt.getInteger("windUpAnimationId"); activeAnimationId = nbt.getInteger("activeAnimationId"); - dazedAnimationId = nbt.getInteger("dazedAnimationId"); + dazedAnimationId = nbt.hasKey("dazedAnimationId") ? nbt.getInteger("dazedAnimationId") : -1; windUpAnimationName = nbt.getString("windUpAnimationName"); activeAnimationName = nbt.getString("activeAnimationName"); dazedAnimationName = nbt.getString("dazedAnimationName"); @@ -1339,6 +1423,8 @@ public abstract class Ability implements IAbility, IAbilityAction { customData = nbt.getCompoundTag("customData"); allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); ignoreCooldown = nbt.getBoolean("ignoreCooldown"); + perAbilityCooldown = nbt.getBoolean("perAbilityCooldown"); + freeOnCast = nbt.getBoolean("freeOnCast"); // Toggle toggleStates = nbt.getInteger("toggleStates"); @@ -1365,7 +1451,7 @@ public abstract class Ability implements IAbility, IAbilityAction { conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); for (int i = 0; i < condList.tagCount(); i++) { - Condition c = Condition.fromNBT(condList.getCompoundTagAt(i)); + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); if (c != null) conditions.add(c); } @@ -1903,11 +1989,11 @@ public abstract class Ability implements IAbility, IAbilityAction { return customData; } - public List getConditions() { + public List getConditions() { return conditions; } - public void addCondition(Condition c) { + public void addCondition(AbilityCondition c) { conditions.add(c); } @@ -1927,6 +2013,22 @@ public abstract class Ability implements IAbility, IAbilityAction { this.ignoreCooldown = ignoreCooldown; } + public boolean isPerAbilityCooldown() { + return perAbilityCooldown; + } + + public void setPerAbilityCooldown(boolean perAbilityCooldown) { + this.perAbilityCooldown = perAbilityCooldown; + } + + public boolean isFreeOnCast() { + return freeOnCast; + } + + public void setFreeOnCast(boolean freeOnCast) { + this.freeOnCast = freeOnCast; + } + public boolean isToggleable() { return toggleStates > 0; } @@ -2125,6 +2227,134 @@ public abstract class Ability implements IAbility, IAbilityAction { return false; } + // ═══════════════════════════════════════════════════════════════════ + // LINE-OF-SIGHT UTILITIES + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if there is a clear line of sight (no solid blocks) between caster and target. + * Raycasts from caster's eye position to target's body center. + * + * @return true if there IS line of sight (no blocks in the way) + */ + public static boolean hasLineOfSight(World world, EntityLivingBase caster, EntityLivingBase target) { + Vec3 start = Vec3.createVectorHelper(caster.posX, caster.posY + caster.getEyeHeight(), caster.posZ); + Vec3 end = Vec3.createVectorHelper(target.posX, target.posY + target.height * 0.5, target.posZ); + MovingObjectPosition result = world.rayTraceBlocks(start, end); + return result == null; + } + + /** + * Check if an enemy barrier (dome or panel) blocks the line between caster and target. + * Barriers owned by the caster or allies of the caster are not considered blocking. + * + * @return true if an enemy barrier blocks the attack + */ + @SuppressWarnings("unchecked") + public static boolean isBlockedByBarrier(World world, EntityLivingBase caster, EntityLivingBase target) { + // Barrier entities have tiny Minecraft bounding boxes (1x1 for domes, 0.5x0.5 for panels) + // but their actual collision geometry extends up to MAX_ENTITY_RADIUS (50) blocks. + // Must expand search to match EntityEnergyProjectile.checkBarrierCollision() pattern. + double searchRange = 55.0; // MAX_ENTITY_RADIUS(50) + 5 + double minX = Math.min(caster.posX, target.posX) - searchRange; + double minY = Math.min(caster.posY, target.posY) - searchRange; + double minZ = Math.min(caster.posZ, target.posZ) - searchRange; + double maxX = Math.max(caster.posX, target.posX) + searchRange; + double maxY = Math.max(caster.posY, target.posY) + searchRange; + double maxZ = Math.max(caster.posZ, target.posZ) + searchRange; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + List barriers = world.getEntitiesWithinAABB(EntityAbilityBarrier.class, searchBox); + + for (EntityAbilityBarrier barrier : barriers) { + if (barrier.isDead) continue; + if (barrier.isCharging()) continue; + + // Skip barriers owned by caster or allies + if (barrier.getOwnerEntityId() == caster.getEntityId()) continue; + Entity barrierOwner = barrier.getOwnerEntity(); + if (barrierOwner instanceof EntityLivingBase) { + if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue; + } + + if (barrier instanceof EntityAbilityDome) { + if (isDomeBlocking((EntityAbilityDome) barrier, caster, target)) return true; + } else if (barrier instanceof EntityAbilityPanel) { + if (isPanelBlocking((EntityAbilityPanel) barrier, caster, target)) return true; + } + } + + return false; + } + + /** + * Check if a dome blocks an attack from caster to target. + * Blocks when caster is outside and target is inside the dome. + */ + private static boolean isDomeBlocking(EntityAbilityDome dome, EntityLivingBase caster, EntityLivingBase target) { + float radius = dome.getDomeRadius(); + + double cdx = caster.posX - dome.posX; + double cdy = (caster.posY + caster.getEyeHeight()) - dome.posY; + double cdz = caster.posZ - dome.posZ; + double casterDist = Math.sqrt(cdx * cdx + cdy * cdy + cdz * cdz); + + double tdx = target.posX - dome.posX; + double tdy = (target.posY + target.height * 0.5) - dome.posY; + double tdz = target.posZ - dome.posZ; + double targetDist = Math.sqrt(tdx * tdx + tdy * tdy + tdz * tdz); + + // Block when caster is outside and target is inside + return casterDist > radius && targetDist < radius; + } + + /** + * Check if a panel blocks an attack from caster to target. + * Checks if the line from caster to target crosses through the panel bounds. + */ + private static boolean isPanelBlocking(EntityAbilityPanel panel, EntityLivingBase caster, EntityLivingBase target) { + float halfW = panel.getPanelData().panelWidth * 0.5f; + float halfH = panel.getPanelData().panelHeight * 0.5f; + + // Panel normal direction + float yawRad = (float) Math.toRadians(panel.getPanelYaw()); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + + // Line from caster to target + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + double dx = target.posX - startX; + double dy = (target.posY + target.height * 0.5) - startY; + double dz = target.posZ - startZ; + + // Dot product of line direction with panel normal + double denom = dx * normalX + dz * normalZ; + if (Math.abs(denom) < 0.0001) return false; // Line parallel to panel + + // Parameter t where line crosses panel plane + double relX = panel.posX - startX; + double relZ = panel.posZ - startZ; + double t = (relX * normalX + relZ * normalZ) / denom; + + if (t < 0 || t > 1) return false; // Intersection outside the line segment + + // Calculate intersection point + double hitX = startX + dx * t; + double hitY = startY + dy * t; + double hitZ = startZ + dz * t; + + // Transform to panel local space (right axis) + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + double localRight = (hitX - panel.posX) * cos + (hitZ - panel.posZ) * sin; + double localUp = hitY - panel.posY; + + // Check bounds + return Math.abs(localRight) <= halfW && Math.abs(localUp) <= halfH; + } + // ═══════════════════════════════════════════════════════════════════ // IAbility API METHODS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java index 77370b58c..60a64369d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java @@ -5,7 +5,7 @@ import net.minecraft.nbt.NBTTagCompound; /** * Unified slot for storing any combat action: inline ability, ability reference, or chain reference. - * Replaces {@link AbilitySlot} with support for all {@link IAbilityAction} types. + * Support for all {@link IAbilityAction} types. *

* References are lazy-resolved via their respective controllers and cached until * the controller revision changes. diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java new file mode 100644 index 000000000..2120e9ca6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityIconData.java @@ -0,0 +1,202 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +/** + * Icon data for abilities, stored in the ability's customData NBT under "AbilityIcon". + * Used to render ability icons in the Ability Hotbar, Wheel, and Abilities Tab. + */ +public class AbilityIconData { + public static final String NBT_KEY = "AbilityIcon"; + + private final NBTTagCompound customData; + + // Icon properties + public String texture = ""; + public int iconX = 0; + public int iconY = 0; + public int width = 32; + public int height = 32; + public float scale = 1.0f; + + /** Per-state icon UV overrides (0-indexed, maps to toggle states 1, 2, ...). */ + private int[][] stateIcons = null; + + private AbilityIconData(NBTTagCompound customData) { + this.customData = customData; + } + + /** + * Create an AbilityIconData instance from a raw customData compound. + * Reads existing values if present, otherwise uses defaults. + */ + public static AbilityIconData fromCustomData(NBTTagCompound customData) { + AbilityIconData icon = new AbilityIconData(customData); + if (customData.hasKey(NBT_KEY)) { + icon.readFromNBT(customData.getCompoundTag(NBT_KEY)); + } + return icon; + } + + /** + * Create an AbilityIconData instance from an ability's customData. + */ + public static AbilityIconData fromAbility(Ability ability) { + return fromCustomData(ability.getCustomData()); + } + + /** + * Create an AbilityIconData instance from a chained ability's customData. + */ + public static AbilityIconData fromChainedAbility(ChainedAbility chain) { + return fromCustomData(chain.getCustomData()); + } + + /** + * Write current state back to the customData NBT. + */ + public void save() { + NBTTagCompound tag = new NBTTagCompound(); + writeToNBT(tag); + customData.setTag(NBT_KEY, tag); + } + + public void writeToNBT(NBTTagCompound nbt) { + nbt.setString("Texture", texture); + nbt.setInteger("IconX", iconX); + nbt.setInteger("IconY", iconY); + nbt.setInteger("Width", width); + nbt.setInteger("Height", height); + nbt.setFloat("Scale", scale); + if (stateIcons != null && stateIcons.length > 0) { + NBTTagList list = new NBTTagList(); + for (int[] pair : stateIcons) { + NBTTagCompound comp = new NBTTagCompound(); + comp.setInteger("IconX", pair[0]); + comp.setInteger("IconY", pair[1]); + list.appendTag(comp); + } + nbt.setTag("StateIcons", list); + } + } + + public void readFromNBT(NBTTagCompound nbt) { + texture = nbt.getString("Texture"); + iconX = nbt.getInteger("IconX"); + iconY = nbt.getInteger("IconY"); + width = nbt.getInteger("Width"); + if (width <= 0) width = 32; + height = nbt.getInteger("Height"); + if (height <= 0) height = 32; + scale = nbt.getFloat("Scale"); + if (scale <= 0) scale = 1.0f; + if (nbt.hasKey("StateIcons")) { + NBTTagList list = nbt.getTagList("StateIcons", 10); + stateIcons = new int[list.tagCount()][2]; + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound comp = list.getCompoundTagAt(i); + stateIcons[i][0] = comp.getInteger("IconX"); + stateIcons[i][1] = comp.getInteger("IconY"); + } + } + } + + /** + * Check if this icon has a valid texture configured. + */ + public boolean hasTexture() { + return texture != null && !texture.isEmpty(); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS AND SETTERS (with auto-save) + // ═══════════════════════════════════════════════════════════════════ + + public String getTexture() { + return texture; + } + + public void setTexture(String texture) { + this.texture = texture != null ? texture : ""; + save(); + } + + public int getIconX() { + return iconX; + } + + public void setIconX(int iconX) { + this.iconX = Math.max(0, iconX); + save(); + } + + public int getIconY() { + return iconY; + } + + public void setIconY(int iconY) { + this.iconY = Math.max(0, iconY); + save(); + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = Math.max(1, width); + save(); + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = Math.max(1, height); + save(); + } + + public float getScale() { + return scale; + } + + public void setScale(float scale) { + this.scale = Math.max(0.1f, scale); + save(); + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-STATE ICON OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + public void setStateIcons(int[][] stateIcons) { + this.stateIcons = stateIcons; + save(); + } + + /** + * Get iconX for a specific toggle state. + * Falls back to default iconX if no state override exists. + * @param state 1-indexed toggle state (0 = off/default) + */ + public int getIconXForState(int state) { + if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { + return stateIcons[state - 1][0]; + } + return iconX; + } + + /** + * Get iconY for a specific toggle state. + * Falls back to default iconY if no state override exists. + * @param state 1-indexed toggle state (0 = off/default) + */ + public int getIconYForState(int state) { + if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { + return stateIcons[state - 1][1]; + } + return iconY; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java deleted file mode 100644 index 1afbf0906..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java +++ /dev/null @@ -1,163 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import kamkeel.npcs.controllers.AbilityController; -import net.minecraft.nbt.NBTTagCompound; - -/** - * Wrapper that stores either an inline ability (full NBT) or a reference - * to a built-in/custom ability (by name or UUID). - *

- * References are lazy-resolved via {@link AbilityController#resolveAbility(String)} - * and cached until the controller version changes. - * - * @deprecated Use {@link AbilityAction} instead, which supports abilities and chained abilities. - */ -@Deprecated -public class AbilitySlot { - - private Ability inlineAbility; - private String referenceId; - - /** - * Per-slot enabled override for reference slots (null = use master's default). - */ - private Boolean enabledOverride; - - private transient Ability cachedAbility; - private transient int cachedVersion = -1; - - private AbilitySlot() { - } - - /** - * Create a slot with an inline (embedded) ability. - */ - public static AbilitySlot inline(Ability ability) { - AbilitySlot slot = new AbilitySlot(); - slot.inlineAbility = ability; - slot.referenceId = null; - return slot; - } - - /** - * Create a slot that references a built-in ability (by name) or custom ability (by name). - */ - public static AbilitySlot reference(String referenceId) { - AbilitySlot slot = new AbilitySlot(); - slot.inlineAbility = null; - slot.referenceId = referenceId; - return slot; - } - - public boolean isReference() { - return referenceId != null; - } - - public String getReferenceId() { - return referenceId; - } - - /** - * Get the resolved ability. For inline slots, returns the ability directly. - * For reference slots, lazily resolves from AbilityController and caches. - * Returns null if the reference cannot be resolved (broken ref). - */ - public Ability getAbility() { - if (!isReference()) { - return inlineAbility; - } - - // Lazy resolve with version-based cache invalidation - AbilityController controller = AbilityController.Instance; - if (controller == null) return null; - - int currentVersion = controller.getCustomAbilityRevision(); - if (cachedAbility != null && cachedVersion == currentVersion) { - return cachedAbility; - } - - cachedAbility = controller.resolveAbility(referenceId); - // Apply per-slot enabled override so NPC-specific enable/disable persists - if (cachedAbility != null && enabledOverride != null) { - cachedAbility.setEnabled(enabledOverride); - } - cachedVersion = currentVersion; - return cachedAbility; - } - - /** - * Set the per-slot enabled override for reference slots. - * For inline slots, delegates directly to the ability. - */ - public void setEnabled(boolean enabled) { - if (!isReference()) { - if (inlineAbility != null) { - inlineAbility.setEnabled(enabled); - } - } else { - this.enabledOverride = enabled; - // Also update the cached ability immediately if present - if (cachedAbility != null) { - cachedAbility.setEnabled(enabled); - } - } - } - - /** - * Get the inline ability directly (null for reference slots). - */ - public Ability getInlineAbility() { - return inlineAbility; - } - - /** - * Convert this reference slot to an inline slot by copying the resolved ability. - * No-op if already inline. Returns false if resolution fails. - */ - public boolean convertToInline() { - if (!isReference()) return true; - - Ability resolved = getAbility(); - if (resolved == null) return false; - - // Deep copy via NBT round-trip - inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT()); - referenceId = null; - cachedAbility = null; - cachedVersion = -1; - return true; - } - - // ═══════════════════════════════════════════════════════════════════ - // NBT - // ═══════════════════════════════════════════════════════════════════ - - public NBTTagCompound writeNBT() { - if (isReference()) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("Reference", referenceId); - if (enabledOverride != null) { - nbt.setBoolean("RefEnabled", enabledOverride); - } - return nbt; - } - return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound(); - } - - public static AbilitySlot fromNBT(NBTTagCompound nbt) { - if (nbt == null) return null; - - if (nbt.hasKey("Reference")) { - AbilitySlot slot = reference(nbt.getString("Reference")); - if (nbt.hasKey("RefEnabled")) { - slot.enabledOverride = nbt.getBoolean("RefEnabled"); - } - return slot; - } - - // Inline ability - Ability ability = AbilityController.Instance.fromNBT(nbt); - if (ability == null) return null; - return inline(ability); - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java index 5de37416e..5a80166c7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/ChainedAbility.java @@ -1,6 +1,7 @@ package kamkeel.npcs.controllers.data.ability; import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -57,7 +58,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { /** * Chain-level conditions (individual ability conditions are ignored). */ - private List conditions = new ArrayList<>(); + private List conditions = new ArrayList<>(); /** * Ordered list of ability entries to execute. @@ -185,11 +186,11 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { return UserType.NPC_ONLY; } - public List getConditions() { + public List getConditions() { return conditions; } - public void setConditions(List conditions) { + public void setConditions(List conditions) { this.conditions = conditions != null ? conditions : new ArrayList<>(); } @@ -279,7 +280,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { * Check all chain-level conditions against the caster and target. */ public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { if (!c.check(caster, target)) { return false; } @@ -291,7 +292,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { * Check conditions for player use (skip target-requiring conditions). */ public boolean checkConditionsForPlayer(EntityLivingBase caster) { - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { if (c.requiresTarget()) continue; if (!c.check(caster, null)) { return false; @@ -382,7 +383,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { // Conditions NBTTagList condList = new NBTTagList(); - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { condList.appendTag(c.writeNBT()); } nbt.setTag("Conditions", condList); @@ -416,7 +417,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { conditions.clear(); NBTTagList condList = nbt.getTagList("Conditions", 10); for (int i = 0; i < condList.tagCount(); i++) { - Condition c = Condition.fromNBT(condList.getCompoundTagAt(i)); + AbilityCondition c = AbilityCondition.fromNBT(condList.getCompoundTagAt(i)); if (c != null) { conditions.add(c); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java index a1f4ac777..612cd9145 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityAction.java @@ -1,5 +1,6 @@ package kamkeel.npcs.controllers.data.ability; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -30,7 +31,7 @@ public interface IAbilityAction { UserType getAllowedBy(); - List getConditions(); + List getConditions(); boolean checkConditions(EntityLivingBase caster, EntityLivingBase target); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java index e3e7e5c0b..f3e7ccfd8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java @@ -73,4 +73,46 @@ public interface IAbilityExtender { double knockbackDirX, double knockbackDirZ) { return false; } + + /** + * Called to modify outgoing projectile damage before it hits a barrier or is used in other contexts. + * Unlike onAbilityDamage (chain of responsibility), this is cumulative — all extenders apply their + * modifications in sequence, each receiving the previous extender's output. + * + * @param ability The source ability of the projectile + * @param caster The entity that fired the projectile + * @param baseDamage The base damage from the ability configuration + * @return The modified damage value + */ + default float modifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) { + return baseDamage; + } + + /** + * Called when a barrier entity is about to be created, allowing extenders to modify its max health. + * Cumulative: all extenders apply in sequence, each receiving the previous output. + * + * @param ability The barrier ability being executed + * @param caster The entity creating the barrier + * @param baseHealth The base max health from EnergyBarrierData.maxHealth + * @return The modified max health value + */ + default float modifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) { + return baseHealth; + } + + /** + * Called when an ability is about to heal an entity. + * Return true to handle the healing (skip default entity.heal()). + * Chain of responsibility: first returning true wins. + * + * @param ability The ability performing the heal + * @param caster The entity casting the ability + * @param target The entity being healed + * @param healAmount The heal amount calculated by the ability + * @return true if healing was handled (skip default), false to pass to next extender or default + */ + default boolean onAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) { + return false; + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java new file mode 100644 index 000000000..479776930 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/AbilityCondition.java @@ -0,0 +1,127 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.LogWriter; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public abstract class AbilityCondition { + public static final int MAX_CONDITIONS = 5; + + protected String typeId = ""; + protected String name = ""; + protected UserType userType = UserType.BOTH; + protected ConditionFilter conditionFilter = ConditionFilter.CASTER; + + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + switch (getFilter()) { + case CASTER: + return checkEntity(caster); + case TARGET: + return target != null && checkEntity(target); + case BOTH: + return checkEntity(caster) && (target != null && checkEntity(target)); + default: + return checkEntity(caster); + } + } + + protected abstract boolean checkEntity(EntityLivingBase entity); + + public boolean requiresTarget() { + return false; + } + + /** + * Returns true if all required fields are filled in. + * Used to disable the Done button in SubGuiConditionEdit when incomplete. + */ + public boolean isConfigured() { + return true; + } + + public UserType getUserType() { + return userType; + } + + public String getTypeId() { + return typeId; + } + + public String getName() { + return name; + } + + public ConditionFilter getFilter() { + return conditionFilter; + } + + public void setFilter(ConditionFilter filter) { + this.conditionFilter = filter; + } + + @SideOnly(Side.CLIENT) + public abstract void getConditionDefinitions(List defs); + + /** + * Returns a human-readable summary of this condition's configuration. + * Used for tooltips when hovering over condition buttons. + */ + @SideOnly(Side.CLIENT) + public abstract String getConditionSummary(); + + @SideOnly(Side.CLIENT) + public final List getAllDefinitions() { + List defs = new ArrayList<>(); + + defs.add(FieldDef.labelField("ability.validFor", () -> + "\u00A7e" + StatCollector.translateToLocal("ability.userType." + getUserType().name()))); + defs.add(FieldDef.enumField("condition.filter", ConditionFilter.class, this::getFilter, this::setFilter)); + getConditionDefinitions(defs); + return defs; + } + + public final NBTTagCompound writeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString("typeId", getTypeId()); + nbt.setString("name", getName()); + nbt.setInteger("userType", getUserType().ordinal()); + nbt.setInteger("filter", getFilter().ordinal()); + writeTypeNBT(nbt); + return nbt; + } + + public abstract void writeTypeNBT(NBTTagCompound nbt); + + public abstract void readTypeNBT(NBTTagCompound nbt); + + public final void readNBT(NBTTagCompound nbt) { + typeId = nbt.getString("typeId"); + name = nbt.getString("name"); + userType = UserType.fromOrdinal(nbt.getInteger("userType")); + conditionFilter = ConditionFilter.fromOrdinal(nbt.getInteger("filter")); + readTypeNBT(nbt); + } + + public static AbilityCondition fromNBT(NBTTagCompound nbt) { + String typeId = nbt.getString("typeId"); + Supplier factory = AbilityController.Instance.getConditionType(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown condition type: " + typeId); + return null; + } + AbilityCondition condition = factory.get(); + condition.readNBT(nbt); + + return condition; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java new file mode 100644 index 000000000..6c8e0c24e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionFilter.java @@ -0,0 +1,39 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; + +public enum ConditionFilter { + CASTER, + TARGET, + BOTH; + + public boolean checksCaster() { + return this == CASTER || this == BOTH; + } + + public boolean checksTarget() { + return this == TARGET || this == BOTH; + } + + public static ConditionFilter fromOrdinal(int ordinal) { + ConditionFilter[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return BOTH; + } + + @Override + public String toString() { + switch (this) { + case BOTH: + return "condition.filter.both"; + case CASTER: + return "condition.filter.caster"; + case TARGET: + return "condition.filter.target"; + default: + return name(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java new file mode 100644 index 000000000..dfb997526 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHPThreshold.java @@ -0,0 +1,26 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; + +public class ConditionHPThreshold extends ConditionThreshold { + + public ConditionHPThreshold() { + this.typeId = "condition.cnpc.hp_threshold"; + this.name = "condition.hp_threshold"; + } + + @Override + protected float getEntityValue(EntityLivingBase entity) { + return entity.getHealth(); + } + + @Override + protected float getEntityMaxValue(EntityLivingBase entity) { + return entity.getMaxHealth(); + } + + @Override + protected String getStatName() { + return "HP"; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java new file mode 100644 index 000000000..124b34bfb --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHasEffect.java @@ -0,0 +1,106 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.advanced.SubGuiCustomEffectSelect; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.CustomEffectController; +import noppes.npcs.controllers.data.CustomEffect; + +import java.util.HashMap; +import java.util.List; + +public class ConditionHasEffect extends AbilityCondition { + private int effectId = -1; + private int effectIndex = 0; + + public ConditionHasEffect() { + this.typeId = "condition.cnpc.has_effect"; + this.name = "condition.has_effect"; + this.userType = UserType.PLAYER_ONLY; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + if (!(entity instanceof EntityPlayer)) return false; + if (effectId < 0) return false; + + EntityPlayer player = (EntityPlayer) entity; + return CustomEffectController.getInstance().hasEffect(player, effectId, effectIndex); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.subGuiField("condition.select_effect", + () -> new SubGuiCustomEffectSelect(effectId, effectIndex), + (SubGuiInterface gui) -> { + SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui; + if (sel.getSelectedEffectId() >= 0) { + effectId = sel.getSelectedEffectId(); + effectIndex = sel.getSelectedIndex(); + } + }) + .buttonLabel(() -> { + if (effectId < 0) return "None"; + CustomEffect effect = getEffect(); + return effect != null ? effect.getName() : "ID:" + effectId; + }) + .clearable(() -> { + effectId = -1; + effectIndex = 0; + })); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String effectName = "None"; + if (effectId >= 0) { + CustomEffect effect = getEffect(); + effectName = effect != null ? effect.getName() : "ID:" + effectId; + } + return "[" + filterLabel + "] Effect: " + effectName; + } + + @Override + public boolean isConfigured() { + return effectId >= 0; + } + + private CustomEffect getEffect() { + HashMap map = CustomEffectController.getInstance().getEffectMap(effectIndex); + return map != null ? map.get(effectId) : null; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("effectId", effectId); + nbt.setInteger("effectIndex", effectIndex); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + effectId = nbt.getInteger("effectId"); + effectIndex = nbt.getInteger("effectIndex"); + } + + public int getEffectId() { + return effectId; + } + + public void setEffectId(int effectId) { + this.effectId = effectId; + } + + public int getEffectIndex() { + return effectIndex; + } + + public void setEffectIndex(int effectIndex) { + this.effectIndex = effectIndex; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java new file mode 100644 index 000000000..8a326a16c --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionHitCount.java @@ -0,0 +1,78 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +public class ConditionHitCount extends AbilityCondition { + private int requiredHits = 3; + private int withinTicks = 60; + + public ConditionHitCount() { + this.typeId = "condition.cnpc.hit_count"; + this.name = "condition.hit_count"; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + // Not used — this condition overrides check() directly + return false; + } + + @Override + public boolean check(EntityLivingBase caster, EntityLivingBase target) { + if (caster instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) caster; + if (npc.abilities != null) { + return npc.abilities.getRecentHitCount(withinTicks) >= requiredHits; + } + } + + // For players, hit count tracking is not yet supported + return false; + } + + public int getRequiredHits() { + return requiredHits; + } + + public void setRequiredHits(int requiredHits) { + this.requiredHits = Math.max(0, requiredHits); + } + + public int getWithinTicks() { + return withinTicks; + } + + public void setWithinTicks(int withinTicks) { + this.withinTicks = Math.max(0, withinTicks); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.intField("condition.required_hits", this::getRequiredHits, this::setRequiredHits).min(1)); + defs.add(FieldDef.intField("condition.within_ticks", this::getWithinTicks, this::setWithinTicks).min(0)); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + return "[" + filterLabel + "] Hit " + requiredHits + " times in " + withinTicks + " ticks"; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("requiredHits", requiredHits); + nbt.setInteger("withinTicks", withinTicks); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + requiredHits = nbt.getInteger("requiredHits"); + withinTicks = nbt.getInteger("withinTicks"); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java new file mode 100644 index 000000000..a137304ef --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -0,0 +1,202 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.List; + +public class ConditionItem extends AbilityCondition { + + public enum UsageType { + ARMOR, HOLDING, AMMO, OFFHAND; + + public static UsageType fromOrdinal(int ordinal) { + UsageType[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : HOLDING; + } + } + + public enum ArmorSlot { + BOOTS, LEGS, CHEST, HELMET; + + public static ArmorSlot fromOrdinal(int ordinal) { + ArmorSlot[] values = values(); + return (ordinal >= 0 && ordinal < values.length) ? values[ordinal] : BOOTS; + } + } + + // Shared + private UsageType usageType = UsageType.HOLDING; + private String itemName = ""; + + // ARMOR only + private ArmorSlot armorSlot = ArmorSlot.BOOTS; + private boolean fullArmorSet = false; + + // AMMO + PLAYER only + private int requiredCount = 1; + + public ConditionItem() { + this.typeId = "condition.cnpc.item"; + this.name = "condition.item"; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + switch (usageType) { + case HOLDING: + return checkHolding(entity); + case ARMOR: + return checkArmor(entity); + case AMMO: + return checkAmmo(entity); + case OFFHAND: + return checkOffhand(entity); + default: + return false; + } + } + + private boolean checkHolding(EntityLivingBase entity) { + ItemStack held = entity.getHeldItem(); + return matchesItem(held); + } + + private boolean checkArmor(EntityLivingBase entity) { + // MC getEquipmentInSlot: 1=boots, 2=legs, 3=chest, 4=helmet + int slot = armorSlot.ordinal() + 1; // BOOTS=0, LEGS=1, CHEST=2, HELMET=3 + return matchesItem(entity.getEquipmentInSlot(slot)); + } + + private boolean checkFullArmor(EntityLivingBase entity) { + for (int i = 0; i < 4; i++) { + int slot = i + 1; + if (!matchesItem(i, entity.getEquipmentInSlot(slot))) + return false; + } + + return true; + } + + private boolean checkAmmo(EntityLivingBase entity) { + if (entity instanceof EntityPlayer) { + return checkPlayerInventoryCount((EntityPlayer) entity); + } + if (entity instanceof EntityNPCInterface) { + return checkNPCProjectile((EntityNPCInterface) entity); + } + + return false; + } + + private boolean checkOffhand(EntityLivingBase entity) { + // No offhand for players + if (entity instanceof EntityPlayer) return false; + + ItemStack item = ((EntityNPCInterface) entity).getOffHand(); + return matchesItem(item); + } + + private boolean checkPlayerInventoryCount(EntityPlayer player) { + int count = 0; + for (ItemStack stack : player.inventory.mainInventory) { + if (matchesItem(stack)) { + count += stack.stackSize; + } + } + return count >= requiredCount; + } + + private boolean checkNPCProjectile(EntityNPCInterface npc) { + ItemStack projectile = npc.inventory.getProjectile(); + return matchesItem(projectile); + } + + private boolean matchesItem(ItemStack stack) { + return matchesItem(0, stack); + } + + private boolean matchesItem(int index, ItemStack stack) { + if (stack == null || itemName == null || itemName.isEmpty()) return false; + String registryName = net.minecraft.item.Item.itemRegistry.getNameForObject(stack.getItem()); + return itemName.equals(registryName); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.enumField("condition.usage_type", UsageType.class, + this::getUsageType, this::setUsageType)); + + defs.add(FieldDef.stringField("condition.item_name", + this::getItemName, this::setItemName)); +// .hover("condition.hover.item_name")); + + + + defs.add(FieldDef.enumField("condition.armor_slot", ArmorSlot.class, + this::getArmorSlot, this::setArmorSlot) + .visibleWhen(() -> usageType == UsageType.ARMOR)); +// .hover("condition.hover.armor_slots")); + + defs.add(FieldDef.intField("condition.item_count", + this::getRequiredCount, this::setRequiredCount) + .range(1, 64) + .visibleWhen(() -> usageType == UsageType.AMMO && userType.allowsPlayer())); +// .hover("condition.hover.required_count")); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String usage = usageType.name(); + String item = itemName.isEmpty() ? "None" : itemName; + return "[" + filterLabel + "] " + usage + ": " + item; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setString("itemName", itemName); + nbt.setInteger("usageType", usageType.ordinal()); + nbt.setInteger("armorSlot", armorSlot.ordinal()); + nbt.setInteger("requiredCount", requiredCount); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + itemName = nbt.getString("itemName"); + usageType = UsageType.fromOrdinal(nbt.getInteger("usageType")); + armorSlot = ArmorSlot.fromOrdinal(nbt.getInteger("armorSlot")); + requiredCount = nbt.getInteger("requiredCount"); + } + + + @Override + public boolean isConfigured() { + return itemName != null && !itemName.isEmpty(); + } + + public UsageType getUsageType() { return usageType; } + public void setUsageType(UsageType usageType) { this.usageType = usageType; } + + public String getItemName() { return itemName; } + public void setItemName(String itemName) { this.itemName = itemName; } + + public ArmorSlot getArmorSlot() { return armorSlot; } + public void setArmorSlot(ArmorSlot armorSlot) { this.armorSlot = armorSlot; } + + public boolean isFullArmorSet() { + return fullArmorSet; + } + + public void setFullArmorSet(boolean fullArmorSet) { + this.fullArmorSet = fullArmorSet; + } + + public int getRequiredCount() { return requiredCount; } + public void setRequiredCount(int requiredCount) { this.requiredCount = Math.max(1, requiredCount); } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java new file mode 100644 index 000000000..213358ca5 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionQuestCompleted.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import kamkeel.npcs.controllers.data.ability.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.select.GuiQuestSelection; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.QuestController; +import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.controllers.data.Quest; + +import java.util.List; + +public class ConditionQuestCompleted extends AbilityCondition { + private int questId = -1; + + public ConditionQuestCompleted() { + this.typeId = "condition.cnpc.quest_completed"; + this.name = "condition.quest_completed"; + this.userType = UserType.PLAYER_ONLY; + } + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + if (!(entity instanceof EntityPlayer)) return false; + if (questId < 0) return false; + + EntityPlayer player = (EntityPlayer) entity; + return PlayerData.get(player).questData.hasFinishedQuest(questId); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.subGuiField("condition.select_quest", + () -> new GuiQuestSelection(questId), + (SubGuiInterface gui) -> { + GuiQuestSelection sel = (GuiQuestSelection) gui; + if (sel.selectedQuest != null) { + questId = sel.selectedQuest.id; + } + }) + .buttonLabel(() -> { + if (questId < 0) return "None"; + Quest q = QuestController.Instance.quests.get(questId); + return q != null ? q.title : "ID:" + questId; + }) + .clearable(() -> questId = -1)); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String questName = "None"; + if (questId >= 0) { + Quest q = QuestController.Instance.quests.get(questId); + questName = q != null ? q.title : "ID:" + questId; + } + return "[" + filterLabel + "] Quest: " + questName; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("questId", questId); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + questId = nbt.getInteger("questId"); + } + + @Override + public boolean isConfigured() { + return questId >= 0; + } + + public int getQuestId() { + return questId; + } + + public void setQuestId(int questId) { + this.questId = questId; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java new file mode 100644 index 000000000..aaa4a6b06 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionThreshold.java @@ -0,0 +1,171 @@ +package kamkeel.npcs.controllers.data.ability.conditions; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for threshold-based conditions (HP, Ki, etc.). + * Provides shared percent/flat toggle, ThresholdType enum, and FieldDef generation. + */ +public abstract class ConditionThreshold extends AbilityCondition { + + public enum ThresholdType { + ABOVE { + @Override + public boolean test(float value, float threshold) { + return value >= threshold; + } + }, + BELOW { + @Override + public boolean test(float value, float threshold) { + return value <= threshold; + } + }, + EQUAL { + @Override + public boolean test(float value, float threshold) { + return value == threshold; + } + }; + + public abstract boolean test(float value, float threshold); + + public static ThresholdType fromOrdinal(int ordinal) { + ThresholdType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return ABOVE; + } + + @Override + public String toString() { + switch (this) { + case ABOVE: + return "condition.above"; + case BELOW: + return "condition.below"; + case EQUAL: + return "condition.equal"; + default: + return name(); + } + } + } + + protected float thresholdFlat = 100f; + protected float thresholdPercent = 0.5f; + protected boolean percent = true; + protected ThresholdType thresholdType = ThresholdType.ABOVE; + + /** + * Returns the raw stat value for the entity (e.g. current HP, current Ki). + */ + protected abstract float getEntityValue(EntityLivingBase entity); + + /** + * Returns the maximum stat value for the entity (e.g. max HP, max Ki). + * Used to compute the percentage ratio. + */ + protected abstract float getEntityMaxValue(EntityLivingBase entity); + + /** + * Returns the display name for the stat being checked (e.g. "HP", "Ki"). + * Used in getConditionSummary(). + */ + protected abstract String getStatName(); + + @Override + protected boolean checkEntity(EntityLivingBase entity) { + float value; + float threshold; + if (percent) { + float max = getEntityMaxValue(entity); + value = max > 0 ? getEntityValue(entity) / max : 0; + threshold = thresholdPercent; + } else { + value = getEntityValue(entity); + threshold = thresholdFlat; + } + return thresholdType.test(value, threshold); + } + + @Override + public void getConditionDefinitions(List defs) { + defs.add(FieldDef.floatField("condition.threshold_flat", this::getThresholdFlat, this::setThresholdFlat) + .min(0).visibleWhen(() -> !isPercent())); + defs.add(FieldDef.floatField("condition.threshold_percent", this::getThresholdPercent, this::setThresholdPercent) + .min(0).max(1).visibleWhen(this::isPercent)); + defs.add(FieldDef.boolField("condition.percent", this::isPercent, this::setIsPercent)); + defs.add(FieldDef.enumField("condition.threshold_type", ThresholdType.class, + this::getThresholdType, this::setThresholdType)); + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("thresholdFlat", thresholdFlat); + nbt.setFloat("thresholdPercent", thresholdPercent); + nbt.setBoolean("percent", percent); + nbt.setInteger("thresholdType", thresholdType.ordinal()); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + thresholdFlat = nbt.getFloat("thresholdFlat"); + thresholdPercent = nbt.getFloat("thresholdPercent"); + percent = nbt.getBoolean("percent"); + thresholdType = ThresholdType.fromOrdinal(nbt.getInteger("thresholdType")); + } + + @Override + public String getConditionSummary() { + String filterLabel = StatCollector.translateToLocal(getFilter().toString()); + String typeName = getStatName(); + String typeLabel = StatCollector.translateToLocal(thresholdType.toString()); + String value = percent + ? String.format("%.0f%%", thresholdPercent * 100) + : String.format("%.0f", thresholdFlat); + return "[" + filterLabel + "] " + typeName + " " + typeLabel + " " + value; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public float getThresholdFlat() { + return thresholdFlat; + } + + public void setThresholdFlat(float value) { + this.thresholdFlat = Math.max(0, value); + } + + public float getThresholdPercent() { + return thresholdPercent; + } + + public void setThresholdPercent(float value) { + this.thresholdPercent = Math.max(0, Math.min(1, value)); + } + + public boolean isPercent() { + return percent; + } + + public void setIsPercent(boolean percent) { + this.percent = percent; + } + + public ThresholdType getThresholdType() { + return thresholdType; + } + + public void setThresholdType(ThresholdType type) { + this.thresholdType = type; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java index ef9bcff57..d54f205cc 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyBarrierData.java @@ -8,10 +8,14 @@ import java.util.Map; /** * Groups barrier properties shared by energy barrier abilities (Dome, Wall, Shield). * Handles health/durability, duration, and per-projectile-type damage multipliers. + * + * Properties: + * - Solid: Hard wall — entities cannot pass through the barrier boundary (either direction) + * - Knockback: Repulsion field — entities near the surface get pushed away + * - Absorbing: Caster's incoming damage is redirected to the barrier + * - Allows Melee: Barrier can be hit by melee attacks (punching) */ public class EnergyBarrierData { - // Knockback target display keys - private static final String[] KNOCKBACK_TARGET_KEYS = {"gui.both", "gui.players", "gui.npcs"}; public float maxHealth = 100.0f; public boolean useHealth = true; @@ -19,15 +23,17 @@ public class EnergyBarrierData { public boolean useDuration = true; public float defaultMultiplier = 1.0f; - // Knockback settings + // Solid: entities cannot pass through the barrier boundary + public boolean solid = false; + + // Knockback: repulsion field pushing entities away from surface public boolean knockbackEnabled = false; public float knockbackStrength = 1.0f; - /** - * 0=Both, 1=Player only, 2=NPC only - */ - public int knockbackTarget = 0; - // Melee settings + // Absorbing: caster's damage is redirected to the barrier + public boolean absorbing = false; + + // Melee: barrier can be hit by melee attacks public boolean meleeEnabled = false; public float meleeDamageMultiplier = 1.0f; @@ -113,24 +119,6 @@ public class EnergyBarrierData { this.defaultMultiplier = defaultMultiplier; } - // Knockback target key helpers - public static String[] getKnockbackTargetKeys() { - return KNOCKBACK_TARGET_KEYS; - } - - public String getKnockbackTargetKey() { - return KNOCKBACK_TARGET_KEYS[Math.max(0, Math.min(knockbackTarget, 2))]; - } - - public void setKnockbackTargetFromKey(String key) { - for (int i = 0; i < KNOCKBACK_TARGET_KEYS.length; i++) { - if (KNOCKBACK_TARGET_KEYS[i].equals(key)) { - knockbackTarget = i; - return; - } - } - } - // ==================== NBT ==================== public void writeNBT(NBTTagCompound nbt) { @@ -139,9 +127,10 @@ public class EnergyBarrierData { nbt.setInteger("barrierDuration", durationTicks); nbt.setBoolean("barrierUseDuration", useDuration); nbt.setFloat("barrierDefaultMult", defaultMultiplier); + nbt.setBoolean("barrierSolid", solid); nbt.setBoolean("barrierKnockback", knockbackEnabled); nbt.setFloat("barrierKnockbackStr", knockbackStrength); - nbt.setInteger("barrierKnockbackTarget", knockbackTarget); + nbt.setBoolean("barrierAbsorbing", absorbing); nbt.setBoolean("barrierMelee", meleeEnabled); nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier); @@ -158,9 +147,10 @@ public class EnergyBarrierData { durationTicks = nbt.hasKey("barrierDuration") ? nbt.getInteger("barrierDuration") : 200; useDuration = !nbt.hasKey("barrierUseDuration") || nbt.getBoolean("barrierUseDuration"); defaultMultiplier = nbt.hasKey("barrierDefaultMult") ? nbt.getFloat("barrierDefaultMult") : 1.0f; + solid = nbt.hasKey("barrierSolid") && nbt.getBoolean("barrierSolid"); knockbackEnabled = nbt.hasKey("barrierKnockback") && nbt.getBoolean("barrierKnockback"); knockbackStrength = nbt.hasKey("barrierKnockbackStr") ? nbt.getFloat("barrierKnockbackStr") : 1.0f; - knockbackTarget = nbt.hasKey("barrierKnockbackTarget") ? nbt.getInteger("barrierKnockbackTarget") : 0; + absorbing = nbt.hasKey("barrierAbsorbing") && nbt.getBoolean("barrierAbsorbing"); meleeEnabled = nbt.hasKey("barrierMelee") && nbt.getBoolean("barrierMelee"); meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f; @@ -178,9 +168,10 @@ public class EnergyBarrierData { public EnergyBarrierData copy() { EnergyBarrierData copy = new EnergyBarrierData(maxHealth, useHealth, durationTicks, useDuration); copy.defaultMultiplier = defaultMultiplier; + copy.solid = solid; copy.knockbackEnabled = knockbackEnabled; copy.knockbackStrength = knockbackStrength; - copy.knockbackTarget = knockbackTarget; + copy.absorbing = absorbing; copy.meleeEnabled = meleeEnabled; copy.meleeDamageMultiplier = meleeDamageMultiplier; copy.damageMultipliers = new HashMap<>(damageMultipliers); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java new file mode 100644 index 000000000..c12cec47f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyChargingData.java @@ -0,0 +1,83 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class EnergyChargingData { + + public int chargeDuration = 60; + public int chargeDelay = 0; + public int maxCharge = 100; + public boolean hasCharge = true; + public boolean chargeWindUpSync = true; + + public EnergyChargingData() { + } + + public EnergyChargingData(int chargeDuration, int chargeDelay, int maxCharge, boolean hasCharge, boolean chargeWindUpSync) { + this.chargeDuration = chargeDuration; + this.chargeDelay = chargeDelay; + this.maxCharge = maxCharge; + this.hasCharge = hasCharge; + this.chargeWindUpSync = chargeWindUpSync; + } + + public boolean hasCharge() { + return hasCharge; + } + + public void setHasCharge(boolean hasCharge) { + this.hasCharge = hasCharge; + } + + public boolean isChargeWindUpSync() { + return chargeWindUpSync; + } + + public void setChargeWindUpSync(boolean chargeWindUpSync) { + this.chargeWindUpSync = chargeWindUpSync; + } + + public int getChargeDuration() { + return chargeDuration; + } + + public void setChargeDuration(int chargeDuration) { + this.chargeDuration = chargeDuration; + } + + public int getChargeDelay() { + return chargeDelay; + } + + public void setChargeDelay(int chargeDelay) { + this.chargeDelay = chargeDelay; + } + + public int getMaxCharge() { + return maxCharge; + } + + public void setMaxCharge(int maxCharge) { + this.maxCharge = Math.max(0, maxCharge); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("chargeDuration", chargeDuration); + nbt.setInteger("chargeDelay", chargeDelay); + nbt.setInteger("maxCharge", maxCharge); + nbt.setBoolean("hasCharge", hasCharge); + nbt.setBoolean("chargeWindUpSync", chargeWindUpSync); + } + + public void readNBT(NBTTagCompound nbt) { + chargeDuration = nbt.hasKey("chargeDuration") ? nbt.getInteger("chargeDuration") : 60; + chargeDelay = nbt.hasKey("chargeDelay") ? nbt.getInteger("chargeDelay") : 0; + maxCharge = nbt.hasKey("maxCharge") ? nbt.getInteger("maxCharge") : 100; + hasCharge = !nbt.hasKey("hasCharge") || nbt.getBoolean("hasCharge"); + chargeWindUpSync = !nbt.hasKey("chargeWindUpSync") || nbt.getBoolean("chargeWindUpSync"); + } + + public EnergyChargingData copy() { + return new EnergyChargingData(chargeDuration, chargeDelay, maxCharge, hasCharge, chargeWindUpSync); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index d6d7044f3..4f7021705 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -52,7 +52,7 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { this.windUpSound = "mob.zombie.wood"; this.activeSound = "mob.zombie.attack"; this.windUpAnimationName = "Ability_Charge_Windup"; - this.activeAnimationName = "Ability_Active_Windup"; + this.activeAnimationName = "Ability_Charge_Active"; } @Override @@ -66,26 +66,25 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { } /** - * Called on the first tick of windup - lock direction here so it matches telegraph. + * During windup, NPCs face toward their target for animation purposes. + * Players aim freely — the telegraph follows their look direction on the client, + * and direction is locked at the end of windup in onExecute(). */ @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { - if (tick == 1) { - lockDirection(caster, target); + if (!isPlayerCaster(caster) && target != null) { + lockDirectionToTarget(caster, target); + enforceLockedRotation(caster); } - enforceLockedRotation(caster); } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // Lock final direction at end of windup so it matches the telegraph + lockDirection(caster, target); initMovement(caster, maxRange, chargeSpeed); hitEntities.clear(); - // If direction wasn't set during windup (shouldn't happen), set it now - if (movementDirection == null) { - lockDirection(caster, target); - } - enforceLockedRotation(caster); } @@ -227,6 +226,11 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { // Telegraph follows caster during windup - allows caster to reposition instance.setEntityIdToFollow(caster.getEntityId()); + // For player casters, track their rotation so telegraph follows look direction + if (isPlayerCaster(caster)) { + instance.setTrackFollowedEntityYaw(true); + } + return instance; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index e49e5bb55..6db0f832e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -134,6 +134,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { if (target != null && !isRotationLockedDuringWindup()) { instance.setTargetEntityId(target.getEntityId()); + } else { + // No target to track yaw from — track the caster's rotation instead + // so the telegraph follows where the player/NPC is facing + instance.setTrackFollowedEntityYaw(true); } return instance; @@ -160,8 +164,9 @@ public class AbilityCutter extends Ability implements IAbilityCutter { currentRotation = -arcAngle / 2.0f; activeSoundPlayed = false; - // Lock sweep direction toward target at execute time to prevent - // AI look-at jitter from misdirecting the sweep at close range + // Compute sweep direction from caster/target at execution time. + // Server-side telegraph instances are not ticked, so their yaw is stale + // from windup start — use the caster's current rotation instead. if (target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; @@ -260,6 +265,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { if (dist < minDist || dist > maxDist) continue; if (!isInSweepRange(dx, dz, sweepBaseYaw, minAngle, maxAngle)) continue; + // Line-of-sight check: skip targets behind solid blocks or enemy barriers + if (!hasLineOfSight(world, caster, entity)) continue; + if (isBlockedByBarrier(world, caster, entity)) continue; + hitEntities.add(entity.getEntityId()); float distFactor = 1.0f - ((float) dist / maxDist) * 0.3f; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java index fffbf6ca5..b5342e3d8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -26,7 +26,8 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { */ public enum DashMode { AGGRESSIVE, - DEFENSIVE; + DEFENSIVE, + DIRECTIONAL; @Override public String toString() { @@ -35,6 +36,8 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { return "ability.dash.aggressive"; case DEFENSIVE: return "ability.dash.defensive"; + case DIRECTIONAL: + return "ability.dash.directional"; default: return name(); } @@ -124,16 +127,22 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { public void onExecute(EntityLivingBase caster, EntityLivingBase target) { initMovement(caster, dashDistance, dashSpeed); - // Choose random direction based on mode - DashDirection[] directions = dashMode == DashMode.AGGRESSIVE - ? AGGRESSIVE_DIRECTIONS - : DEFENSIVE_DIRECTIONS; - chosenDirection = directions[RANDOM.nextInt(directions.length)]; + if (dashMode == DashMode.DIRECTIONAL) { + // Dash straight in the caster's look direction + chosenDirection = DashDirection.FORWARD; + setDirectionFromYaw(caster.rotationYaw); + } else { + // Choose random direction based on mode + DashDirection[] directions = dashMode == DashMode.AGGRESSIVE + ? AGGRESSIVE_DIRECTIONS + : DEFENSIVE_DIRECTIONS; + chosenDirection = directions[RANDOM.nextInt(directions.length)]; - // Calculate direction: base yaw (toward target or look dir) + direction offset - float baseYaw = getBaseYaw(caster, target); - float dashYaw = baseYaw + chosenDirection.getAngleOffset(); - setDirectionFromYaw(dashYaw); + // Calculate direction: base yaw (toward target or look dir) + direction offset + float baseYaw = getBaseYaw(caster, target); + float dashYaw = baseYaw + chosenDirection.getAngleOffset(); + setDirectionFromYaw(dashYaw); + } // Small upward impulse for a skip/hop arc (gravity handles the descent) caster.motionY = 0.2; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java index c81e97ced..d4f9c474b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java @@ -131,7 +131,7 @@ public class AbilityEffect extends Ability implements IAbilityEffect { if (instantHeal) { for (EntityLivingBase entity : getAffectedEntities()) { - healEntity(entity); + healEntity(caster, entity); applyAllEffects(caster, entity); spawnHealParticles(caster.worldObj, entity); } @@ -159,7 +159,9 @@ public class AbilityEffect extends Ability implements IAbilityEffect { } if (totalTickHeal > 0) { - entity.heal(totalTickHeal); + if (!AbilityController.Instance.fireOnAbilityHeal(this, caster, entity, totalTickHeal)) { + entity.heal(totalTickHeal); + } } if (tick % 20 == 0) { @@ -226,13 +228,15 @@ public class AbilityEffect extends Ability implements IAbilityEffect { } } - private void healEntity(EntityLivingBase entity) { + private void healEntity(EntityLivingBase caster, EntityLivingBase entity) { float totalHeal = healAmount; if (healPercent > 0) { totalHeal += entity.getMaxHealth() * healPercent; } if (totalHeal > 0) { - entity.heal(totalHeal); + if (!AbilityController.Instance.fireOnAbilityHeal(this, caster, entity, totalHeal)) { + entity.heal(totalHeal); + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java index 24489b9eb..1a1555f11 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java @@ -66,6 +66,11 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.counterAnimationName = "Ability_Guard_Counter"; } + @Override + public boolean hasDamage() { + return canCounter; + } + @Override public boolean allowBurst() { return false; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java index 740f97be8..7e61f04c0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -121,6 +121,10 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { double sideDist = dx * rightX + dz * rightZ; if (Math.abs(sideDist) > hitWidth) continue; + // Line-of-sight check: skip targets behind solid blocks or enemy barriers + if (!hasLineOfSight(caster.worldObj, caster, livingTarget)) continue; + if (isBlockedByBarrier(caster.worldObj, caster, livingTarget)) continue; + // Entity is within the rectangle - apply damage boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); if (wasHit) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java index d5b8d8c52..331b91920 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java @@ -2,6 +2,8 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.play.server.S12PacketEntityVelocity; import net.minecraft.util.Vec3; /** @@ -25,7 +27,7 @@ public abstract class AbilityMovement extends Ability { * Until the round trip completes, the server sees the old (stationary) position, * which would falsely trigger stall detection. */ - private static final int PLAYER_STALL_GRACE_TICKS = 5; + private static final int PLAYER_STALL_GRACE_TICKS = 8; private static final int NPC_STALL_GRACE_TICKS = 2; // ═══════════════════════════════════════════════════════════════════ @@ -213,6 +215,24 @@ public abstract class AbilityMovement extends Ability { // VELOCITY APPLICATION // ═══════════════════════════════════════════════════════════════════ + /** + * Send an authoritative velocity packet to a player. + *

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

+ * By sending S12 manually here — before friction — the client receives the full + * velocity and moves at the correct speed. + */ + private void sendPlayerVelocity(EntityLivingBase caster) { + if (caster instanceof EntityPlayerMP) { + ((EntityPlayerMP) caster).playerNetServerHandler.sendPacket( + new S12PacketEntityVelocity(caster)); + } + } + /** * Apply movement velocity to the caster (horizontal only, Y unchanged). */ @@ -220,7 +240,11 @@ public abstract class AbilityMovement extends Ability { caster.motionX = movementDirection.xCoord * speed; caster.motionZ = movementDirection.zCoord * speed; if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } } } @@ -233,7 +257,11 @@ public abstract class AbilityMovement extends Ability { caster.motionY = 0; caster.motionZ = movementDirection.zCoord * speed; if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } } } @@ -244,7 +272,11 @@ public abstract class AbilityMovement extends Ability { caster.motionX = 0; caster.motionZ = 0; if (!isPreview()) { - caster.velocityChanged = true; + if (caster instanceof EntityPlayerMP) { + sendPlayerVelocity(caster); + } else { + caster.velocityChanged = true; + } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java index 9f1c64ff5..079bcbf0f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -41,10 +41,24 @@ public class AbilitySlam extends Ability implements IAbilitySlam { private float leapSpeed = 1.0f; private float leapHeight = 4.0f; + /** + * Grace period (in active ticks) before landing detection activates. + * Players need more time because: + * - Server sets motionY and sends S12 velocity packet to client + * - Client receives S12 and starts moving upward + * - Client sends C03 position packet back to server with onGround=false + * Until the round trip completes, the server's player.onGround (from stale C03) + * remains true, which would falsely trigger landing detection. + */ + private static final int PLAYER_LANDING_GRACE_TICKS = 10; + private static final int NPC_LANDING_GRACE_TICKS = 3; + // Runtime state private transient double targetX, targetY, targetZ; + private transient double startY; // Y position at launch for rise detection private transient boolean hasLaunched = false; private transient boolean hasLanded = false; + private transient boolean hasRisen = false; // Whether entity has risen above launch position private transient int airTicks = 0; private transient int maxAirTicks = 60; // Timeout to prevent stuck in air @@ -118,7 +132,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { public void onExecute(EntityLivingBase caster, EntityLivingBase target) { hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; + startY = caster.posY; caster.fallDistance = 0; if (isPlayerCaster(caster)) { @@ -297,9 +313,33 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.fallDistance = 0; } - // Check for landing: hit the ground or hit a wall mid-flight - if (airTicks > 3) { - if (caster.onGround || caster.isCollidedHorizontally) { + // Prevent NPC navigator from interfering with ballistic arc. + // lockMovement=WINDUP means applyMovementControl() doesn't clear + // the navigator during ACTIVE, so AI pathfinding could add motion. + if (!isPreview() && caster instanceof EntityNPCInterface) { + ((EntityNPCInterface) caster).getNavigator().clearPathEntity(); + } + + // Track if entity has risen above launch position. + // This prevents premature landing detection for players, where + // server-side caster.onGround remains true from stale C03 packets + // until the velocity S12 round-trip completes (can take 4-8+ ticks). + if (!hasRisen && caster.posY > startY + 0.5) { + hasRisen = true; + } + + // Landing detection uses different grace periods for NPC vs Player. + // NPCs: server physics is authoritative, onGround is accurate after 3 ticks. + // Players: onGround depends on C03 packets, needs longer grace + rise confirmation. + int graceTicks = isPlayerCaster(caster) ? PLAYER_LANDING_GRACE_TICKS : NPC_LANDING_GRACE_TICKS; + if (airTicks > graceTicks) { + if (hasRisen && (caster.onGround || caster.isCollidedHorizontally)) { + onLanding(caster, caster.worldObj); + return; + } + // Safety: if entity hasn't risen after triple the grace period, + // the launch may have failed (blocked by ceiling, etc.) - force landing + if (!hasRisen && airTicks > graceTicks * 3) { onLanding(caster, caster.worldObj); return; } @@ -424,6 +464,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; } @@ -434,6 +475,15 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } hasLaunched = false; hasLanded = false; + hasRisen = false; + airTicks = 0; + } + + @Override + public void cleanup() { + hasLaunched = false; + hasLanded = false; + hasRisen = false; airTicks = 0; } @@ -442,6 +492,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { super.reset(); hasLaunched = false; hasLanded = false; + hasRisen = false; airTicks = 0; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java index b5cc53a9e..a1d1af290 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -67,7 +67,7 @@ public abstract class AbilityZone extends Ability { this.maxRange = 20.0f; this.lockMovement = LockMovementType.WINDUP; this.cooldownTicks = 0; - this.allowedBy = UserType.NPC_ONLY; + this.allowedBy = UserType.BOTH; } @Override @@ -75,6 +75,17 @@ public abstract class AbilityZone extends Ability { return false; } + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + activeEntities.clear(); + preCalculatedPositions.clear(); + } + @Override public boolean isTargetingModeLocked() { return true; @@ -130,6 +141,12 @@ public abstract class AbilityZone extends Ability { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + // Free on Cast: complete immediately — zones live independently + if (isFreeOnCast()) { + signalCompletion(); + return; + } + Iterator it = activeEntities.iterator(); while (it.hasNext()) { EntityAbilityZone entity = it.next(); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java similarity index 78% rename from src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java rename to src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java index f78cf5654..841750d1c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java @@ -2,9 +2,10 @@ package kamkeel.npcs.controllers.data.ability.type.energy; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; -import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityAbilityBarrier; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; @@ -16,14 +17,14 @@ import java.util.List; * Abstract base for energy barrier abilities (Dome, Wall, Shield). * Handles shared visual data, barrier configuration, and lifecycle management. */ -public abstract class AbilityEnergyBarrier extends AbilityEnergy { +public abstract class AbilityBarrier extends AbilityEnergy { protected final EnergyBarrierData barrierData; // Runtime entity tracking - protected transient EntityEnergyBarrier barrierEntity; + protected transient EntityAbilityBarrier barrierEntity; - protected AbilityEnergyBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) { + protected AbilityBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) { super(displayData); this.barrierData = barrierData; } @@ -33,7 +34,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { /** * Create and spawn the barrier entity during execution. */ - protected abstract EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); + protected abstract EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); /** * Add type-specific GUI field definitions. @@ -63,6 +64,16 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { return false; // Barriers are defensive } + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + barrierEntity = null; + } + @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (caster.worldObj.isRemote) return; @@ -70,6 +81,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { if (tick == 1) { barrierEntity = createBarrierEntity(caster, target); if (barrierEntity != null) { + applyBarrierHealthModifiers(caster); barrierEntity.setupCharging(getWindUpTicks()); spawnAbilityEntity(barrierEntity); } @@ -85,6 +97,7 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { // No windup or entity died — create fresh barrierEntity = createBarrierEntity(caster, target); if (barrierEntity != null) { + applyBarrierHealthModifiers(caster); spawnAbilityEntity(barrierEntity); } } @@ -97,6 +110,12 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { return; } + // Free on Cast: complete immediately after barrier becomes active + if (isFreeOnCast()) { + signalCompletion(); + return; + } + // Duration tracked by entity itself, but check here too as a failsafe if (barrierData.useDuration && tick >= barrierData.durationTicks) { cleanup(); @@ -108,6 +127,16 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { public void onComplete(EntityLivingBase caster, EntityLivingBase target) { } + /** + * Allow extenders to modify the barrier's max health at spawn time. + */ + private void applyBarrierHealthModifiers(EntityLivingBase caster) { + float modHealth = AbilityController.Instance.fireModifyBarrierHealth(this, caster, barrierData.maxHealth); + if (modHealth != barrierData.maxHealth) { + barrierEntity.setBarrierMaxHealth(modHealth); + } + } + @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { cleanup(); @@ -190,6 +219,15 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { return barrierData.getMultiplier(typeId); } + // Solid data + public boolean isSolid() { + return barrierData.solid; + } + + public void setSolid(boolean solid) { + barrierData.solid = solid; + } + // Knockback data public boolean isKnockbackEnabled() { return barrierData.knockbackEnabled; @@ -207,12 +245,13 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { barrierData.knockbackStrength = strength; } - public String getKnockbackTargetKey() { - return barrierData.getKnockbackTargetKey(); + // Absorbing data + public boolean isAbsorbing() { + return barrierData.absorbing; } - public void setKnockbackTargetKey(String key) { - barrierData.setKnockbackTargetFromKey(key); + public void setAbsorbing(boolean absorbing) { + barrierData.absorbing = absorbing; } // Melee data @@ -250,19 +289,13 @@ public abstract class AbilityEnergyBarrier extends AbilityEnergy { .range(1, 12000).visibleWhen(this::isUseDuration)); defs.add(FieldDef.floatField("ability.defaultMultiplier", this::getDefaultMultiplier, this::setDefaultMultiplier)); - // Knockback section - defs.add(FieldDef.section("ability.section.knockback")); + // Properties section + defs.add(FieldDef.section("ability.section.properties")); + defs.add(FieldDef.boolField("ability.solid", this::isSolid, this::setSolid)); defs.add(FieldDef.boolField("ability.knockbackEnabled", this::isKnockbackEnabled, this::setKnockbackEnabled)); - defs.add(FieldDef.row( - FieldDef.floatField("ability.knockbackStrength", this::getKnockbackStrength, this::setKnockbackStrength) - .range(0, 10).visibleWhen(this::isKnockbackEnabled), - FieldDef.stringEnumField("ability.knockbackTarget", EnergyBarrierData.getKnockbackTargetKeys(), - this::getKnockbackTargetKey, this::setKnockbackTargetKey) - .visibleWhen(this::isKnockbackEnabled) - )); - - // Melee section - defs.add(FieldDef.section("ability.section.melee")); + defs.add(FieldDef.floatField("ability.knockbackStrength", this::getKnockbackStrength, this::setKnockbackStrength) + .range(0, 10).visibleWhen(this::isKnockbackEnabled)); + defs.add(FieldDef.boolField("ability.absorbing", this::isAbsorbing, this::setAbsorbing)); defs.add(FieldDef.boolField("ability.meleeEnabled", this::isMeleeEnabled, this::setMeleeEnabled)); defs.add(FieldDef.floatField("ability.meleeDamageMultiplier", this::getMeleeDamageMultiplier, this::setMeleeDamageMultiplier) .range(0, 10).visibleWhen(this::isMeleeEnabled)); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java index 10643e7f2..0feda043a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java @@ -48,8 +48,8 @@ public class AbilityBeam extends AbilityEnergyProjectile impl this.cooldownTicks = 0; this.windUpTicks = 40; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; - this.rotationMode = RotationMode.TRACK; - this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.LOCKED; + this.rotationPhase = LockMovementType.ACTIVE; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; this.windUpAnimationName = "Ability_Beam_Windup"; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java index 78a317cc2..1663f2447 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -8,8 +8,8 @@ import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -22,7 +22,7 @@ import java.util.List; * Blocks incoming energy projectiles with configurable damage multipliers. * Duration and/or HP based. */ -public class AbilityDome extends AbilityEnergyBarrier { +public class AbilityDome extends AbilityBarrier { private float domeRadius = 5.0f; private boolean followCaster = false; @@ -47,8 +47,8 @@ public class AbilityDome extends AbilityEnergyBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { - EntityEnergyDome dome = new EntityEnergyDome( + protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + EntityAbilityDome dome = new EntityAbilityDome( caster.worldObj, caster, caster.posX, caster.posY, caster.posZ, domeRadius, displayData.copy(), lightningData.copy(), barrierData.copy() diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java index da3e95c81..50b68554e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java @@ -244,6 +244,16 @@ public abstract class AbilityEnergyProjectile return true; } + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + entities = null; + } + @Override public boolean isReadyForBurstCompletion(int activeTick) { return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); @@ -338,6 +348,15 @@ public abstract class AbilityEnergyProjectile } } + // Free on Cast: complete once all projectiles have been fired + if (isFreeOnCast()) { + int lastFireTick = fireDelay > 0 ? fireDelay * (projectileCount - 1) : 0; + if (tick >= lastFireTick) { + signalCompletion(); + return; + } + } + // Check if all entities are dead or unreachable boolean allDead = true; for (E entity : entities) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java index 8dd7125e6..90e0360e0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java @@ -115,6 +115,9 @@ public class AbilityOrb extends AbilityEnergyProjectile implem orb.setDamage(4.0f); orb.setKnockback(0.0f); orb.setKnockbackUp(0.0f); + orb.setProjectileCount(2); + orb.setFireDelay(2); + a.setLockMovement(LockMovementType.WINDUP_AND_ACTIVE); a.setMaxRange(75.0f); a.setBurstEnabled(true); a.setBurstAmount(15); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java index f19f9844f..2d9c515a4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java @@ -10,8 +10,8 @@ import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyPanelData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -24,7 +24,7 @@ import java.util.List; * The shield follows the caster's position and rotates with their look direction. * Cannot be placed — it's always held. */ -public class AbilityShield extends AbilityEnergyBarrier { +public class AbilityShield extends AbilityBarrier { private float shieldWidth = 2.5f; private float shieldHeight = 2.5f; @@ -50,7 +50,7 @@ public class AbilityShield extends AbilityEnergyBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, 0.0f); float frontDist = 1.5f; @@ -59,10 +59,10 @@ public class AbilityShield extends AbilityEnergyBarrier { double spawnY = caster.posY + (caster.height * 0.5f); double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist); - EntityEnergyPanel panel = new EntityEnergyPanel( + EntityAbilityPanel panel = new EntityAbilityPanel( caster.worldObj, caster, spawnX, spawnY, spawnZ, caster.rotationYaw, - EntityEnergyPanel.PanelMode.HELD, + EntityAbilityPanel.PanelMode.HELD, displayData.copy(), lightningData.copy(), barrierData.copy(), panelData ); panel.setSourceAbility(this); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java index 5c9a9fe37..2cc64bde4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -31,7 +31,7 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { // Type-specific parameters private float beamLength = 10.0f; private float beamWidth = 0.3f; // Thin like beam trail - private float beamHeight = 0.5f; // Height above ground (low enough to jump over) + private float beamHeight = 1.0f; // Beam vertical size in blocks (1 block tall, jumpable) private float damage = 5.0f; private int damageInterval = 5; private boolean piercing = true; @@ -62,6 +62,21 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { return false; } + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + @Override + public void detach() { + activeEntity = null; + } + @Override public boolean isTargetingModeLocked() { return true; @@ -97,6 +112,12 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { if (activeEntity == null || activeEntity.isDead) { activeEntity = null; signalCompletion(); + return; + } + + // Free on Cast: complete immediately — sweeper lives independently + if (isFreeOnCast()) { + signalCompletion(); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java index 4320177c1..5237485b8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java @@ -9,8 +9,8 @@ import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyPanelData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityPanel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -23,7 +23,7 @@ import java.util.List; * Can float above ground (configurable height offset). * Optional launching mode fires the wall forward with damage/knockback. */ -public class AbilityWall extends AbilityEnergyBarrier { +public class AbilityWall extends AbilityBarrier { private final EnergyPanelData panelData; @@ -55,7 +55,7 @@ public class AbilityWall extends AbilityEnergyBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { // Place wall between caster and target double placeX, placeY, placeZ; float yaw; @@ -87,11 +87,11 @@ public class AbilityWall extends AbilityEnergyBarrier { yaw = caster.rotationYaw; } - EntityEnergyPanel.PanelMode mode = panelData.launching - ? EntityEnergyPanel.PanelMode.LAUNCHED - : EntityEnergyPanel.PanelMode.PLACED; + EntityAbilityPanel.PanelMode mode = panelData.launching + ? EntityAbilityPanel.PanelMode.LAUNCHED + : EntityAbilityPanel.PanelMode.PLACED; - EntityEnergyPanel panel = new EntityEnergyPanel( + EntityAbilityPanel panel = new EntityAbilityPanel( caster.worldObj, caster, placeX, placeY, placeZ, yaw, mode, displayData.copy(), lightningData.copy(), barrierData.copy(), panelData.copy() diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java index a5d2f0d95..7c502e284 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphInstance.java @@ -33,6 +33,7 @@ public class TelegraphInstance { private int entityIdToFollow = -1; private int casterEntityId = -1; private int targetEntityId = -1; // For LINE telegraphs: entity to face (yaw tracking) + private boolean trackFollowedEntityYaw = false; // Track followed entity's rotationYaw when no targetEntity // Timing private int remainingTicks; @@ -96,6 +97,11 @@ public class TelegraphInstance { this.z = entity.posZ; // Find ground level below the entity for proper telegraph placement this.y = Ability.findGroundLevel(world, entity.posX, entity.posY, entity.posZ); + + // Track followed entity's yaw for directional telegraphs (player casters) + if (trackFollowedEntityYaw && targetEntityId < 0) { + this.yaw = entity.rotationYaw; + } } } @@ -218,6 +224,7 @@ public class TelegraphInstance { nbt.setInteger("entityIdToFollow", entityIdToFollow); nbt.setInteger("casterEntityId", casterEntityId); nbt.setInteger("targetEntityId", targetEntityId); + nbt.setBoolean("trackFollowedYaw", trackFollowedEntityYaw); nbt.setInteger("remainingTicks", remainingTicks); nbt.setInteger("totalTicks", totalTicks); @@ -243,6 +250,7 @@ public class TelegraphInstance { this.entityIdToFollow = nbt.getInteger("entityIdToFollow"); this.casterEntityId = nbt.getInteger("casterEntityId"); this.targetEntityId = nbt.getInteger("targetEntityId"); + this.trackFollowedEntityYaw = nbt.hasKey("trackFollowedYaw") && nbt.getBoolean("trackFollowedYaw"); this.remainingTicks = nbt.getInteger("remainingTicks"); this.totalTicks = nbt.getInteger("totalTicks"); @@ -335,6 +343,14 @@ public class TelegraphInstance { this.targetEntityId = targetEntityId; } + public boolean isTrackFollowedEntityYaw() { + return trackFollowedEntityYaw; + } + + public void setTrackFollowedEntityYaw(boolean track) { + this.trackFollowedEntityYaw = track; + } + public int getRemainingTicks() { return remainingTicks; } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java similarity index 55% rename from src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java rename to src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java index af6766b15..02fbbdc4e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java @@ -1,22 +1,57 @@ package kamkeel.npcs.entity; +import kamkeel.npcs.controllers.data.ability.AbilityTargetHelper; import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.world.World; import noppes.npcs.EventHooks; import noppes.npcs.entity.EntityNPCInterface; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + /** * Base class for energy barrier entities (Dome, Panel). * Provides shared health, damage, hit flash, knockback target, * and barrier lifecycle management. * Extends EntityEnergyAbility for shared visual/owner/charging state. */ -public abstract class EntityEnergyBarrier extends EntityEnergyAbility { +public abstract class EntityAbilityBarrier extends EntityEnergyAbility { + + // ==================== ACTIVE BARRIER REGISTRY ==================== + private static final List> activeBarriers = new ArrayList<>(); + private boolean tracked = false; + + public static void trackBarrier(EntityAbilityBarrier barrier) { + activeBarriers.add(new WeakReference<>(barrier)); + } + + /** + * Get all living barriers in the given world. Auto-cleans dead refs. + */ + public static List getActiveBarriers(World world) { + List result = new ArrayList<>(); + Iterator> it = activeBarriers.iterator(); + while (it.hasNext()) { + EntityAbilityBarrier b = it.next().get(); + if (b == null || b.isDead) { + it.remove(); + } else if (b.worldObj == world) { + result.add(b); + } + } + return result; + } + + public static void clearAllBarriers() { + activeBarriers.clear(); + } // ==================== BARRIER PROPERTIES ==================== protected EnergyBarrierData barrierData = new EnergyBarrierData(); @@ -27,7 +62,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { protected static final int DW_HEALTH_PERCENT = 21; protected static final int DW_HIT_FLASH = 22; - public EntityEnergyBarrier(World world) { + public EntityAbilityBarrier(World world) { super(world); this.noClip = true; } @@ -58,9 +93,69 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { public abstract void finishCharging(); /** - * Push entities away from the barrier surface. + * Process entity physics for this barrier. + * Handles solid wall (entity repositioning) and knockback (repulsion force). */ - protected abstract void knockbackEntities(); + protected abstract void processEntityPhysics(); + + /** + * Get the maximum extent of this barrier for distance pre-filtering. + * Dome returns radius, Panel returns max(width, height) / 2. + */ + public abstract float getMaxExtent(); + + /** + * Check if a generic (non-CNPC+) projectile is incoming toward this barrier. + * Uses the same geometric logic as isIncomingProjectile but with raw position data. + * + * @param posX, posY, posZ Current (or predicted) position of the projectile + * @param motionX, motionY, motionZ Current velocity of the projectile + * @param prevPosX, prevPosY, prevPosZ Previous position of the projectile + * @param ownerEntityId Entity ID of the projectile's shooter + */ + public abstract boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId); + + // ==================== GENERIC PROJECTILE HIT ==================== + + /** + * Apply damage from a generic (non-CNPC+) projectile to this barrier. + * Uses the typeId for damage multiplier lookup (e.g. "dbc.ki_attack"). + * + * @param projectileEntity The entity that hit the barrier (for context) + * @param damage Base damage to apply + * @param typeId Type identifier for damage multiplier lookup + * @return true if the barrier absorbed the hit (projectile should be destroyed) + */ + public boolean onGenericProjectileHit(Entity projectileEntity, float damage, String typeId) { + float multiplier = barrierData.getMultiplier(typeId); + float finalDamage = damage * multiplier; + + if (!worldObj.isRemote) { + float eventDamage = EventHooks.onEnergyBarrierHit(this, ownerEntityId, null, finalDamage); + if (eventDamage < 0) return false; + finalDamage = eventDamage; + } + + triggerHitFlash(); + + if (!barrierData.useHealth) { + return true; + } + + currentHealth -= finalDamage; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + + return true; + } // ==================== PROJECTILE HIT ==================== @@ -108,6 +203,16 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return barrierData.meleeEnabled; } + @Override + public boolean isEntityInsideOpaqueBlock() { + return false; + } + + @Override + protected boolean func_145771_j(double x, double y, double z) { + return false; + } + @Override public boolean attackEntityFrom(DamageSource source, float amount) { if (worldObj.isRemote || !barrierData.meleeEnabled) return false; @@ -145,8 +250,12 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { */ protected boolean updateBarrierTick() { if (!worldObj.isRemote) { - // Fire spawned event on first tick + // Track barrier and fire spawned event on first tick if (ticksAlive == 1) { + if (!tracked) { + trackBarrier(this); + tracked = true; + } EventHooks.onEnergyBarrierSpawned(this, ownerEntityId); } @@ -225,14 +334,79 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { return this.dataWatcher.getWatchableObjectFloat(DW_HEALTH_PERCENT); } - protected boolean isKnockbackTarget(EntityLivingBase entity) { - switch (barrierData.knockbackTarget) { - case 1: - return entity instanceof EntityPlayer; - case 2: - return entity instanceof EntityNPCInterface; - default: - return entity instanceof EntityPlayer || entity instanceof EntityNPCInterface; + /** + * Check if an entity is an ally of this barrier's owner. + * Allies are not affected by barrier physics. + */ + protected boolean isAllyOfOwner(EntityLivingBase entity) { + Entity owner = getOwnerEntity(); + if (owner == null || !(owner instanceof EntityLivingBase)) return false; + return AbilityTargetHelper.isAlly((EntityLivingBase) owner, entity); + } + + // ==================== CONTAINMENT & ABSORBING ==================== + + /** + * Check if an entity is geometrically inside this barrier's protected zone. + * Override in subclasses (dome checks sphere containment). + */ + public boolean isEntityInside(Entity entity) { + return false; + } + + /** + * Find a barrier that would absorb damage for the given entity (its caster). + * Returns the barrier if: absorbing is enabled AND entity is the barrier's owner. + */ + public static EntityAbilityBarrier getAbsorbingBarrier(Entity entity) { + if (entity == null || entity.worldObj == null) return null; + List barriers = getActiveBarriers(entity.worldObj); + for (EntityAbilityBarrier barrier : barriers) { + if (barrier.isDead) continue; + if (!barrier.barrierData.absorbing) continue; + if (barrier.ownerEntityId == entity.getEntityId()) { + return barrier; + } + } + return null; + } + + /** + * Absorb damage from an external source. Reduces barrier health directly. + * Used by damage protection to redirect attacks on inside entities to the barrier. + * + * @param amount The damage amount to absorb + * @return true if damage was absorbed (barrier still alive or just destroyed) + */ + public boolean absorbDamage(float amount) { + if (worldObj.isRemote) return false; + + triggerHitFlash(); + + if (!barrierData.useHealth) { + return true; // Duration-only: absorb but no health loss + } + + currentHealth -= amount; + syncHealthPercent(); + + if (currentHealth <= 0) { + onBarrierDestroyed(); + this.setDead(); + } + return true; + } + + /** + * Teleport an entity to a position. Uses network handler for players + * to ensure reliable client synchronization. + */ + protected void teleportEntity(EntityLivingBase ent, double x, double y, double z) { + if (ent instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) ent; + player.playerNetServerHandler.setPlayerLocation(x, y, z, player.rotationYaw, player.rotationPitch); + } else { + ent.setPosition(x, y, z); } } @@ -251,6 +425,16 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility { syncHealthPercent(); } + /** + * Override the barrier's max health and set current health to match. + * Used by extenders (e.g., DBC scaling) to dynamically set barrier HP at spawn time. + */ + public void setBarrierMaxHealth(float maxHealth) { + this.barrierData.setMaxHealth(maxHealth); + this.currentHealth = maxHealth; + syncHealthPercent(); + } + public int getTicksAlive() { return ticksAlive; } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java new file mode 100644 index 000000000..149475d0d --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java @@ -0,0 +1,625 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import noppes.npcs.CustomNpcs; + +import java.util.HashSet; +import java.util.List; + +/** + * Energy Dome entity - a spherical barrier that blocks incoming energy projectiles. + * Centered on the caster's position at time of casting. + * Only blocks incoming attacks (not outgoing from allies inside). + * Extends EntityAbilityBarrier for shared barrier logic. + */ +public class EntityAbilityDome extends EntityAbilityBarrier { + + // ==================== DOME-SPECIFIC PROPERTIES ==================== + protected float domeRadius = 5.0f; + protected float targetDomeRadius = 5.0f; + protected boolean followCaster = false; + + // Server-side melee detection state + private boolean inTickMelee = false; + private final HashSet processedMeleeSwings = new HashSet<>(); + + public EntityAbilityDome(World world) { + super(world); + this.noClip = true; + this.stepHeight = 0.0F; + this.setSize(1.0f, 1.0f); + } + + public EntityAbilityDome(World world, EntityLivingBase owner, double x, double y, double z, + float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier) { + this(world); + this.noClip = true; + this.stepHeight = 0.0F; + this.ownerEntityId = owner.getEntityId(); + this.setDomeRadius(domeRadius); + this.displayData = display; + this.lightningData = lightning; + this.barrierData = barrier; + this.currentHealth = barrier.maxHealth; + this.setPosition(x, y, z); + } + + // ==================== POSITION / BOUNDING BOX ==================== + + @Override + protected void setSize(float width, float height) { + super.setSize(width, height); + } + + @Override + public void applyEntityCollision(Entity entityIn) { + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + super.onUpdate(); + + // Follow caster: both sides for smooth interpolated rendering + if (followCaster) { + Entity owner = ownerEntityId >= 0 ? worldObj.getEntityByID(ownerEntityId) : null; + if (owner != null) { + this.setPosition(owner.posX, owner.posY, owner.posZ); + // Sync prevPos with owner's prevPos for smooth interpolation + this.prevPosX = owner.prevPosX; + this.prevPosY = owner.prevPosY; + this.prevPosZ = owner.prevPosZ; + } + } + + // Handle charging animation (both sides for smooth rendering) + if (isCharging()) { + chargeTick++; + float progress = getChargeProgress(); + this.setDomeRadius(targetDomeRadius * progress); + // Refresh BB for current charge radius + this.setPosition(posX, posY, posZ); + return; // Don't tick duration/death during charging + } + + ticksAlive++; + + if (updateBarrierTick()) return; + + // Server-side: detect and apply melee hits from nearby players. + // Bypasses MC's processUseEntity reach check (which uses center-to-center + // distance and fails for domes with radius > 5). + if (!worldObj.isRemote && barrierData.meleeEnabled) { + processMeleeHits(); + } + + // Process entity physics every tick + // Server: solid + knockback for all entities + // Client: solid prediction for local player only (smooth movement blocking) + if (barrierData.solid || barrierData.knockbackEnabled) { + processEntityPhysics(); + } + + // Client-side: adjust BB for accurate melee targeting at all approach angles. + // Must run AFTER all position/BB updates and BEFORE getMouseOver() in the render phase. + if (worldObj.isRemote && barrierData.meleeEnabled && !isCharging()) { + adjustMeleeBoundingBox(); + } + } + + // ==================== INCOMING CHECK ==================== + + /** + * Swept ray-sphere intersection test. + * Tests if the line segment from prevPos to currPos crosses the dome sphere boundary + * from outside. Handles fast projectiles that skip through in a single tick. + * + * @return true if the segment enters the sphere from outside + */ + private boolean isIncomingRay( + double currX, double currY, double currZ, + double prevX, double prevY, double prevZ, + int projOwnerEntityId) + { + if (isCharging()) return false; + if (projOwnerEntityId == this.ownerEntityId) return false; + + // Ray: P(t) = prev + t * (curr - prev), t in [0, 1] + double rayDirX = currX - prevX; + double rayDirY = currY - prevY; + double rayDirZ = currZ - prevZ; + + // Vector from dome center to ray origin (prevPos) + double ocX = prevX - this.posX; + double ocY = prevY - this.posY; + double ocZ = prevZ - this.posZ; + + double r = domeRadius; + + // Quadratic: a*t^2 + b*t + c = 0 + double a = rayDirX * rayDirX + rayDirY * rayDirY + rayDirZ * rayDirZ; + double b = 2.0 * (ocX * rayDirX + ocY * rayDirY + ocZ * rayDirZ); + double c = (ocX * ocX + ocY * ocY + ocZ * ocZ) - r * r; + + // c > 0: prevPos is outside sphere; c <= 0: inside (don't block) + if (c <= 0) return false; + + if (a < 1e-10) return false; // No movement + + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0) return false; // Ray misses sphere entirely + + double sqrtDisc = Math.sqrt(discriminant); + double t1 = (-b - sqrtDisc) / (2.0 * a); // Entry point (first intersection) + + // Entry must be within this tick's movement segment [0, 1] + return t1 >= 0.0 && t1 <= 1.0; + } + + @Override + public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { + // Faction check: don't block same-faction NPC projectiles + Entity owner = getOwnerEntity(); + Entity projOwner = projectile.getOwnerEntity(); + if (owner instanceof noppes.npcs.entity.EntityNPCInterface && projOwner instanceof noppes.npcs.entity.EntityNPCInterface) { + if (((noppes.npcs.entity.EntityNPCInterface) owner).faction.id == ((noppes.npcs.entity.EntityNPCInterface) projOwner).faction.id) { + return false; + } + } + + double prevX = projectile.posX - projectile.motionX; + double prevY = projectile.posY - projectile.motionY; + double prevZ = projectile.posZ - projectile.motionZ; + + return isIncomingRay( + projectile.posX, projectile.posY, projectile.posZ, + prevX, prevY, prevZ, + projectile.getOwnerEntityId()); + } + + @Override + public boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId) + { + return isIncomingRay(posX, posY, posZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } + + @Override + public float getMaxExtent() { + return domeRadius; + } + + // ==================== CHARGING ==================== + + @Override + public void setupCharging(int duration) { + this.targetDomeRadius = this.domeRadius; + this.setDomeRadius(0.01f); + this.chargeDuration = duration; + this.chargeTick = 0; + setCharging(true); + } + + @Override + public void finishCharging() { + this.setDomeRadius(this.targetDomeRadius); + setCharging(false); + } + + // ==================== ENTITY PHYSICS (Solid + Knockback) ==================== + + /** + * Processes entity physics for the dome barrier. Two independent systems: + *

+ * SOLID: Hard wall — entities cannot cross the dome boundary in either direction. + * Uses reactive crossing detection: compares current position to previous tick + * to detect boundary crossings, then teleports back and applies velocity correction. + * Also preemptively cancels inward velocity when near the surface. + *

+ * KNOCKBACK: Repulsion force — entities near the dome surface get pushed away. + * This is a push effect only; entities can still pass through with enough effort. + * Does NOT prevent passthrough — use solid for that. + *

+ * For moving domes (followCaster), dome velocity is accounted for by using + * the dome's previous position for previous-tick distance calculations. + */ + @Override + @SuppressWarnings("unchecked") + protected void processEntityPhysics() { + float r = domeRadius; + boolean solid = barrierData.solid; + boolean knockback = barrierData.knockbackEnabled; + float strength = barrierData.knockbackStrength; + + float solidMargin = 1.5f; // Zone around surface for preemptive velocity correction + float knockbackMargin = 2.0f; // Zone around surface for knockback push + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - r - knockbackMargin, posY - r - knockbackMargin, posZ - r - knockbackMargin, + posX + r + knockbackMargin, posY + r + knockbackMargin, posZ + r + knockbackMargin + ); + + // On client, identify local player for client-side solid prediction + EntityPlayer localPlayer = worldObj.isRemote ? CustomNpcs.proxy.getPlayer() : null; + + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + for (EntityLivingBase ent : entities) { + if (ent.getEntityId() == ownerEntityId) continue; + if (isAllyOfOwner(ent)) continue; + + // Client-side: only process local player for solid prediction + if (worldObj.isRemote && (localPlayer == null || ent != localPlayer)) continue; + + // Current position relative to dome center + double dx = ent.posX - posX; + double dy = (ent.posY + ent.height * 0.5) - posY; + double dz = ent.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (dist < 0.01) continue; + + // Normalized direction from dome center toward entity (outward) + double nx = dx / dist; + double ny = dy / dist; + double nz = dz / dist; + + boolean isInside = dist < r; + + // --- SOLID: hard wall preventing boundary crossing --- + if (solid) { + // Previous tick: entity position relative to dome's previous position + double prevDx = ent.prevPosX - prevPosX; + double prevDy = (ent.prevPosY + ent.height * 0.5) - prevPosY; + double prevDz = ent.prevPosZ - prevPosZ; + double prevDist = Math.sqrt(prevDx * prevDx + prevDy * prevDy + prevDz * prevDz); + boolean wasInside = prevDist < r; + + // Radial velocity (positive = moving outward from dome center) + double radialVel = ent.motionX * nx + ent.motionY * ny + ent.motionZ * nz; + + if (wasInside != isInside) { + // Entity crossed the boundary this tick — push back to original side + double pushDist = wasInside ? (r - 0.3) : (r + 0.3); + double surfaceX = posX + nx * pushDist; + double surfaceY = posY + ny * pushDist - ent.height * 0.5; + double surfaceZ = posZ + nz * pushDist; + teleportEntity(ent, surfaceX, surfaceY, surfaceZ); + + // Cancel radial velocity and add corrective push + ent.motionX -= radialVel * nx; + ent.motionY -= radialVel * ny; + ent.motionZ -= radialVel * nz; + double pushForce = wasInside ? -0.15 : 0.15; + ent.motionX += nx * pushForce; + ent.motionZ += nz * pushForce; + ent.velocityChanged = true; + } else { + // Preemptive: near surface and moving toward it — cancel radial velocity + double surfaceDist = Math.abs(dist - r); + if (surfaceDist < solidMargin) { + boolean movingTowardSurface = (!isInside && radialVel < -0.01) + || (isInside && radialVel > 0.01); + if (movingTowardSurface) { + ent.motionX -= radialVel * nx; + ent.motionY -= radialVel * ny; + ent.motionZ -= radialVel * nz; + double pushForce = isInside ? -0.05 : 0.05; + ent.motionX += nx * pushForce; + ent.motionZ += nz * pushForce; + ent.velocityChanged = true; + } + } + } + } + + // --- KNOCKBACK: repulsion push (server only, synced via velocityChanged) --- + if (!worldObj.isRemote && knockback) { + double surfaceDist = Math.abs(dist - r); + if (surfaceDist < knockbackMargin) { + double proximity = 1.0 - (surfaceDist / knockbackMargin); + double force = proximity * strength * 0.06; + + if (isInside) { + // Push toward center (away from surface) + ent.motionX += -nx * force; + ent.motionY += -ny * force * 0.5; + ent.motionZ += -nz * force; + } else { + // Push outward (away from surface) + ent.motionX += nx * force; + ent.motionY += ny * force * 0.5; + ent.motionZ += nz * force; + } + ent.velocityChanged = true; + } + } + } + } + + // ==================== CONTAINMENT CHECK ==================== + + @Override + public boolean isEntityInside(Entity entity) { + if (entity == null) return false; + double dx = entity.posX - posX; + double dy = (entity.posY + entity.height * 0.5) - posY; + double dz = entity.posZ - posZ; + return dx * dx + dy * dy + dz * dz < domeRadius * domeRadius; + } + + // ==================== MELEE (spherical check) ==================== + + /** + * Controls whether MC's entity picking (crosshair raycast) can target this dome. + * Returns false when melee is disabled or the dome is still charging. + *

+ * Inside players CAN target the dome because adjustMeleeBoundingBox places a small BB + * at the nearest surface point, allowing mobs in other directions to still be targeted. + */ + @Override + public boolean canBeCollidedWith() { + if (!barrierData.meleeEnabled) return false; + if (isCharging()) return false; + return true; + } + + /** + * Client-side: Repositions the bounding box to a small cube at the nearest sphere surface + * point toward the player. This fixes melee targeting at diagonal approach angles where the + * player would otherwise be inside the dome-sized cubic BB but outside the actual sphere, + * causing MC's AABB raycast to return the far exit point (beyond reach distance). + *

+ * With a small BB (2x2x2) at the surface point, even if the player is inside it at close + * range, the exit point is at most ~1.7 blocks away — well within melee reach. + */ + private void adjustMeleeBoundingBox() { + EntityPlayer player = CustomNpcs.proxy.getPlayer(); + if (player == null) { + updateBoundingBox(); + return; + } + + double dx = player.posX - posX; + double dy = (player.posY + player.getEyeHeight()) - posY; + double dz = player.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + // Only adjust when player is within reasonable melee range of dome surface + if (dist < 0.01 || dist > domeRadius + 6.0) { + updateBoundingBox(); + return; + } + + // Nearest point on sphere surface toward player + double nx = dx / dist; + double ny = dy / dist; + double nz = dz / dist; + double surfX = posX + nx * domeRadius; + double surfY = posY + ny * domeRadius; + double surfZ = posZ + nz * domeRadius; + + float s = 1.0f; + this.boundingBox.setBounds( + surfX - s, surfY - s, surfZ - s, + surfX + s, surfY + s, surfZ + s + ); + } + + /** + * Player melee is handled by processMeleeHits (server-side tick detection) to bypass + * MC's processUseEntity reach check which uses center-to-center distance. + * Direct player melee ("player" damage type) is rejected unless inTickMelee is set, + * preventing double-hits when both the C02 path and tick detection fire. + * Non-player melee (mobs) and all other damage sources pass through with sphere validation. + */ + @Override + public boolean attackEntityFrom(DamageSource source, float amount) { + // Player melee: only allow from tick-based detection + if (!inTickMelee && "player".equals(source.damageType)) { + return false; + } + if (source.getEntity() != null) { + Entity attacker = source.getEntity(); + double dx = attacker.posX - this.posX; + double dy = (attacker.posY + attacker.height * 0.5) - this.posY; + double dz = attacker.posZ - this.posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + double surfaceDist = Math.abs(dist - domeRadius); + if (surfaceDist > 5.0) return false; + } + return super.attackEntityFrom(source, amount); + } + + /** + * Server-side melee detection. Each tick, finds players near the dome surface who are + * swinging and looking at the dome, then applies the attack via attackTargetEntityWithCurrentItem + * (preserving enchantments, crits, fire aspect, etc.). This bypasses MC's processUseEntity + * reach check which uses center-to-center distance and fails for large domes. + */ + @SuppressWarnings("unchecked") + private void processMeleeHits() { + float r = domeRadius; + float maxReach = 6.0f; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - r - maxReach, posY - r - maxReach, posZ - r - maxReach, + posX + r + maxReach, posY + r + maxReach, posZ + r + maxReach + ); + + List players = worldObj.getEntitiesWithinAABB(EntityPlayer.class, searchBox); + for (EntityPlayer player : players) { + if (player.getEntityId() == ownerEntityId) continue; + if (isAllyOfOwner(player)) continue; + + int playerId = player.getEntityId(); + + if (!player.isSwingInProgress) { + processedMeleeSwings.remove(playerId); + continue; + } + + if (processedMeleeSwings.contains(playerId)) continue; + + // Check surface distance + double dx = player.posX - posX; + double dy = (player.posY + 1.62) - posY; + double dz = player.posZ - posZ; + double distSq = dx * dx + dy * dy + dz * dz; + double dist = Math.sqrt(distSq); + double surfaceDist = Math.abs(dist - r); + if (surfaceDist > maxReach) continue; + + // Ray-sphere intersection: check if look direction hits the dome + Vec3 look = player.getLook(1.0f); + double b = 2.0 * (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord); + double c = distSq - (double)(r * r); + double discriminant = b * b - 4.0 * c; + if (discriminant < 0) continue; + + double sqrtDisc = Math.sqrt(discriminant); + double t1 = (-b - sqrtDisc) / 2.0; + double t2 = (-b + sqrtDisc) / 2.0; + + // Outside: t1 is entry distance. Inside: t1 < 0, t2 is exit distance. + double hitDist = t1 >= 0 ? t1 : t2; + if (hitDist < 0 || hitDist > maxReach) continue; + + // Apply the attack with full MC damage calculation + processedMeleeSwings.add(playerId); + inTickMelee = true; + player.attackTargetEntityWithCurrentItem(this); + inTickMelee = false; + } + } + + // ==================== BOUNDING BOX ==================== + + /** + * No expansion needed — the bounding box is already dome-sized. + * Returning 0 ensures players outside the dome sphere are also outside the + * ray-testing BB, so MC's raycast returns the near-face hit (within reach) + * rather than the far exit point (beyond reach). + */ + @Override + public float getCollisionBorderSize() { + return 0.0f; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + double d = domeRadius * 8.0D; + d *= 64.0D; + 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() { + return domeRadius; + } + + public void setDomeRadius(float radius) { + this.domeRadius = Math.max(0.1f, radius); + this.setPosition(this.posX, this.posY, this.posZ); + } + + public boolean isFollowCaster() { + return followCaster; + } + + public void setFollowCaster(boolean follow) { + this.followCaster = follow; + } + + @Override + @SideOnly(Side.CLIENT) + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int increments) { + // Don't do the vanilla "push up out of blocks" logic. + this.setPosition(x, y, z); + this.setRotation(yaw, pitch); + } + + @Override + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + updateBoundingBox(); + } + + protected void updateBoundingBox() { + float r = this.domeRadius; + this.boundingBox.setBounds( + this.posX - r, this.posY - r, this.posZ - r, + this.posX + r, this.posY + r, this.posZ + r + ); + } + + // ==================== NBT ==================== + + @Override + protected void readEntityFromNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBarrierBaseNBT(nbt); + nbt.setFloat("DomeRadius", domeRadius); + nbt.setFloat("TargetDomeRadius", targetDomeRadius); + nbt.setBoolean("FollowCaster", followCaster); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBarrierBaseNBT(nbt); + this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS)); + this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); + this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); + } +} diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 38808cad9..6a568a89d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -14,6 +14,7 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.EventHooks; +import noppes.npcs.entity.EntityNPCInterface; import java.util.HashSet; import java.util.List; @@ -369,6 +370,99 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { return true; } + // ==================== BARRIER COLLISION ==================== + + /** + * Override barrier collision for lasers. The base class uses projectile position/velocity + * which doesn't work for lasers (posX/Y/Z stays at origin, motionX/Y/Z is zero). + * Instead, performs line-sphere intersection against domes. + */ + @Override + @SuppressWarnings("unchecked") + protected boolean checkBarrierCollision() { + if (currentLength <= 0 || fullyExtended) return false; + + List barriers = EntityAbilityBarrier.getActiveBarriers(worldObj); + for (EntityAbilityBarrier barrier : barriers) { + if (barrier.isDead || barrier.isCharging()) continue; + if (barrier.getOwnerEntityId() == this.ownerEntityId) continue; + + // Same-faction NPC check + Entity bOwner = barrier.getOwnerEntity(); + Entity lOwner = this.getOwnerEntity(); + if (bOwner instanceof EntityNPCInterface && lOwner instanceof EntityNPCInterface) { + if (((EntityNPCInterface) bOwner).faction.id == ((EntityNPCInterface) lOwner).faction.id) { + continue; + } + } + + if (barrier instanceof EntityAbilityDome) { + EntityAbilityDome dome = (EntityAbilityDome) barrier; + float intersectDist = getLineSphereIntersection(dome); + if (intersectDist >= 0) { + // Truncate laser at dome surface + currentLength = intersectDist; + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + fullyExtended = true; + + float damage = getModifiedDamage(); + dome.onProjectileHit(this, damage); + return false; // Don't kill laser — it's truncated and will linger + } + } else { + // Non-dome barriers: fall through to standard check + if (barrier.isIncomingProjectile(this)) { + float damage = getModifiedDamage(); + if (barrier.onProjectileHit(this, damage)) { + hasHit = true; + this.setDead(); + return true; + } + } + } + } + return false; + } + + /** + * Line-sphere intersection between the laser line segment and a dome. + * Returns the distance along the laser direction to the first entry point, + * or -1 if no intersection from outside. + */ + private float getLineSphereIntersection(EntityAbilityDome dome) { + double cx = dome.posX; + double cy = dome.posY; + double cz = dome.posZ; + float radius = dome.getDomeRadius(); + + // If laser origin is inside the dome, don't block (outgoing) + double ocX = startX - cx; + double ocY = startY - cy; + double ocZ = startZ - cz; + double originDistSq = ocX * ocX + ocY * ocY + ocZ * ocZ; + if (originDistSq < (double) radius * radius) return -1; + + // Solve: |start + t*dir - C|^2 = R^2 + // a*t^2 + b*t + c = 0 + double a = dirX * dirX + dirY * dirY + dirZ * dirZ; + double b = 2.0 * (dirX * ocX + dirY * ocY + dirZ * ocZ); + double c = originDistSq - (double) radius * radius; + + double discriminant = b * b - 4.0 * a * c; + if (discriminant < 0) return -1; + + double sqrtD = Math.sqrt(discriminant); + double t1 = (-b - sqrtD) / (2.0 * a); // Entry point + + if (t1 >= 0 && t1 <= currentLength) { + return (float) t1; + } + + return -1; + } + // ==================== GETTERS FOR RENDERER ==================== public void setLockVerticalDirection(boolean lock) { diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java similarity index 53% rename from src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java rename to src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java index d3665e319..f1a89012e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java @@ -13,6 +13,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; +import noppes.npcs.CustomNpcs; import noppes.npcs.NpcDamageSource; import noppes.npcs.entity.EntityNPCInterface; @@ -21,9 +22,9 @@ import java.util.List; /** * Energy Panel entity - a flat rectangular barrier used by Wall and Shield abilities. * Supports three modes: PLACED (stationary), HELD (tracks caster), LAUNCHED (moves forward). - * Extends EntityEnergyBarrier for shared barrier logic. + * Extends EntityAbilityBarrier for shared barrier logic. */ -public class EntityEnergyPanel extends EntityEnergyBarrier { +public class EntityAbilityPanel extends EntityAbilityBarrier { public enum PanelMode { PLACED, // Stationary wall @@ -35,24 +36,26 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { protected EnergyPanelData panelData = new EnergyPanelData(); protected PanelMode mode = PanelMode.PLACED; protected float panelYaw = 0.0f; // Rotation of the panel face (degrees) + protected float prevPanelYaw = 0.0f; // Previous tick yaw for smooth interpolation // ==================== CHARGING (panel-specific targets) ==================== protected float targetPanelWidth; protected float targetPanelHeight; - public EntityEnergyPanel(World world) { + public EntityAbilityPanel(World world) { super(world); this.setSize(0.5f, 0.5f); } - public EntityEnergyPanel(World world, EntityLivingBase owner, double x, double y, double z, - float yaw, PanelMode mode, - EnergyDisplayData display, EnergyLightningData lightning, - EnergyBarrierData barrier, EnergyPanelData panel) { + public EntityAbilityPanel(World world, EntityLivingBase owner, double x, double y, double z, + float yaw, PanelMode mode, + EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier, EnergyPanelData panel) { this(world); this.setPosition(x, y + panel.heightOffset, z); this.ownerEntityId = owner.getEntityId(); this.panelYaw = yaw; + this.prevPanelYaw = yaw; this.mode = mode; this.displayData = display; this.lightningData = lightning; @@ -69,11 +72,36 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { } } + // ==================== POSITION / BOUNDING BOX ==================== + + /** + * Override setPosition to maintain panel-sized bounding box. + * MC's default setPosition() resets BB based on width/height fields. + * Network sync calls setPosition(), which would shrink the BB. + * This ensures melee targeting always works against the full panel surface. + */ + @Override + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + if (panelData != null) { + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float extent = Math.max(halfW, 0.5f); + this.boundingBox.setBounds(x - extent, y - halfH, z - extent, x + extent, y + halfH, z + extent); + } else { + float f = this.width / 2.0F; + this.boundingBox.setBounds(x - f, y, z - f, x + f, y + this.height, z + f); + } + } + @Override public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; + this.prevPanelYaw = this.panelYaw; super.onUpdate(); @@ -95,9 +123,11 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { if (updateBarrierTick()) return; - // Knockback (not during launched mode) - if (!worldObj.isRemote && barrierData.knockbackEnabled && mode != PanelMode.LAUNCHED) { - knockbackEntities(); + // Process entity physics every tick (not during launched mode) + // Server: solid + knockback for all entities + // Client: solid prediction for local player only (smooth movement blocking) + if ((barrierData.solid || barrierData.knockbackEnabled) && mode != PanelMode.LAUNCHED) { + processEntityPhysics(); } // Mode-specific updates @@ -130,6 +160,12 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { double newZ = owner.posZ + (Math.cos(yawRad) * frontDist); this.setPosition(newX, newY, newZ); + + // Sync prevPos with owner's prevPos for smooth interpolation + float prevYawRad = (float) Math.toRadians(owner.prevRotationYaw); + this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist); + this.prevPosY = owner.prevPosY + panelData.heightOffset + (owner.height * 0.5f); + this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist); } private void updateLaunched() { @@ -199,16 +235,89 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { // ==================== INCOMING CHECK ==================== /** - * Check if a projectile hits this panel surface. - * Only blocks incoming projectiles (not from the panel's owner). + * Swept ray-plane intersection test for the panel. + * Tests if the line segment from prevPos to currPos crosses the panel plane + * within its width/height bounds. Handles fast projectiles that skip through + * the thin panel in a single tick. + * + * @return true if the segment crosses the panel from either side */ + private boolean isIncomingRay( + double currX, double currY, double currZ, + double prevX, double prevY, double prevZ, + int projOwnerEntityId) + { + if (isCharging()) return false; + if (projOwnerEntityId == this.ownerEntityId) return false; + + float halfW = panelData.panelWidth * 0.5f; + float halfH = panelData.panelHeight * 0.5f; + float panelThickness = 0.5f; + + float yawRad = (float) Math.toRadians(panelYaw); + double normalX = -Math.sin(yawRad); + double normalZ = Math.cos(yawRad); + double cos = Math.cos(yawRad); + double sin = Math.sin(yawRad); + + // Signed distance from prevPos and currPos to panel plane + double relPrevX = prevX - this.posX; + double relPrevY = prevY - this.posY; + double relPrevZ = prevZ - this.posZ; + double prevDist = relPrevX * normalX + relPrevZ * normalZ; + + double relCurrX = currX - this.posX; + double relCurrY = currY - this.posY; + double relCurrZ = currZ - this.posZ; + double currDist = relCurrX * normalX + relCurrZ * normalZ; + + // Check if segment crosses the plane (sign change) + if (prevDist * currDist > 0) { + // Both on same side — check if within thickness (slow projectile fallback) + if (Math.abs(currDist) <= panelThickness) { + double localRight = relCurrX * cos + relCurrZ * sin; + if (Math.abs(localRight) > halfW) return false; + if (Math.abs(relCurrY) > halfH) return false; + // Check incoming direction + double motX = currX - prevX; + double motZ = currZ - prevZ; + double dot = motX * normalX + motZ * normalZ; + if (currDist > 0 && dot >= 0) return false; + if (currDist < 0 && dot <= 0) return false; + return true; + } + return false; + } + + // Segment crosses plane — compute intersection parameter t + double rayDirX = currX - prevX; + double rayDirZ = currZ - prevZ; + double denom = rayDirX * normalX + rayDirZ * normalZ; + if (Math.abs(denom) < 1e-10) return false; // Parallel to plane + + double t = -prevDist / denom; + if (t < 0.0 || t > 1.0) return false; + + // Compute intersection point + double hitX = prevX + (currX - prevX) * t; + double hitY = prevY + (currY - prevY) * t; + double hitZ = prevZ + (currZ - prevZ) * t; + + // Transform hit point to panel-local space and check bounds + double relHitX = hitX - this.posX; + double relHitY = hitY - this.posY; + double relHitZ = hitZ - this.posZ; + + double localRight = relHitX * cos + relHitZ * sin; + if (Math.abs(localRight) > halfW) return false; + if (Math.abs(relHitY) > halfH) return false; + + return true; + } + @Override public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { - // Don't block during charging phase - if (isCharging()) return false; - if (projectile.getOwnerEntityId() == this.ownerEntityId) return false; - - // Faction check + // Faction check: don't block same-faction NPC projectiles Entity owner = getOwnerEntity(); Entity projOwner = projectile.getOwnerEntity(); if (owner instanceof EntityNPCInterface && projOwner instanceof EntityNPCInterface) { @@ -217,38 +326,29 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { } } - // Check if projectile is within panel bounds - float halfW = panelData.panelWidth * 0.5f; - float halfH = panelData.panelHeight * 0.5f; - float panelThickness = 0.5f; // Collision thickness + double prevX = projectile.posX - projectile.motionX; + double prevY = projectile.posY - projectile.motionY; + double prevZ = projectile.posZ - projectile.motionZ; - // Transform projectile position to panel-local space - float yawRad = (float) Math.toRadians(panelYaw); - double relX = projectile.posX - this.posX; - double relY = projectile.posY - this.posY; - double relZ = projectile.posZ - this.posZ; + return isIncomingRay( + projectile.posX, projectile.posY, projectile.posZ, + prevX, prevY, prevZ, + projectile.getOwnerEntityId()); + } - // Rotate into panel space (panel faces along -sin(yaw), cos(yaw)) - double cos = Math.cos(yawRad); - double sin = Math.sin(yawRad); - double localForward = relX * (-sin) + relZ * cos; // Distance along panel normal - double localRight = relX * cos + relZ * sin; // Distance along panel width + @Override + public boolean isIncomingGenericProjectile( + double posX, double posY, double posZ, + double motionX, double motionY, double motionZ, + double prevPosX, double prevPosY, double prevPosZ, + int ownerEntityId) + { + return isIncomingRay(posX, posY, posZ, prevPosX, prevPosY, prevPosZ, ownerEntityId); + } - // Check bounds - if (Math.abs(localForward) > panelThickness) return false; - if (Math.abs(localRight) > halfW) return false; - if (Math.abs(relY) > halfH) return false; - - // Check incoming direction via dot product with panel normal - double normalX = -Math.sin(yawRad); - double normalZ = Math.cos(yawRad); - double dot = projectile.motionX * normalX + projectile.motionZ * normalZ; - - // Determine which side of the panel the projectile is on - if (localForward > 0 && dot >= 0) return false; // Moving away from front side - if (localForward < 0 && dot <= 0) return false; // Moving away from back side - - return true; + @Override + public float getMaxExtent() { + return Math.max(panelData.panelWidth, panelData.panelHeight) * 0.5f + 1.0f; } // ==================== CHARGING ==================== @@ -271,23 +371,38 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { setCharging(false); } - // ==================== KNOCKBACK ==================== + // ==================== ENTITY PHYSICS (Solid + Knockback) ==================== /** - * Push entities away from the panel surface. + * Processes entity physics for the panel barrier. Two independent systems: + *

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

+ * KNOCKBACK: Repulsion force — entities near the panel surface get pushed away. + * This is a push effect only; entities can still pass through with enough effort. + * Does NOT prevent passthrough — use solid for that. */ @Override @SuppressWarnings("unchecked") - protected void knockbackEntities() { + protected void processEntityPhysics() { float halfW = panelData.panelWidth * 0.5f; float halfH = panelData.panelHeight * 0.5f; - float margin = 1.0f; + float searchExtension = 3.0f; + boolean solid = barrierData.solid; + boolean knockback = barrierData.knockbackEnabled; + float strength = barrierData.knockbackStrength; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - halfW - margin, posY - halfH - margin, posZ - halfW - margin, - posX + halfW + margin, posY + halfH + margin, posZ + halfW + margin + posX - halfW - searchExtension, posY - halfH - searchExtension, posZ - halfW - searchExtension, + posX + halfW + searchExtension, posY + halfH + searchExtension, posZ + halfW + searchExtension ); + // On client, identify local player for client-side solid prediction + EntityPlayer localPlayer = worldObj.isRemote ? CustomNpcs.proxy.getPlayer() : null; + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); float yawRad = (float) Math.toRadians(panelYaw); float normalX = -(float) Math.sin(yawRad); @@ -295,46 +410,87 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { for (EntityLivingBase ent : entities) { if (ent.getEntityId() == ownerEntityId) continue; - if (!isKnockbackTarget(ent)) continue; + if (isAllyOfOwner(ent)) continue; - // Transform entity position to panel-local space + // Client-side: only process local player for solid prediction + if (worldObj.isRemote && (localPlayer == null || ent != localPlayer)) continue; + + // Current position relative to panel center double dx = ent.posX - posX; double dy = (ent.posY + ent.height * 0.5) - posY; double dz = ent.posZ - posZ; - // Check proximity to panel surface + // Panel-local coordinates float localForward = (float) (dx * normalX + dz * normalZ); float localRight = (float) (dx * (-normalZ) + dz * normalX); - if (Math.abs(localForward) < margin && Math.abs(localRight) < halfW + margin && Math.abs(dy) < halfH + margin) { - // Push entity away from the panel face - float pushDir = localForward >= 0 ? 1.0f : -1.0f; - double pushStrength = barrierData.knockbackStrength * 0.5; - ent.addVelocity( - normalX * pushDir * pushStrength, - 0.1, - normalZ * pushDir * pushStrength - ); - ent.velocityChanged = true; + // Skip if outside panel bounds (with margin) + if (Math.abs(localRight) > halfW + 1.0f) continue; + if (Math.abs(dy) > halfH + 1.0f) continue; + if (Math.abs(localForward) > searchExtension) continue; + + // Determine which side the entity is on + float side = localForward >= 0 ? 1.0f : -1.0f; + + // Check if within panel width/height bounds + boolean inBounds = Math.abs(localRight) <= halfW && Math.abs(dy) <= halfH; + + // --- SOLID: hard wall preventing plane crossing --- + if (solid && inBounds) { + // Previous tick: entity position relative to panel + double prevDx = ent.prevPosX - prevPosX; + double prevDz = ent.prevPosZ - prevPosZ; + float prevLocalForward = (float) (prevDx * normalX + prevDz * normalZ); + float prevSide = prevLocalForward >= 0 ? 1.0f : -1.0f; + + // Normal velocity component (positive = moving in normal direction) + double normalVel = ent.motionX * normalX + ent.motionZ * normalZ; + + if (prevSide != side) { + // Entity crossed the panel plane this tick — push back to original side + double pushDist = 0.3; + double newX = posX + normalX * prevSide * pushDist + (localRight * (-normalZ)); + double newZ = posZ + normalZ * prevSide * pushDist + (localRight * normalX); + teleportEntity(ent, newX, ent.posY, newZ); + + // Cancel normal velocity and add corrective push + ent.motionX -= normalVel * normalX; + ent.motionZ -= normalVel * normalZ; + ent.motionX += normalX * prevSide * 0.15; + ent.motionZ += normalZ * prevSide * 0.15; + ent.velocityChanged = true; + } else { + // Preemptive: near the plane and moving toward it — cancel normal velocity + double absDist = Math.abs(localForward); + if (absDist < 1.5) { + boolean movingToward = (side > 0 && normalVel < -0.01) + || (side < 0 && normalVel > 0.01); + if (movingToward) { + ent.motionX -= normalVel * normalX; + ent.motionZ -= normalVel * normalZ; + ent.motionX += normalX * side * 0.05; + ent.motionZ += normalZ * side * 0.05; + ent.velocityChanged = true; + } + } + } + } + + // --- KNOCKBACK: repulsion push (server only, synced via velocityChanged) --- + if (!worldObj.isRemote && knockback && inBounds) { + double absDist = Math.abs(localForward); + if (absDist < searchExtension) { + double proximity = 1.0 - (absDist / searchExtension); + double force = proximity * strength * 0.06; + ent.motionX += normalX * side * force; + ent.motionZ += normalZ * side * force; + ent.velocityChanged = true; + } } } } - // ==================== BOUNDING BOX ==================== - - @Override - public AxisAlignedBB getBoundingBox() { - if (barrierData.meleeEnabled) { - float halfW = panelData.panelWidth * 0.5f; - float halfH = panelData.panelHeight * 0.5f; - float extent = Math.max(halfW, 0.5f); - return AxisAlignedBB.getBoundingBox( - posX - extent, posY - halfH, posZ - extent, - posX + extent, posY + halfH, posZ + extent - ); - } - return null; - } + // ==================== RENDER ==================== @Override @SideOnly(Side.CLIENT) @@ -395,6 +551,10 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { return panelYaw; } + public float getPrevPanelYaw() { + return prevPanelYaw; + } + public EnergyPanelData getPanelData() { return panelData; } @@ -403,6 +563,26 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeBarrierBaseNBT(nbt); + nbt.setFloat("PanelYaw", panelYaw); + nbt.setInteger("PanelMode", mode.ordinal()); + nbt.setFloat("TargetPanelWidth", targetPanelWidth); + nbt.setFloat("TargetPanelHeight", targetPanelHeight); + panelData.writeNBT(nbt); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { readBarrierBaseNBT(nbt); this.panelYaw = nbt.getFloat("PanelYaw"); int modeOrdinal = nbt.getInteger("PanelMode"); @@ -414,14 +594,4 @@ public class EntityEnergyPanel extends EntityEnergyBarrier { 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 - protected void writeEntityToNBT(NBTTagCompound nbt) { - writeBarrierBaseNBT(nbt); - nbt.setFloat("PanelYaw", panelYaw); - nbt.setInteger("PanelMode", mode.ordinal()); - nbt.setFloat("TargetPanelWidth", targetPanelWidth); - nbt.setFloat("TargetPanelHeight", targetPanelHeight); - panelData.writeNBT(nbt); - } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index fd739876d..f08ffeb2a 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -34,7 +34,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { // Beam properties private float beamLength = 10.0f; private float beamWidth = 0.3f; // Thin like beam trail - private float beamHeight = 0.8f; + private float beamHeight = 1.0f; // Combat properties private float damage = 5.0f; @@ -100,8 +100,8 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { this.baseYaw = owner.rotationYaw; } - // Position at owner - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + // Position at beam center (bottom at feet, top at feet + beamHeight) + this.setPosition(owner.posX, owner.posY + beamHeight / 2.0, owner.posZ); // Ready to deal damage immediately this.ticksSinceDamage = damageInterval; @@ -149,7 +149,7 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { } if (owner != null) { - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + this.setPosition(owner.posX, owner.posY + beamHeight / 2.0, owner.posZ); } // Check if sweep is done @@ -204,10 +204,10 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { double checkY = startY; double checkZ = startZ + dirZ * beamLength * progress; - // Narrow hitbox for thin beam + // Hitbox: beam center ± half-height vertically, generous width for thin beams AxisAlignedBB checkBox = AxisAlignedBB.getBoundingBox( - checkX - beamWidth * 2, checkY - 0.5, checkZ - beamWidth * 2, - checkX + beamWidth * 2, checkY + 1.0, checkZ + beamWidth * 2 + checkX - beamWidth * 2, checkY - beamHeight / 2.0, checkZ - beamWidth * 2, + checkX + beamWidth * 2, checkY + beamHeight / 2.0, checkZ + beamWidth * 2 ); @SuppressWarnings("unchecked") @@ -259,11 +259,14 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { return false; } - // Height check - entity's feet must be below beam top (allows jumping over) + // Height check - entity must overlap beam vertically + double beamTopY = startY + beamHeight / 2.0; + double beamBottomY = startY - beamHeight / 2.0; double entityFeetY = entity.posY; - double beamTopY = startY + 0.5; + double entityTopY = entity.posY + entity.height; - return entityFeetY < beamTopY; + // Entity feet must be below beam top AND entity top must be above beam bottom + return entityFeetY < beamTopY && entityTopY > beamBottomY; } /** @@ -363,10 +366,40 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + nbt.setFloat("BeamLength", beamLength); + nbt.setFloat("BeamWidth", beamWidth); + nbt.setFloat("BeamHeight", beamHeight); + nbt.setFloat("SweepSpeed", sweepSpeed); + nbt.setInteger("NumRotations", numberOfRotations); + nbt.setInteger("CompletedRotations", completedRotations); + nbt.setInteger("MaxTicks", maxTicks); + nbt.setInteger("TargetId", targetEntityId); + nbt.setFloat("CurrentAngle", currentAngle); + nbt.setFloat("BaseYaw", baseYaw); + nbt.setLong("DeathWorldTime", deathWorldTime); + nbt.setFloat("Damage", damage); + nbt.setInteger("DamageInterval", damageInterval); + nbt.setBoolean("Piercing", piercing); + nbt.setBoolean("LockOnTarget", lockOnTarget); + } + + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { readEnergyBaseNBT(nbt); this.beamLength = sanitize(nbt.getFloat("BeamLength"), 10.0f, MAX_ENTITY_SIZE); this.beamWidth = sanitize(nbt.getFloat("BeamWidth"), 0.3f, MAX_ENTITY_SIZE); - this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 0.8f, MAX_ENTITY_SIZE); + this.beamHeight = sanitize(nbt.getFloat("BeamHeight"), 1.0f, MAX_ENTITY_SIZE); this.sweepSpeed = nbt.hasKey("SweepSpeed") ? nbt.getFloat("SweepSpeed") : 3.0f; if (Float.isNaN(sweepSpeed) || Float.isInfinite(sweepSpeed) || sweepSpeed <= 0) sweepSpeed = 3.0f; this.numberOfRotations = nbt.hasKey("NumRotations") ? nbt.getInteger("NumRotations") : 2; @@ -386,24 +419,4 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { this.piercing = !nbt.hasKey("Piercing") || nbt.getBoolean("Piercing"); this.lockOnTarget = nbt.getBoolean("LockOnTarget"); } - - @Override - protected void writeEntityToNBT(NBTTagCompound nbt) { - writeEnergyBaseNBT(nbt); - nbt.setFloat("BeamLength", beamLength); - nbt.setFloat("BeamWidth", beamWidth); - nbt.setFloat("BeamHeight", beamHeight); - nbt.setFloat("SweepSpeed", sweepSpeed); - nbt.setInteger("NumRotations", numberOfRotations); - nbt.setInteger("CompletedRotations", completedRotations); - nbt.setInteger("MaxTicks", maxTicks); - nbt.setInteger("TargetId", targetEntityId); - nbt.setFloat("CurrentAngle", currentAngle); - nbt.setFloat("BaseYaw", baseYaw); - nbt.setLong("DeathWorldTime", deathWorldTime); - nbt.setFloat("Damage", damage); - nbt.setInteger("DamageInterval", damageInterval); - nbt.setBoolean("Piercing", piercing); - nbt.setBoolean("LockOnTarget", lockOnTarget); - } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java index a3aa494b4..129b87495 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -1,6 +1,6 @@ package kamkeel.npcs.entity; -import cpw.mods.fml.common.network.ByteBufUtils; +import kamkeel.npcs.util.ByteBufUtils; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -716,130 +716,12 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - int zoneTypeOrd = nbt.getInteger("ZoneType"); - this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; - try { - this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); - } catch (Exception e) { - this.shape = ZoneShape.CIRCLE; - } - - this.ownerEntityId = nbt.getInteger("OwnerId"); - this.radius = nbt.hasKey("Radius") ? nbt.getFloat("Radius") : 4.0f; - this.durationTicks = nbt.hasKey("Duration") ? nbt.getInteger("Duration") : 200; - this.maxTicks = nbt.hasKey("MaxTicks") ? nbt.getInteger("MaxTicks") : 200; - this.innerColor = nbt.hasKey("InnerColor") ? nbt.getInteger("InnerColor") : 0xFF6600; - this.outerColor = nbt.hasKey("OuterColor") ? nbt.getInteger("OuterColor") : 0xFF0000; - this.outerColorEnabled = !nbt.hasKey("OuterColorEnabled") || nbt.getBoolean("OuterColorEnabled"); - this.zoneHeight = nbt.hasKey("ZoneHeight") ? nbt.getFloat("ZoneHeight") : 2.0f; - this.particleDensity = nbt.hasKey("ParticleDensity") ? nbt.getFloat("ParticleDensity") : 1.0f; - this.particleScale = nbt.hasKey("ParticleScale") ? nbt.getFloat("ParticleScale") : 1.0f; - this.animSpeed = nbt.hasKey("AnimSpeed") ? nbt.getFloat("AnimSpeed") : 1.0f; - this.lightningDensity = nbt.hasKey("LightningDensity") ? nbt.getFloat("LightningDensity") : 1.0f; - this.deathWorldTime = nbt.getLong("DeathWorldTime"); - - // Visual layer fields - this.groundFill = nbt.getBoolean("GroundFill"); - this.groundAlpha = nbt.getFloat("GroundAlpha"); - this.rings = nbt.getBoolean("Rings"); - this.ringCount = nbt.getInteger("RingCount"); - this.border = nbt.getBoolean("Border"); - this.borderSpeed = nbt.getFloat("BorderSpeed"); - this.accents = nbt.getBoolean("Accents"); - this.accentStyle = nbt.getInteger("AccentStyle"); - this.lightning = nbt.getBoolean("Lightning"); - this.particles = nbt.getBoolean("Particles"); - this.particleMotion = nbt.getInteger("ParticleMotion"); - this.particleDir = nbt.getString("ParticleDir"); - this.particleSize = nbt.getInteger("ParticleSize"); - this.particleGlow = nbt.getBoolean("ParticleGlow"); - - // Trap - this.armTime = nbt.getInteger("ArmTime"); - this.triggerRadius = nbt.getFloat("TriggerRadius"); - this.maxTriggers = nbt.getInteger("MaxTriggers"); - this.triggerCooldown = nbt.getInteger("TriggerCooldown"); - this.damage = nbt.getFloat("Damage"); - this.damageRadius = nbt.getFloat("DamageRadius"); - this.knockback = nbt.getFloat("Knockback"); - this.visible = nbt.getBoolean("Visible"); - - // Hazard - this.damagePerSecond = nbt.hasKey("DamagePerSecond") ? nbt.getFloat("DamagePerSecond") : 1.0f; - this.damageInterval = nbt.hasKey("DamageInterval") ? nbt.getInteger("DamageInterval") : 20; - if (damageInterval <= 0) damageInterval = 1; - this.ignoreInvulnFrames = nbt.getBoolean("IgnoreInvuln"); - this.affectsCaster = nbt.getBoolean("AffectsCaster"); - - // Effects - effects.clear(); - if (nbt.hasKey("Effects")) { - NBTTagList effectList = nbt.getTagList("Effects", 10); - for (int i = 0; i < effectList.tagCount(); i++) { - AbilityPotionEffect effect = AbilityPotionEffect.fromNBT(effectList.getCompoundTagAt(i)); - if (effect != null && effect.isValid()) { - effects.add(effect); - } - } - } + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { - nbt.setInteger("ZoneType", zoneType.ordinal()); - nbt.setString("ShapeName", shape.name()); - nbt.setInteger("OwnerId", ownerEntityId); - nbt.setFloat("Radius", radius); - nbt.setInteger("Duration", durationTicks); - nbt.setInteger("MaxTicks", maxTicks); - nbt.setInteger("InnerColor", innerColor); - nbt.setInteger("OuterColor", outerColor); - nbt.setBoolean("OuterColorEnabled", outerColorEnabled); - nbt.setFloat("ZoneHeight", zoneHeight); - nbt.setFloat("ParticleDensity", particleDensity); - nbt.setFloat("ParticleScale", particleScale); - nbt.setFloat("AnimSpeed", animSpeed); - nbt.setFloat("LightningDensity", lightningDensity); - nbt.setLong("DeathWorldTime", deathWorldTime); - - // Visual layer fields - nbt.setBoolean("GroundFill", groundFill); - nbt.setFloat("GroundAlpha", groundAlpha); - nbt.setBoolean("Rings", rings); - nbt.setInteger("RingCount", ringCount); - nbt.setBoolean("Border", border); - nbt.setFloat("BorderSpeed", borderSpeed); - nbt.setBoolean("Accents", accents); - nbt.setInteger("AccentStyle", accentStyle); - nbt.setBoolean("Lightning", lightning); - nbt.setBoolean("Particles", particles); - nbt.setInteger("ParticleMotion", particleMotion); - nbt.setString("ParticleDir", particleDir); - nbt.setInteger("ParticleSize", particleSize); - nbt.setBoolean("ParticleGlow", particleGlow); - - // Trap - nbt.setInteger("ArmTime", armTime); - nbt.setFloat("TriggerRadius", triggerRadius); - nbt.setInteger("MaxTriggers", maxTriggers); - nbt.setInteger("TriggerCooldown", triggerCooldown); - nbt.setFloat("Damage", damage); - nbt.setFloat("DamageRadius", damageRadius); - nbt.setFloat("Knockback", knockback); - nbt.setBoolean("Visible", visible); - - // Hazard - nbt.setFloat("DamagePerSecond", damagePerSecond); - nbt.setInteger("DamageInterval", damageInterval); - nbt.setBoolean("IgnoreInvuln", ignoreInvulnFrames); - nbt.setBoolean("AffectsCaster", affectsCaster); - - // Effects - NBTTagList effectList = new NBTTagList(); - for (AbilityPotionEffect effect : effects) { - effectList.appendTag(effect.writeNBT()); - } - nbt.setTag("Effects", effectList); + // Intentionally empty — ability entities are transient (not saved to world) } // ═══════════════════════════════════════════════════════════════════ @@ -849,7 +731,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD @Override public void writeSpawnData(ByteBuf buffer) { buffer.writeInt(zoneType.ordinal()); - ByteBufUtils.writeUTF8String(buffer, shape.name()); + ByteBufUtils.writeString(buffer, shape.name()); buffer.writeInt(ownerEntityId); buffer.writeFloat(radius); buffer.writeInt(durationTicks); @@ -875,7 +757,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD buffer.writeBoolean(lightning); buffer.writeBoolean(particles); buffer.writeInt(particleMotion); - ByteBufUtils.writeUTF8String(buffer, particleDir); + ByteBufUtils.writeString(buffer, particleDir); buffer.writeInt(particleSize); buffer.writeBoolean(particleGlow); @@ -890,14 +772,18 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD effectList.appendTag(effect.writeNBT()); } effectsNbt.setTag("Effects", effectList); - ByteBufUtils.writeTag(buffer, effectsNbt); + try { + ByteBufUtils.writeNBT(buffer, effectsNbt); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error writing zone effects spawn data", e); + } } @Override public void readSpawnData(ByteBuf buffer) { int zoneTypeOrd = buffer.readInt(); this.zoneType = (zoneTypeOrd >= 0 && zoneTypeOrd < ZoneType.values().length) ? ZoneType.values()[zoneTypeOrd] : ZoneType.TRAP; - String shapeName = ByteBufUtils.readUTF8String(buffer); + String shapeName = ByteBufUtils.readString(buffer); try { this.shape = ZoneShape.valueOf(shapeName); } catch (Exception e) { @@ -928,7 +814,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.lightning = buffer.readBoolean(); this.particles = buffer.readBoolean(); this.particleMotion = buffer.readInt(); - this.particleDir = ByteBufUtils.readUTF8String(buffer); + this.particleDir = ByteBufUtils.readString(buffer); this.particleSize = buffer.readInt(); this.particleGlow = buffer.readBoolean(); @@ -936,7 +822,12 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD this.visible = buffer.readBoolean(); // Effects - NBTTagCompound effectsNbt = ByteBufUtils.readTag(buffer); + NBTTagCompound effectsNbt = null; + try { + effectsNbt = ByteBufUtils.readNBT(buffer); + } catch (java.io.IOException e) { + noppes.npcs.LogWriter.error("Error reading zone effects spawn data", e); + } effects.clear(); if (effectsNbt != null && effectsNbt.hasKey("Effects")) { NBTTagList effectList = effectsNbt.getTagList("Effects", 10); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java index 2546fb8a2..585eadc7d 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java @@ -7,6 +7,7 @@ import io.netty.buffer.ByteBuf; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; +import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -314,12 +315,30 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit // ==================== SPAWN DATA ==================== + /** + * Write entity data for client sync. Subclasses override this + * to serialize their fields. Separate from writeEntityToNBT + * which is intentionally empty (entities are transient, not saved to world). + */ + protected void writeSpawnNBT(NBTTagCompound nbt) { + writeEnergyBaseNBT(nbt); + } + + /** + * Read entity data from client sync. Subclasses override this + * to deserialize their fields. Separate from readEntityFromNBT + * which is intentionally empty (entities are transient, not saved to world). + */ + protected void readSpawnNBT(NBTTagCompound nbt) { + readEnergyBaseNBT(nbt); + } + @Override public void writeSpawnData(ByteBuf buffer) { try { NBTTagCompound compound = new NBTTagCompound(); - this.writeEntityToNBT(compound); - cpw.mods.fml.common.network.ByteBufUtils.writeTag(buffer, compound); + this.writeSpawnNBT(compound); + ByteBufUtils.writeNBT(buffer, compound); } catch (Exception e) { noppes.npcs.LogWriter.error("Error writing energy ability spawn data", e); } @@ -328,9 +347,9 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit @Override public void readSpawnData(ByteBuf buffer) { try { - NBTTagCompound compound = cpw.mods.fml.common.network.ByteBufUtils.readTag(buffer); + NBTTagCompound compound = ByteBufUtils.readNBT(buffer); if (compound != null) { - this.readEntityFromNBT(compound); + this.readSpawnNBT(compound); } } catch (Exception e) { noppes.npcs.LogWriter.error("Error reading energy ability spawn data", e); diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java deleted file mode 100644 index 782413435..000000000 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java +++ /dev/null @@ -1,284 +0,0 @@ -package kamkeel.npcs.entity; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.data.EnergyBarrierData; -import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.DamageSource; -import net.minecraft.world.World; - -import java.util.List; - -/** - * Energy Dome entity - a spherical barrier that blocks incoming energy projectiles. - * Centered on the caster's position at time of casting. - * Only blocks incoming attacks (not outgoing from allies inside). - * Extends EntityEnergyBarrier for shared barrier logic. - */ -public class EntityEnergyDome extends EntityEnergyBarrier { - - // ==================== DOME-SPECIFIC PROPERTIES ==================== - protected float domeRadius = 5.0f; - protected float targetDomeRadius = 5.0f; - protected boolean followCaster = false; - - public EntityEnergyDome(World world) { - super(world); - 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.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 - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - - super.onUpdate(); - - // Follow caster: both sides for smooth interpolated rendering - if (followCaster) { - Entity owner = ownerEntityId >= 0 ? worldObj.getEntityByID(ownerEntityId) : null; - if (owner != null) { - this.setPosition(owner.posX, owner.posY, owner.posZ); - } - } - - // Handle charging animation (both sides for smooth rendering) - if (isCharging()) { - chargeTick++; - float progress = getChargeProgress(); - this.domeRadius = targetDomeRadius * progress; - return; // Don't tick duration/death during charging - } - - ticksAlive++; - - if (updateBarrierTick()) return; - - // Knockback entities inside the dome - if (!worldObj.isRemote && barrierData.knockbackEnabled) { - knockbackEntities(); - } - } - - // ==================== INCOMING CHECK ==================== - - /** - * Check if a projectile at the given position is entering this dome from outside. - * Only blocks incoming projectiles (dot product check). - */ - @Override - public boolean isIncomingProjectile(EntityEnergyProjectile projectile) { - // Don't block during charging phase - if (isCharging()) return false; - // Don't block projectiles from the dome's owner - if (projectile.getOwnerEntityId() == this.ownerEntityId) return false; - - // Don't block projectiles from same-faction NPCs - Entity owner = getOwnerEntity(); - Entity projOwner = projectile.getOwnerEntity(); - if (owner instanceof noppes.npcs.entity.EntityNPCInterface && projOwner instanceof noppes.npcs.entity.EntityNPCInterface) { - if (((noppes.npcs.entity.EntityNPCInterface) owner).faction.id == ((noppes.npcs.entity.EntityNPCInterface) projOwner).faction.id) { - return false; - } - } - - double dx = projectile.posX - this.posX; - double dy = projectile.posY - this.posY; - double dz = projectile.posZ - this.posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - - // Check if projectile is outside dome radius - if (dist > domeRadius) return false; - - // 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; - return dot < 0; - } - - // ==================== CHARGING ==================== - - @Override - public void setupCharging(int duration) { - this.targetDomeRadius = this.domeRadius; - this.domeRadius = 0.01f; - this.chargeDuration = duration; - this.chargeTick = 0; - setCharging(true); - } - - @Override - public void finishCharging() { - this.domeRadius = targetDomeRadius; - setCharging(false); - } - - // ==================== KNOCKBACK ==================== - - /** - * Push entities away from the dome surface. - * Entities outside are pushed outward, entities inside are pushed inward (containment). - */ - @Override - @SuppressWarnings("unchecked") - protected void knockbackEntities() { - float margin = 1.0f; - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - domeRadius - margin, posY - domeRadius - margin, posZ - domeRadius - margin, - posX + domeRadius + margin, posY + domeRadius + margin, posZ + domeRadius + margin - ); - - List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); - for (EntityLivingBase ent : entities) { - if (ent.getEntityId() == ownerEntityId) continue; - if (!isKnockbackTarget(ent)) continue; - - double dx = ent.posX - posX; - double dy = (ent.posY + ent.height * 0.5) - posY; - double dz = ent.posZ - posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (dist < 0.01) continue; - - // Only affect entities near the dome surface - if (dist < domeRadius + margin && dist > domeRadius - margin) { - double pushStrength = barrierData.knockbackStrength * 0.5; - double pushDir = dist >= domeRadius ? 1.0 : -1.0; // Outside = outward, Inside = inward - ent.addVelocity( - (dx / dist) * pushStrength * pushDir, - 0.05 * pushDir, - (dz / dist) * pushStrength * pushDir - ); - ent.velocityChanged = true; - } - } - } - - // ==================== 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 float getCollisionBorderSize() { - return domeRadius; - } - - @Override - @SideOnly(Side.CLIENT) - public boolean isInRangeToRenderDist(double distance) { - double d = domeRadius * 8.0D; - d *= 64.0D; - 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() { - return domeRadius; - } - - public void setDomeRadius(float radius) { - this.domeRadius = Math.max(0.1f, radius); - } - - public boolean isFollowCaster() { - return followCaster; - } - - public void setFollowCaster(boolean follow) { - this.followCaster = follow; - } - - // ==================== NBT ==================== - - @Override - protected void readEntityFromNBT(NBTTagCompound nbt) { - readBarrierBaseNBT(nbt); - 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"); - } - - @Override - protected void writeEntityToNBT(NBTTagCompound nbt) { - writeBarrierBaseNBT(nbt); - nbt.setFloat("DomeRadius", domeRadius); - nbt.setFloat("TargetDomeRadius", targetDomeRadius); - nbt.setBoolean("FollowCaster", followCaster); - } -} diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index 4f0c16e50..5e48a468f 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -318,19 +318,21 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { * @return true if projectile was absorbed (caller should stop processing) */ protected boolean checkBarrierCollision() { - // Search range must cover the largest possible barrier (dome radius up to MAX_ENTITY_RADIUS) - double searchRange = MAX_ENTITY_RADIUS + 5; - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - posX - searchRange, posY - searchRange, posZ - searchRange, - posX + searchRange, posY + searchRange, posZ + searchRange - ); - - @SuppressWarnings("unchecked") - List barriers = worldObj.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); - for (EntityEnergyBarrier barrier : barriers) { + List barriers = EntityAbilityBarrier.getActiveBarriers(worldObj); + for (EntityAbilityBarrier barrier : barriers) { if (barrier.isDead) continue; + + // Quick distance pre-filter + double dx = barrier.posX - this.posX; + double dy = barrier.posY - this.posY; + double dz = barrier.posZ - this.posZ; + double distSq = dx * dx + dy * dy + dz * dz; + double maxRange = barrier.getMaxExtent() + 5.0; + if (distSq > maxRange * maxRange) continue; + if (barrier.isIncomingProjectile(this)) { - if (barrier.onProjectileHit(this, getDamage())) { + float damage = getModifiedDamage(); + if (barrier.onProjectileHit(this, damage)) { hasHit = true; this.setDead(); return true; @@ -341,6 +343,22 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { return false; } + /** + * Get the projectile damage modified by extenders (e.g. DBC damage scaling). + * Falls back to base getDamage() when no sourceAbility or no extenders modify it. + */ + protected float getModifiedDamage() { + float damage = getDamage(); + if (sourceAbility != null) { + Entity owner = getOwnerEntity(); + if (owner instanceof EntityLivingBase) { + damage = AbilityController.Instance.fireModifyProjectileDamage( + sourceAbility, (EntityLivingBase) owner, damage); + } + } + return damage; + } + // ==================== POSITION INTERPOLATION ==================== @Override @@ -908,16 +926,26 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { @Override protected void readEntityFromNBT(NBTTagCompound nbt) { - readBaseNBT(nbt); - readProjectileNBT(nbt); + // Intentionally empty — ability entities are transient (not saved to world) } @Override protected void writeEntityToNBT(NBTTagCompound nbt) { + // Intentionally empty — ability entities are transient (not saved to world) + } + + @Override + protected void writeSpawnNBT(NBTTagCompound nbt) { writeBaseNBT(nbt); writeProjectileNBT(nbt); } + @Override + protected void readSpawnNBT(NBTTagCompound nbt) { + readBaseNBT(nbt); + readProjectileNBT(nbt); + } + /** * Read base projectile properties from NBT. */ diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index c3c555d48..8e784b5b8 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -8,24 +8,9 @@ import cpw.mods.fml.common.network.internal.FMLProxyPacket; import cpw.mods.fml.relauncher.Side; import io.netty.buffer.ByteBuf; import kamkeel.npcs.network.enums.EnumChannelType; -import kamkeel.npcs.network.packets.data.AchievementPacket; -import kamkeel.npcs.network.packets.data.ChatAlertPacket; -import kamkeel.npcs.network.packets.data.ChatBubblePacket; -import kamkeel.npcs.network.packets.data.ClonerPacket; -import kamkeel.npcs.network.packets.data.ConfigCommandPacket; -import kamkeel.npcs.network.packets.data.DisableMouseInputPacket; -import kamkeel.npcs.network.packets.data.LoginPacket; -import kamkeel.npcs.network.packets.data.MarkDataPacket; -import kamkeel.npcs.network.packets.data.OverlayQuestTrackingPacket; -import kamkeel.npcs.network.packets.data.ParticlePacket; -import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket; -import kamkeel.npcs.network.packets.data.PlayerUpdateSkinOverlaysPacket; -import kamkeel.npcs.network.packets.data.QuestCompletionPacket; -import kamkeel.npcs.network.packets.data.ScrollSelectedPacket; -import kamkeel.npcs.network.packets.data.SoundManagementPacket; -import kamkeel.npcs.network.packets.data.SwingPlayerArmPacket; -import kamkeel.npcs.network.packets.data.UpdateAnimationsPacket; -import kamkeel.npcs.network.packets.data.VillagerListPacket; +import kamkeel.npcs.network.packets.data.*; +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.gui.GuiClosePacket; @@ -54,6 +39,9 @@ import kamkeel.npcs.network.packets.data.script.ScriptedParticlePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; import kamkeel.npcs.network.packets.player.AuctionActionPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityTogglePacket; import kamkeel.npcs.network.packets.player.BankActionPacket; import kamkeel.npcs.network.packets.player.CheckPlayerValue; import kamkeel.npcs.network.packets.player.CompanionActionPacket; @@ -578,6 +566,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new DialogPacket()); DATA_PACKET.registerPacket(new RolePacket()); DATA_PACKET.registerPacket(new WeaponNpcPacket()); + DATA_PACKET.registerPacket(new RequestProperSpawnData()); // Data | Script Packets DATA_PACKET.registerPacket(new ScriptedParticlePacket()); @@ -598,6 +587,8 @@ public class PacketHandler { DATA_PACKET.registerPacket(new TelegraphRemovePacket()); DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); + DATA_PACKET.registerPacket(new AbilityHotbarSyncPacket()); + DATA_PACKET.registerPacket(new AbilityCooldownSyncPacket()); } public void registerPlayerPackets() { @@ -663,6 +654,11 @@ public class PacketHandler { PLAYER_PACKET.registerPacket(new PartyAcceptInvitePacket()); PLAYER_PACKET.registerPacket(new PartyIgnoreInvitePacket()); PLAYER_PACKET.registerPacket(new PartyLogToServerPacket()); + + // Ability Hotbar Packets + PLAYER_PACKET.registerPacket(new AbilityHotbarSavePacket()); + PLAYER_PACKET.registerPacket(new AbilityHotbarSelectPacket()); + PLAYER_PACKET.registerPacket(new AbilityTogglePacket()); } public void registerChannels() { diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index 8362cb3c5..ec351a2c9 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -23,6 +23,7 @@ public enum EnumDataPacket { DELETE_NPC, CLONE_NPC, WEAPON_NPC, + REQUEST_SPAWN_DATA, // Data SCROLL_LIST, @@ -64,6 +65,8 @@ public enum EnumDataPacket { TELEGRAPH_REMOVE, PLAYER_ABILITY_SYNC, PLAYER_ABILITY_STATE, + ABILITY_HOTBAR_SYNC, + ABILITY_COOLDOWN_SYNC, // Auction System AUCTION_DATA, diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java index 48f400fb2..e1587467b 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumPlayerPacket.java @@ -37,4 +37,9 @@ public enum EnumPlayerPacket { // Auction AuctionAction, + + // Ability Hotbar + AbilityHotbarSave, + AbilityHotbarSelect, + AbilityToggle, } diff --git a/src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java b/src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java new file mode 100644 index 000000000..afd013a74 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/RequestProperSpawnData.java @@ -0,0 +1,119 @@ +package kamkeel.npcs.network.packets.data; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.LogWriter; +import noppes.npcs.entity.EntityNPCInterface; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class RequestProperSpawnData extends AbstractPacket { + public static final String packetName = "Data|SpawnData"; + private static final int BATCH_LIMIT = 5; + + @SideOnly(Side.CLIENT) + private static final Set entitiesToFix = new HashSet<>(); + @SideOnly(Side.CLIENT) + private static long lastBatchAttemptMillis = 0; + + private int entityId; + + public RequestProperSpawnData() {} + + @SideOnly(Side.CLIENT) + public RequestProperSpawnData(int entityId) { + this.entityId = entityId; + } + + public static void clear() { + entitiesToFix.clear(); + } + + @Override + public Enum getType() { + return EnumDataPacket.REQUEST_SPAWN_DATA; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + @SideOnly(Side.CLIENT) + public void sendData(ByteBuf out) throws IOException { + out.writeInt(this.entityId); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + return; + + int entityId = in.readInt(); + Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(entityId); + if (entity instanceof EntityNPCInterface) { + EntityNPCInterface npc = (EntityNPCInterface) entity; + NBTTagCompound compound = npc.writeSpawnData(); + compound.setInteger("EntityId", npc.getEntityId()); + PacketHandler.Instance.sendToPlayer(new UpdateNpcPacket(compound), (EntityPlayerMP) player); + } + } + + @SideOnly(Side.CLIENT) + public static void reportMissingData(EntityNPCInterface npc) { + int entityID = npc.getEntityId(); + + if (npc.immediateSpawnDataFixAttempts++ < 3) { + PacketClient.sendClient(new RequestProperSpawnData(entityID)); + } else { + entitiesToFix.add(entityID); + } + } + + @SideOnly(Side.CLIENT) + public static boolean canDoBatchUpdate() { + return System.currentTimeMillis() - lastBatchAttemptMillis >= 5000; + } + + @SideOnly(Side.CLIENT) + public static void handleBacklog() { + Minecraft mc = Minecraft.getMinecraft(); + if (mc == null || mc.theWorld == null || mc.thePlayer == null) + return; + + if (entitiesToFix.isEmpty()) + return; + // Remove entity checks if they're no longer loaded + entitiesToFix.removeIf( value -> !(Minecraft.getMinecraft().theWorld.getEntityByID(value) instanceof EntityNPCInterface) ); + + Iterator it = entitiesToFix.iterator(); + int count = 0; + + while (it.hasNext() && count < BATCH_LIMIT) { + PacketClient.sendClient(new RequestProperSpawnData(it.next())); + it.remove(); + count++; + } + + if (count != 0) { + lastBatchAttemptMillis = System.currentTimeMillis(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java new file mode 100644 index 000000000..484cc602c --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityCooldownSyncPacket.java @@ -0,0 +1,109 @@ +package kamkeel.npcs.network.packets.data.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Lightweight packet that syncs cooldown state (global + per-ability) to the client. + * Sent when cooldowns are rolled, reset, or on login. + */ +public final class AbilityCooldownSyncPacket extends AbstractPacket { + public static final String packetName = "Data|AbilityCooldownSync"; + + private long globalCooldownEndTime; + private int globalCooldownDuration; + private HashMap perAbilityCooldownEndTimes; + private HashMap perAbilityCooldownDurations; + + public AbilityCooldownSyncPacket() { + } + + public AbilityCooldownSyncPacket(long globalEndTime, int globalDuration, + HashMap perEndTimes, + HashMap perDurations) { + this.globalCooldownEndTime = globalEndTime; + this.globalCooldownDuration = globalDuration; + this.perAbilityCooldownEndTimes = perEndTimes; + this.perAbilityCooldownDurations = perDurations; + } + + @Override + public Enum getType() { + return EnumDataPacket.ABILITY_COOLDOWN_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeLong(globalCooldownEndTime); + out.writeInt(globalCooldownDuration); + + // Write per-ability cooldowns + int count = perAbilityCooldownEndTimes != null ? perAbilityCooldownEndTimes.size() : 0; + out.writeInt(count); + if (count > 0) { + for (Map.Entry entry : perAbilityCooldownEndTimes.entrySet()) { + ByteBufUtils.writeUTF8String(out, entry.getKey()); + out.writeLong(entry.getValue()); + Integer dur = perAbilityCooldownDurations.get(entry.getKey()); + out.writeInt(dur != null ? dur : 0); + } + } + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + long globalEndTime = in.readLong(); + int globalDuration = in.readInt(); + + int count = in.readInt(); + HashMap perEndTimes = new HashMap<>(); + HashMap perDurations = new HashMap<>(); + for (int i = 0; i < count; i++) { + String key = ByteBufUtils.readUTF8String(in); + long endTime = in.readLong(); + int duration = in.readInt(); + perEndTimes.put(key, endTime); + perDurations.put(key, duration); + } + + PlayerData data = PlayerData.get(player); + if (data != null && data.abilityData != null) { + data.abilityData.applyCooldownSync(globalEndTime, globalDuration, perEndTimes, perDurations); + } + } + + /** + * Send the player's current cooldown state to their client. + */ + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null || data.abilityData == null) return; + + PacketHandler.Instance.sendToPlayer(new AbilityCooldownSyncPacket( + data.abilityData.getCooldownEndTime(), + data.abilityData.getGlobalCooldownDurationValue(), + data.abilityData.getPerAbilityCooldownEndTimes(), + data.abilityData.getPerAbilityCooldownDurations() + ), player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java new file mode 100644 index 000000000..a30682ecc --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/AbilityHotbarSyncPacket.java @@ -0,0 +1,101 @@ +package kamkeel.npcs.network.packets.data.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerAbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSyncPacket extends AbstractPacket { + public static final String packetName = "Data|AbilityHotbarSync"; + + private NBTTagCompound hotbarNBT; + + public AbilityHotbarSyncPacket() { + } + + public AbilityHotbarSyncPacket(NBTTagCompound hotbarNBT) { + this.hotbarNBT = hotbarNBT; + } + + @Override + public Enum getType() { + return EnumDataPacket.ABILITY_HOTBAR_SYNC; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeNBT(out, hotbarNBT); + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + NBTTagCompound nbt = ByteBufUtils.readNBT(in); + if (nbt == null) return; + + PlayerData data = ClientCacheHandler.playerData; + if (data != null) { + data.hotbarData.readFromNBT(nbt); + } + } + + public static void sendToPlayer(EntityPlayerMP player) { + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + PlayerAbilityHotbarData hotbarData = data.hotbarData; + boolean anyCleared = false; + + // Validate all slots before sending + if (AbilityController.Instance != null) { + for (int i = 0; i < hotbarData.slots.length; i++) { + AbilityHotbarData slot = hotbarData.slots[i]; + if (slot.isEmpty()) continue; + + boolean valid; + if (slot.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slot.abilityKey); + } + + if (valid && data.abilityData != null) { + valid = data.abilityData.hasUnlockedAbility(slot.abilityKey); + } + + if (!valid) { + slot.reset(); + anyCleared = true; + } + } + } + + NBTTagCompound nbt = new NBTTagCompound(); + hotbarData.writeToNBT(nbt); + PacketHandler.Instance.sendToPlayer(new AbilityHotbarSyncPacket(nbt), player); + + if (anyCleared) { + data.save(); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java index a58b896f4..3592e1a9a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -57,19 +57,19 @@ public final class SpecialKeyStatePacket extends AbstractPacket { boolean wasDown = data.isSpecialKeyDown(); data.setSpecialKeyDown(keyDown); - // Trigger ability activation on key press (rising edge) + // Trigger ability activation or cancel on key press (rising edge) if (keyDown && !wasDown) { - // Don't activate if player has a GUI open (not the default inventory) - if (player.openContainer != null && !(player.openContainer instanceof net.minecraft.inventory.ContainerPlayer)) { - return; - } - // Don't activate if player is riding an entity (mount) if (player.ridingEntity != null) { return; } - data.abilityData.activateAbility(player); + // If currently executing an ability, try to cancel via double-press + if (data.abilityData.isExecutingAbility() || data.abilityData.isExecutingChain()) { + data.abilityData.tryCancelAbility(); + } else { + data.abilityData.activateAbility(player); + } } } } diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java new file mode 100644 index 000000000..1522763fc --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSavePacket.java @@ -0,0 +1,86 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSavePacket extends AbstractPacket { + public static final String packetName = "Player|AbilityHotbarSave"; + + private int slotIndex; + private NBTTagCompound slotData; + + public AbilityHotbarSavePacket() { + } + + public AbilityHotbarSavePacket(int slotIndex, NBTTagCompound slotData) { + this.slotIndex = slotIndex; + this.slotData = slotData; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityHotbarSave; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(slotIndex); + ByteBufUtils.writeNBT(out, slotData); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + int slot = in.readInt(); + NBTTagCompound compound = ByteBufUtils.readNBT(in); + + if (slot < 0 || slot >= AbilityHotbarData.TOTAL_SLOTS) return; + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null) return; + + AbilityHotbarData slotData = data.hotbarData.getSlot(slot); + if (slotData == null) return; + + slotData.readFromNBT(compound.getCompoundTag("AbilityHotbar" + slot)); + + // Validate the ability key + boolean valid = true; + if (!slotData.isEmpty() && AbilityController.Instance != null) { + if (slotData.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slotData.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slotData.abilityKey); + } + + if (valid && data.abilityData != null) { + valid = data.abilityData.hasUnlockedAbility(slotData.abilityKey); + } + } + + if (!valid) { + slotData.reset(); + } + + data.save(); + AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java new file mode 100644 index 000000000..7a4e183a2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityHotbarSelectPacket.java @@ -0,0 +1,63 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityHotbarSelectPacket extends AbstractPacket { + public static final String packetName = "Player|AbilityHotbarSelect"; + + private String abilityKey; + + public AbilityHotbarSelectPacket() { + } + + public AbilityHotbarSelectPacket(String abilityKey) { + this.abilityKey = abilityKey; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityHotbarSelect; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityKey != null ? abilityKey : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String key = ByteBufUtils.readString(in); + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data == null || data.abilityData == null) return; + + if (key == null || key.isEmpty()) { + // Deselect + data.abilityData.setSelectedIndex(-1); + } else { + int index = data.abilityData.getUnlockedAbilityList().indexOf(key); + if (index >= 0) { + data.abilityData.setSelectedIndex(index); + } + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java new file mode 100644 index 000000000..f9f402c5e --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/player/ability/AbilityTogglePacket.java @@ -0,0 +1,72 @@ +package kamkeel.npcs.network.packets.player.ability; + +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.enums.EnumPlayerPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.StatCollector; +import noppes.npcs.controllers.data.PlayerData; + +import java.io.IOException; + +public final class AbilityTogglePacket extends AbstractPacket { + public static final String packetName = "Player|AbilityToggle"; + private String abilityKey; + + public AbilityTogglePacket() { + } + + public AbilityTogglePacket(String abilityKey) { + this.abilityKey = abilityKey; + } + + @Override + public Enum getType() { + return EnumPlayerPacket.AbilityToggle; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.PLAYER_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityKey != null ? abilityKey : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + String key = ByteBufUtils.readString(in); + if (key == null || key.isEmpty()) return; + if (AbilityController.Instance == null) return; + + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null || !ability.isToggleable() || !ability.getAllowedBy().allowsPlayer()) return; + + PlayerData playerData = PlayerData.get(player); + if (playerData == null || playerData.abilityData == null) return; + + int newState = playerData.abilityData.toggleAbility(key); + + String displayName = ability.getDisplayName(); + if (newState > 0) { + String stateLabel = ability.getToggleStateLabel(newState); + if (stateLabel != null) { + player.addChatMessage(new ChatComponentText("\u00A7a" + displayName + " " + stateLabel)); + } else { + String enabled = StatCollector.translateToLocal("gui.enabled"); + player.addChatMessage(new ChatComponentText("\u00A7a" + displayName + " " + enabled)); + } + } else { + String disabled = StatCollector.translateToLocal("gui.disabled"); + player.addChatMessage(new ChatComponentText("\u00A7c" + displayName + " " + disabled)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java index 9cc361b5d..74061d29c 100644 --- a/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java +++ b/src/main/java/kamkeel/npcs/util/AttributeItemUtil.java @@ -15,6 +15,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import noppes.npcs.client.ClientProxy; +import noppes.npcs.client.gui.player.GuiAuctionInterface; import noppes.npcs.controllers.MagicController; import noppes.npcs.controllers.data.Magic; import org.lwjgl.input.Keyboard; @@ -230,14 +231,14 @@ public class AttributeItemUtil { * Returns the item tooltip. */ @SideOnly(Side.CLIENT) - public static List getToolTip(List original, NBTTagCompound compound) { + public static List getToolTip(List original, NBTTagCompound compound, boolean override) { List tooltip = new ArrayList<>(original); // Get the RPGCore compound and then the Attributes compound. NBTTagCompound rpgCore = compound.hasKey(TAG_RPGCORE) ? compound.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound(); NBTTagCompound attrTag = rpgCore.hasKey(TAG_ATTRIBUTES) ? rpgCore.getCompoundTag(TAG_ATTRIBUTES) : new NBTTagCompound(); - if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode())) { + if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode()) || override) { List newTooltips = new ArrayList<>(); - if (!tooltip.isEmpty()) { + if (!tooltip.isEmpty() && !override) { newTooltips.add(tooltip.get(0)); } @@ -325,7 +326,11 @@ public class AttributeItemUtil { newTooltips.addAll(buildSection(reqEntries)); } - tooltip = newTooltips; + if(override){ + tooltip.addAll(newTooltips); + } else { + tooltip = newTooltips; + } } else { String keyName = Keyboard.getKeyName(ClientProxy.NPCButton.getKeyCode()); tooltip.add(EnumChatFormatting.YELLOW + "" + EnumChatFormatting.ITALIC + diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index eab517ce9..75184778d 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -4,6 +4,7 @@ import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.IEffectAction; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import noppes.npcs.LogWriter; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; @@ -207,4 +208,36 @@ public class Register { return new Register.EffectActions(namespace); } } + + public static class Conditions extends Register { + + private Conditions(String namespace) { + super("condition", namespace); + } + + public AbilityCondition register(String name, Supplier factory) { + entries.put(registryKey + "." + namespace + "." + name, factory); + return factory.get(); + } + + public void register() { + for (Map.Entry> entry : entries.entrySet()) { + AbilityController.Instance.registerCondition(entry.getValue()); + } + } + + public static Register.Conditions create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("condition")) + REGISTERED_NAMESPACES.put("condition", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("condition").contains(namespace)) { + LogWriter.error("REGISTER CONDITIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("condition").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.Conditions(namespace); + } + } } diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java index 240714738..b63481c21 100644 --- a/src/main/java/noppes/npcs/AbstractDataAbilities.java +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -14,6 +14,7 @@ import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -44,10 +45,25 @@ public abstract class AbstractDataAbilities { protected Ability currentAbility; /** - * World time when cooldown ends + * World time when global cooldown ends */ protected long cooldownEndTime = 0; + /** + * Duration of the current global cooldown in ticks (for progress calculation) + */ + protected int globalCooldownDuration = 0; + + /** + * Per-ability cooldown end times. Key = ability key, Value = world time when cooldown ends. + */ + protected HashMap perAbilityCooldownEndTimes = new HashMap<>(); + + /** + * Per-ability cooldown durations in ticks (for progress calculation). + */ + protected HashMap perAbilityCooldownDurations = new HashMap<>(); + /** * Rotation lock state */ @@ -526,6 +542,106 @@ public abstract class AbstractDataAbilities { cooldownEndTime = endTime; } + /** + * Get the global cooldown end time. + */ + public long getCooldownEndTime() { + return cooldownEndTime; + } + + /** + * Get the global cooldown duration value. + */ + public int getGlobalCooldownDurationValue() { + return globalCooldownDuration; + } + + /** + * Get the per-ability cooldown end times map. + */ + public HashMap getPerAbilityCooldownEndTimes() { + return perAbilityCooldownEndTimes; + } + + /** + * Get the per-ability cooldown durations map. + */ + public HashMap getPerAbilityCooldownDurations() { + return perAbilityCooldownDurations; + } + + /** + * Apply cooldown sync data from server. Called on client side. + */ + public void applyCooldownSync(long globalEndTime, int globalDuration, + HashMap perEndTimes, + HashMap perDurations) { + this.cooldownEndTime = globalEndTime; + this.globalCooldownDuration = globalDuration; + this.perAbilityCooldownEndTimes = perEndTimes; + this.perAbilityCooldownDurations = perDurations; + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-ABILITY COOLDOWN MANAGEMENT + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if a specific ability is on its per-ability cooldown. + */ + public boolean isOnPerAbilityCooldown(String key) { + Long endTime = perAbilityCooldownEndTimes.get(key); + return endTime != null && getWorldTime() < endTime; + } + + /** + * Set a per-ability cooldown. + */ + public void setPerAbilityCooldown(String key, long endTime, int duration) { + perAbilityCooldownEndTimes.put(key, endTime); + perAbilityCooldownDurations.put(key, duration); + } + + /** + * Reset a specific per-ability cooldown. + */ + public void resetPerAbilityCooldown(String key) { + perAbilityCooldownEndTimes.remove(key); + perAbilityCooldownDurations.remove(key); + } + + /** + * Reset all per-ability cooldowns. + */ + public void resetAllPerAbilityCooldowns() { + perAbilityCooldownEndTimes.clear(); + perAbilityCooldownDurations.clear(); + } + + /** + * Get global cooldown progress for HUD rendering. + * @return 1.0 when cooldown just started (fully covered), 0.0 when done + */ + public float getGlobalCooldownProgress() { + if (globalCooldownDuration <= 0) return 0f; + long remaining = cooldownEndTime - getWorldTime(); + if (remaining <= 0) return 0f; + return Math.min(1f, (float) remaining / globalCooldownDuration); + } + + /** + * Get per-ability cooldown progress for HUD rendering. + * @return 1.0 when cooldown just started (fully covered), 0.0 when done + */ + public float getPerAbilityCooldownProgress(String key) { + Long endTime = perAbilityCooldownEndTimes.get(key); + Integer duration = perAbilityCooldownDurations.get(key); + if (endTime == null || duration == null || duration <= 0) return 0f; + long remaining = endTime - getWorldTime(); + if (remaining <= 0) return 0f; + return Math.min(1f, (float) remaining / duration); + } + // ═══════════════════════════════════════════════════════════════════ // POSITION LOCKING // ═══════════════════════════════════════════════════════════════════ @@ -918,6 +1034,62 @@ public abstract class AbstractDataAbilities { protected void onInterruptComplete() { } + /** + * Cancel the currently executing ability (voluntary player action). + * Unlike interrupt, this always goes directly to IDLE (never DAZED), + * immediately rolls cooldown, and clears state. + * Also handles cancellation during chain delay (between chain entries). + */ + public void cancelCurrentAbility() { + boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting(); + boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0; + + if (!hasExecutingAbility && !isInChainDelay) return; + + if (hasExecutingAbility) { + AbilityPhase phase = currentAbility.getPhase(); + // Cannot cancel during DAZED (already interrupted) + if (phase == AbilityPhase.DAZED) return; + // Only allow cancel during active phases + if (phase != AbilityPhase.WINDUP && phase != AbilityPhase.ACTIVE + && phase != AbilityPhase.BURST_DELAY) return; + + // Remove telegraph + removeTelegraph(currentAbility); + + // Fire extender complete hook (cancelled = interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, getEntity(), getTarget(), true); + + // Fire interrupt event (source=null, damage=0 for voluntary cancel) + fireInterruptEvent(currentAbility, getTarget(), null, 0); + + // Cancel the ability (cleanup + go directly to IDLE, no DAZED) + currentAbility.onInterrupt(getEntity(), null, 0); + currentAbility.cancel(); + + // Release locks and stop animation + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + } + + // Roll cooldown + if (currentChain != null) { + rollChainCooldown(currentChain); + currentChain = null; + chainEntryIndex = -1; + chainDelayRemaining = -1; + } else if (currentAbility != null) { + rollCooldown(currentAbility); + } + + // Interrupt all concurrent slots + interruptConcurrentSlots(); + + // Clear state via the normal completion path + onAbilityComplete(); + } + // ═══════════════════════════════════════════════════════════════════ // CHAINED ABILITY EXECUTION // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/AnimationMixinFunctions.java b/src/main/java/noppes/npcs/AnimationMixinFunctions.java index 4a6eb1db5..e5c6d2089 100644 --- a/src/main/java/noppes/npcs/AnimationMixinFunctions.java +++ b/src/main/java/noppes/npcs/AnimationMixinFunctions.java @@ -209,21 +209,31 @@ public class AnimationMixinFunctions { return null; } - public static void playerFullModel_head(Entity p_78088_1_, CallbackInfo callbackInfo) { - if (!DBCAddon.IsAvailable() && ClientCacheHandler.playerAnimations.containsKey(p_78088_1_.getUniqueID())) { - AnimationData animData = ClientCacheHandler.playerAnimations.get(p_78088_1_.getUniqueID()); - if (animData != null && animData.isActive()) { - Frame frame = (Frame) animData.animation.currentFrame(); - if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) { - FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); - part.interpolateOffset(); - part.interpolateAngles(); - float pi = 180 / (float) Math.PI; - GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]); - GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0); - GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0); - GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1); - } + public static void playerFullModel_head(Entity entity, CallbackInfo callbackInfo) { + if (!ClientCacheHandler.playerAnimations.containsKey(entity.getUniqueID())) return; + + AnimationData animData = ClientCacheHandler.playerAnimations.get(entity.getUniqueID()); + if (animData == null || !animData.isActive()) return; + + // Snap body rotation to head so animations face the look direction + if (entity instanceof EntityLivingBase) { + EntityLivingBase living = (EntityLivingBase) entity; + living.renderYawOffset = living.rotationYaw; + living.prevRenderYawOffset = living.prevRotationYaw; + } + + // FULL_MODEL GL transforms (non-DBC only) + if (!DBCAddon.IsAvailable()) { + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) { + FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); + part.interpolateOffset(); + part.interpolateAngles(); + float pi = 180 / (float) Math.PI; + GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]); + GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0); + GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0); + GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1); } } } diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index ff2d13031..d7f951b1e 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -28,14 +28,15 @@ import kamkeel.npcs.controllers.SyncController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.controllers.data.profile.CNPCData; import kamkeel.npcs.developer.Developer; +import kamkeel.npcs.entity.EntityAbilityBarrier; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityAbilityPanel; import kamkeel.npcs.entity.EntityAbilitySweeper; import kamkeel.npcs.entity.EntityAbilityZone; -import kamkeel.npcs.entity.EntityEnergyDome; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityDome; import kamkeel.npcs.entity.EntityEnergySlicer; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.util.BukkitUtil; @@ -297,8 +298,8 @@ public class CustomNpcs { registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 3, true); registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true); registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true); - registerNewEntity(EntityEnergyDome.class, "energydome", 64, 3, true); - registerNewEntity(EntityEnergyPanel.class, "energypanel", 64, 3, true); + registerNewEntity(EntityAbilityDome.class, "energydome", 64, 3, true); + registerNewEntity(EntityAbilityPanel.class, "energypanel", 64, 3, true); registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 3, true); new RecipeController(); @@ -335,6 +336,14 @@ public class CustomNpcs { @EventHandler public void loadComplete(FMLLoadCompleteEvent ev) { proxy.buildPackageIndex(); + + // Load built-in animations on the client so they're available for ability preview. + // On dedicated servers, AnimationController.load() only runs on the server JVM, + // leaving the client without built-in animation data. In singleplayer, load() + // runs later during server start and reloads everything, so this is harmless. + if (FMLCommonHandler.instance().getSide().isClient()) { + AnimationController.Instance.loadClientBuiltIns(); + } } @EventHandler @@ -422,6 +431,7 @@ public class CustomNpcs { } kamkeel.npcs.entity.EntityEnergyProjectile.clearAllProjectiles(); + EntityAbilityBarrier.clearAllBarriers(); if (FMLCommonHandler.instance().getSide().isClient()) clientJaninoCompiler = null; diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 44fb852c6..548939a54 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -222,13 +222,18 @@ public class DataAbilities extends AbstractDataAbilities { @Override protected void rollCooldown(Ability ability) { + // Always roll NPC global cooldown (pacing timer) int baseCooldown = minCooldown; if (maxCooldown > minCooldown) { baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1); } - cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown; - // Add ability-specific cooldown offset - cooldownEndTime += ability.getCooldownTicks(); + cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + ability.getCooldownTicks(); + + // Additionally set per-ability cooldown if enabled + if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) { + long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks(); + setPerAbilityCooldown(ability.getName(), endTime, ability.getCooldownTicks()); + } } @Override @@ -482,6 +487,14 @@ public class DataAbilities extends AbstractDataAbilities { return false; } + // Per-ability cooldown filter: ability may have its own independent cooldown + if (!action.isChain()) { + Ability ab = (Ability) action; + if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) { + return false; + } + } + return true; } @@ -726,6 +739,7 @@ public class DataAbilities extends AbstractDataAbilities { stopCurrentAbility(); clearActiveToggles(); interruptConcurrentSlots(); + resetAllPerAbilityCooldowns(); // Roll cooldown so NPC doesn't immediately attack after reset rollCooldownOnReset(); diff --git a/src/main/java/noppes/npcs/ServerEventsHandler.java b/src/main/java/noppes/npcs/ServerEventsHandler.java index b6671b72a..0f9fa1d3e 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -4,6 +4,8 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; import kamkeel.npcs.network.enums.EnumSyncAction; @@ -151,6 +153,52 @@ public class ServerEventsHandler { } } + @SubscribeEvent + public void barrierAbsorbDamage(LivingAttackEvent event) { + if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote) + return; + + EntityAbilityBarrier barrier = EntityAbilityBarrier.getAbsorbingBarrier(event.entityLiving); + if (barrier != null) { + // Redirect the caster's damage to their barrier + barrier.absorbDamage(event.ammount); + event.setCanceled(true); + } + } + + @SubscribeEvent + public void domeItemBlacklist(PlayerInteractEvent event) { + if (event.action == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) return; + EntityPlayer player = event.entityPlayer; + if (player == null || player.worldObj == null || player.worldObj.isRemote) return; + + ItemStack held = player.getHeldItem(); + if (held == null) return; + + String itemId = net.minecraft.item.Item.itemRegistry.getNameForObject(held.getItem()); + if (itemId == null) return; + + String[] blacklist = noppes.npcs.config.ConfigEnergy.DomeItemBlacklist; + if (blacklist == null) return; + + boolean blacklisted = false; + for (String banned : blacklist) { + if (banned.equals(itemId)) { + blacklisted = true; + break; + } + } + if (!blacklisted) return; + + List barriers = EntityAbilityBarrier.getActiveBarriers(player.worldObj); + for (EntityAbilityBarrier barrier : barriers) { + if (barrier instanceof EntityAbilityDome && barrier.isEntityInside(player)) { + event.setCanceled(true); + return; + } + } + } + @SubscribeEvent public void partyDamagedEvent(LivingAttackEvent event) { if (!(event.source != null && event.source.getEntity() instanceof EntityPlayer) || !(event.entityLiving instanceof EntityPlayer) || FMLCommonHandler.instance().getEffectiveSide().isClient()) diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index a73ccf707..6eebfd5d5 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -25,6 +25,7 @@ import noppes.npcs.client.gui.hud.ClientHudManager; import noppes.npcs.client.gui.hud.CompassHudComponent; import noppes.npcs.client.gui.hud.EnumHudComponent; import noppes.npcs.client.gui.hud.QuestTrackingComponent; +import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent; import noppes.npcs.client.gui.player.AuctionTooltipHandler; import noppes.npcs.client.renderer.MarkRenderer; import noppes.npcs.client.renderer.RenderCNPCPlayer; @@ -98,6 +99,24 @@ public class ClientEventHandler { return; } + // Ability Hotbar: Hold HUD key + scroll wheel to cycle + if (event.dwheel != 0 && ClientProxy.AbilityHudKey != null) { + int hudKeyCode = ClientProxy.AbilityHudKey.getKeyCode(); + if (hudKeyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode)) { + AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance() + .getHudComponents().get(EnumHudComponent.AbilityHotbar); + if (comp != null && comp.hasAnyAbilities()) { + if (event.dwheel > 0) { + comp.onCyclePrev(); + } else { + comp.onCycleNext(); + } + event.setCanceled(true); + return; + } + } + } + ArrayList removeList = new ArrayList<>(); for (Map.Entry entry : disabledButtonTimes.entrySet()) { if (entry.getValue() > 0) { @@ -125,6 +144,7 @@ public class ClientEventHandler { if (ClientHudManager.getInstance().getHudComponents().isEmpty()) { ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestTracker, new QuestTrackingComponent(Minecraft.getMinecraft())); ClientHudManager.getInstance().registerHud(EnumHudComponent.QuestCompass, new CompassHudComponent(Minecraft.getMinecraft())); + ClientHudManager.getInstance().registerHud(EnumHudComponent.AbilityHotbar, new AbilityHotbarComponent(Minecraft.getMinecraft())); } ClientHudManager.getInstance().renderAllHUDs(event.partialTicks); diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index 55359c70d..9e91d5556 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -12,8 +12,8 @@ import kamkeel.npcs.client.renderer.RenderAbilityLaser; import kamkeel.npcs.client.renderer.RenderAbilityOrb; import kamkeel.npcs.client.renderer.RenderAbilitySweeper; import kamkeel.npcs.client.renderer.RenderAbilityZone; -import kamkeel.npcs.client.renderer.RenderEnergyDome; -import kamkeel.npcs.client.renderer.RenderEnergyPanel; +import kamkeel.npcs.client.renderer.RenderAbilityDome; +import kamkeel.npcs.client.renderer.RenderAbilityPanel; import kamkeel.npcs.client.renderer.RenderEnergySlicer; import kamkeel.npcs.client.renderer.TelegraphRenderer; import kamkeel.npcs.client.renderer.lightning.LightningHandler; @@ -24,8 +24,8 @@ import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; import kamkeel.npcs.entity.EntityAbilitySweeper; import kamkeel.npcs.entity.EntityAbilityZone; -import kamkeel.npcs.entity.EntityEnergyDome; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityAbilityPanel; import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; @@ -259,6 +259,7 @@ import java.util.Random; public class ClientProxy extends CommonProxy { public static KeyBinding NPCButton; public static KeyBinding SpecialKey; + public static KeyBinding AbilityHudKey; public static final Random RAND = new Random(); public static FontContainer Font; @@ -279,8 +280,8 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone()); - RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome()); - RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDome.class, new RenderAbilityDome()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityPanel.class, new RenderAbilityPanel()); RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer()); RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc()); @@ -334,11 +335,14 @@ public class ClientProxy extends CommonProxy { Minecraft mc = Minecraft.getMinecraft(); NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc"); - SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_B, "key.categories.customnpc"); + SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_GRAVE, "key.categories.customnpc"); ClientRegistry.registerKeyBinding(NPCButton); ClientRegistry.registerKeyBinding(SpecialKey); + AbilityHudKey = new KeyBinding("key.customnpcs.abilityHudKey", Keyboard.KEY_LMENU, "key.categories.customnpc"); + ClientRegistry.registerKeyBinding(AbilityHudKey); + new PresetController(CustomNpcs.Dir); if (ConfigMain.EnableUpdateChecker) { diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 36ad964e9..58d6f5a3f 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -5,10 +5,12 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; +import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.client.renderer.lightning.LightningBolt; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.data.RequestProperSpawnData; import kamkeel.npcs.network.packets.player.CheckPlayerValue; import kamkeel.npcs.network.packets.player.InputDevicePacket; import kamkeel.npcs.network.packets.player.ScreenSizePacket; @@ -59,6 +61,7 @@ public class ClientTickHandler { if (mc.theWorld == null) { ClientCacheHandler.clearCache(); ClientAbilityState.reset(); + RequestProperSpawnData.clear(); } this.prevWorld = mc.theWorld; } @@ -154,6 +157,16 @@ public class ClientTickHandler { renderCNPCPlayer.itemRenderer.updateEquippedItem(); } } + + // Tick telegraph manager AFTER entity updates so telegraph positions + // match entity interpolation (Phase.END runs after world tick) + if (TelegraphManager.ClientInstance != null) { + TelegraphManager.ClientInstance.tick(mc.theWorld); + } + + // Update lightning bolts for ability effects + LightningBolt.updateAll(); + return; } if (mc.thePlayer != null && mc.thePlayer.openContainer instanceof ContainerPlayer) { @@ -179,13 +192,6 @@ public class ClientTickHandler { MusicController.Instance.onUpdate(); ScriptSoundController.Instance.onUpdate(); - // Tick telegraph manager for ability warnings - if (TelegraphManager.ClientInstance != null) { - TelegraphManager.ClientInstance.tick(mc.theWorld); - } - - // Update lightning bolts for ability effects - LightningBolt.updateAll(); if (Minecraft.getMinecraft().thePlayer != null && (prevWidth != mc.displayWidth || prevHeight != mc.displayHeight)) { prevWidth = mc.displayWidth; prevHeight = mc.displayHeight; @@ -196,10 +202,46 @@ public class ClientTickHandler { return; if (mc.theWorld.getTotalWorldTime() % 20 == 0) { // Update every second + if (RequestProperSpawnData.canDoBatchUpdate()) + RequestProperSpawnData.handleBacklog(); updateCompassMarks(); } } + /** + * Enforce ability lock motion constraints right before entity update. + * The Phase.END zeroing in onClientTick can be overwritten by other mods' + * ClientTickEvent Phase.START handlers (e.g. flight mods re-applying gravity). + * PlayerTickEvent fires after all ClientTickEvent handlers but before + * player.onUpdate(), making this the definitive point to enforce motion locks. + */ + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerTick(TickEvent.PlayerTickEvent event) { + if (event.phase != Phase.START || event.side != Side.CLIENT) + return; + + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer == null || mc.currentScreen != null) + return; + + if (!ClientAbilityState.shouldSuppressMovementInput()) + return; + + if (!ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionX = 0; + mc.thePlayer.motionZ = 0; + } + + if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) + && !ClientAbilityState.hasAbilityMovement) { + if (ClientAbilityState.wasFlyingAtLock) { + mc.thePlayer.motionY = 0; + } else { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + } + } + } + @SubscribeEvent public void onMouse(InputEvent.MouseInputEvent event) { if (Mouse.getEventButton() == -1 && Mouse.getEventDWheel() == 0) diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java index cfde598de..0b21d028d 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java @@ -127,7 +127,7 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi int iconWidth = effect.getWidth(); int iconHeight = effect.getHeight(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index 3aa153f59..544a7fefd 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -1,7 +1,7 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; import net.minecraft.client.gui.GuiButton; import net.minecraft.nbt.NBTTagCompound; @@ -20,6 +20,8 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; import java.util.List; +import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS; + public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { private static final int DECLARATIVE_ID_START = 1000; @@ -42,6 +44,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi private static final int L_LABEL_X = 5; private static final int ROW_H = 24; + // Condition buttons + private static final int COND_BASE = 50; + private static final int COND_STRIDE = 10; + private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10 + private static final int BTN_ADD_COND = COND_END; + private final Ability ability; private final IAbilityConfigCallback callback; private int activeTab = TAB_GENERAL; @@ -49,7 +57,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi private List fieldDefs; private List customTabNames; - private List conditions; + private List conditions; private int editingConditionIndex = -1; private AbilityFieldBuilder builder; @@ -234,46 +242,29 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); y += 15; - for (int i = 0; i < conditions.size() && i < 3; i++) { - Condition cond = conditions.get(i); + for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { + AbilityCondition cond = conditions.get(i); String condName = getConditionDisplayName(cond); - sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); - sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); - sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); + GuiNpcButton condBtn = new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName); + condBtn.hoverableText = cond.getConditionSummary(); + sw.addButton(condBtn); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X")); y += 22; } - if (conditions.size() < 3) { - sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); + if (conditions.size() < MAX_CONDITIONS) { + sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));; y += ROW_H; } return y; } - private String getConditionDisplayName(Condition cond) { + private String getConditionDisplayName(AbilityCondition cond) { if (cond == null) return "None"; - String typeId = cond.getTypeId(); - switch (typeId) { - case "hp_above": - return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hp_below": - return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_above": - return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_below": - return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hit_count": - Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; - return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; - default: - return typeId; - } - } - - private float getConditionThreshold(Condition cond) { - NBTTagCompound nbt = cond.writeNBT(); - return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; + String name = cond.getName(); + return StatCollector.translateToLocal(name); } // ═══════════════════════════════════════════════════════════════════════════ @@ -331,9 +322,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } private boolean handleConditionButton(int id) { - if (id >= 50 && id < 80) { - int condIndex = (id - 50) / 10; - int action = (id - 50) % 10; + if (id >= COND_BASE && id < COND_END) { + int condIndex = (id - COND_BASE) / COND_STRIDE; + int action = (id - COND_BASE) % COND_STRIDE; if (action == 0 || action == 1) { if (condIndex < conditions.size()) { editingConditionIndex = condIndex; @@ -347,8 +338,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } return true; } - if (id == 80) { - if (conditions.size() < 3) { + if (id == BTN_ADD_COND) { + if (conditions.size() < MAX_CONDITIONS) { editingConditionIndex = conditions.size(); setSubGui(new SubGuiConditionEdit(null)); } @@ -382,7 +373,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi if (subgui instanceof SubGuiConditionEdit) { SubGuiConditionEdit condEdit = (SubGuiConditionEdit) subgui; - Condition result = condEdit.getResult(); + AbilityCondition result = condEdit.getResult(); if (result != null && editingConditionIndex >= 0) { if (editingConditionIndex < conditions.size()) { conditions.set(editingConditionIndex, result); @@ -409,7 +400,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi protected void applyToAbility() { ability.getConditions().clear(); - for (Condition c : conditions) ability.addCondition(c); + for (AbilityCondition c : conditions) ability.addCondition(c); } public void loadAbility(Ability loadedAbility) { diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index da71dec70..d1946e2e2 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -6,13 +6,13 @@ import kamkeel.npcs.controllers.data.ability.AbilityAction; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.ChainedAbility; import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.data.ability.AbilityIconData; import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider; import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import net.minecraft.client.gui.GuiButton; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.builder.GuiFieldBuilder; @@ -21,18 +21,19 @@ import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.GuiScrollWindow; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; -import noppes.npcs.client.gui.util.ISubGuiListener; -import noppes.npcs.client.gui.util.ITextfieldListener; -import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.client.gui.util.*; import java.util.ArrayList; +import noppes.npcs.client.gui.util.IChainedAbilityConfigCallback; + + import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS; + /** * SubGui for editing a {@link ChainedAbility}. * Core tabs: General, Entries, Conditions. @@ -70,9 +71,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText // Actual ID = COND_BASE + i * COND_STRIDE + offset // offset 0 = name/click, 1 = edit, 2 = delete private static final int COND_BASE = 50; - private static final int COND_END = 80; private static final int COND_STRIDE = 10; - private static final int BTN_ADD_COND = 80; + private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10 + private static final int BTN_ADD_COND = COND_END; // ── Layout constants ────────────────────────────────────────────────────── private static final int L_LABEL_X = 5; @@ -88,7 +89,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText private List fieldDefs; private List entries; - private List conditions; + private List conditions; // Dynamic tabs injected by field providers (e.g., "Icon") private List extraTabs = new ArrayList<>(); @@ -157,7 +158,18 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText FieldDef.floatField("ability.maxRange", chain::getMaxRange, chain::setMaxRange).range(0, 64) ).tab("Target")); - // External field providers (e.g., DBC Addon injecting an "Icon" tab) + // ── Icon tab ────────────────────────────────────────────── + AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain); + fieldDefs.add(FieldDef.stringField("gui.texture", chainIcon::getTexture, chainIcon::setTexture).tab("Icon")); + fieldDefs.add(FieldDef.section("ability.icon.section.uv").tab("Icon")); + fieldDefs.add(FieldDef.intField("ability.icon.x", chainIcon::getIconX, chainIcon::setIconX).tab("Icon").range(0, 4096)); + fieldDefs.add(FieldDef.intField("ability.icon.y", chainIcon::getIconY, chainIcon::setIconY).tab("Icon").range(0, 4096)); + fieldDefs.add(FieldDef.section("gui.size").tab("Icon")); + fieldDefs.add(FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).tab("Icon").range(1, 256)); + fieldDefs.add(FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).tab("Icon").range(1, 256)); + fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f)); + + // External field providers (e.g., DBC Addon injecting a "DBC" tab) if (AbilityController.Instance != null) { for (IChainedAbilityFieldProvider provider : AbilityController.Instance.getChainedFieldProviders()) { provider.addFieldDefinitions(chain, fieldDefs); @@ -416,8 +428,8 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); y += 15; - for (int i = 0; i < conditions.size() && i < 3; i++) { - Condition cond = conditions.get(i); + for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) { + AbilityCondition cond = conditions.get(i); String condName = getConditionDisplayName(cond); sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName)); sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit")); @@ -425,7 +437,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText y += 22; } - if (conditions.size() < 3) { + if (conditions.size() < MAX_CONDITIONS) { sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add")); y += ROW_H; } @@ -433,29 +445,10 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText return y; } - private String getConditionDisplayName(Condition cond) { + private String getConditionDisplayName(AbilityCondition cond) { if (cond == null) return "None"; - String typeId = cond.getTypeId(); - switch (typeId) { - case "hp_above": - return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hp_below": - return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_above": - return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "target_hp_below": - return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; - case "hit_count": - Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; - return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; - default: - return typeId; - } - } - - private float getConditionThreshold(Condition cond) { - NBTTagCompound nbt = cond.writeNBT(); - return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; + String name = cond.getName(); + return StatCollector.translateToLocal(name); } // ═══════════════════════════════════════════════════════════════════════════ @@ -623,7 +616,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText return true; } if (id == BTN_ADD_COND) { - if (conditions.size() < 3) { + if (conditions.size() < MAX_CONDITIONS) { editingConditionIndex = conditions.size(); setSubGui(new SubGuiConditionEdit(null)); } @@ -833,7 +826,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText } private void handleConditionEditClosed(SubGuiConditionEdit gui) { - Condition result = gui.getResult(); + AbilityCondition result = gui.getResult(); if (result != null && editingConditionIndex >= 0) { if (editingConditionIndex < conditions.size()) { conditions.set(editingConditionIndex, result); @@ -879,7 +872,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText // Conditions chain.getConditions().clear(); - for (Condition c : conditions) { + for (AbilityCondition c : conditions) { chain.getConditions().add(c); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java index d941f19ec..b0ed1d635 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiConditionEdit.java @@ -1,190 +1,310 @@ package noppes.npcs.client.gui.advanced; -import kamkeel.npcs.controllers.data.ability.Condition; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; +import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; -import noppes.npcs.client.gui.util.GuiNpcButton; -import noppes.npcs.client.gui.util.GuiNpcLabel; -import noppes.npcs.client.gui.util.GuiNpcTextField; -import noppes.npcs.client.gui.util.ITextfieldListener; -import noppes.npcs.client.gui.util.SubGuiInterface; +import net.minecraft.client.resources.I18n; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.util.*; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; /** - * SubGui for editing a single ability condition. - * Allows selecting condition type and configuring its parameters. + * SubGui for editing a single AbilityCondition. + * + * Split-panel layout: + * Left – Mod namespace filter + scrollable condition type list + * Right – FieldDef configuration for the selected condition */ -public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener { +public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, ICustomScrollListener { - // Condition types - private static final String[] CONDITION_TYPES = { - "condition.hp_above", - "condition.hp_below", - "condition.target_hp_above", - "condition.target_hp_below", - "condition.hit_count" - }; + private static final int DECLARATIVE_ID_START = 1000; + private static final int CLEAR_ID_START = 2000; + private static final int LABEL_ID_START = 3000; - private static final String[] CONDITION_TYPE_IDS = { - "hp_above", - "hp_below", - "target_hp_above", - "target_hp_below", - "hit_count" - }; + private static final int BTN_NAMESPACE = 1; + private static final int BTN_CANCEL = 10; + private static final int BTN_DONE = 11; + private static final int TF_SEARCH = 12; - // Current condition being edited - private Condition condition; - private Condition result; + // Left panel + private static final int LEFT_WIDTH = 110; + private static final int LEFT_MARGIN = 5; - // State - private int selectedTypeIndex = 0; - private float threshold = 0.5f; // For HP conditions (0.0-1.0) - private int requiredHits = 3; // For hit_count - private int withinTicks = 60; // For hit_count + // Right panel + private static final int RIGHT_GAP = 5; - public SubGuiConditionEdit(Condition existing) { - this.condition = existing; + private String searchText = ""; + + private AbilityCondition condition; + private AbilityCondition result; + private String selectedTypeId; + + // Namespace filter + private int namespaceFilter = 0; // 0 = ALL, 1 = cnpc, 2+ = modded namespaces + private List modNamespaces; + + // Type list + private GuiCustomScroll scroll; + private final HashMap displayNameToTypeId = new HashMap<>(); + private String[] filteredTypeIds; + + private AbilityFieldBuilder builder; + + public SubGuiConditionEdit(AbilityCondition existing) { this.result = null; + this.modNamespaces = getModNamespaces(); if (existing != null) { - String typeId = existing.getTypeId(); - for (int i = 0; i < CONDITION_TYPE_IDS.length; i++) { - if (CONDITION_TYPE_IDS[i].equals(typeId)) { - selectedTypeIndex = i; - break; - } + this.condition = existing; + this.selectedTypeId = existing.getTypeId(); + // Set namespace filter to match existing condition + setNamespaceForTypeId(selectedTypeId); + } else { + // Default to first available condition + String[] allTypes = AbilityController.Instance.getConditionTypes(); + if (allTypes.length > 0) { + this.selectedTypeId = allTypes[0]; + this.condition = spawnCondition(selectedTypeId); } - loadFromCondition(existing); } - setBackground("menubg.png"); - xSize = 220; - ySize = 140; + setBackground("menubg.png", 217); + xSize = 356; + ySize = 200; } - private void loadFromCondition(Condition cond) { - String typeId = cond.getTypeId(); - if (typeId.equals("hit_count")) { - Condition.ConditionHitCount hitCount = (Condition.ConditionHitCount) cond; - requiredHits = hitCount.getRequiredHits(); - withinTicks = hitCount.getWithinTicks(); - } else { - // HP-based conditions - net.minecraft.nbt.NBTTagCompound nbt = cond.writeNBT(); - threshold = nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; + private List getModNamespaces() { + List result = new ArrayList<>(); + List registered = Register.REGISTERED_NAMESPACES.get("condition"); + if (registered != null) { + result.addAll(registered); } + return result; + } + + private void setNamespaceForTypeId(String typeId) { + if (typeId == null) return; + String[] parts = typeId.split("\\.", 3); + if (parts.length < 2) return; + String ns = parts[1]; + + if ("cnpc".equals(ns)) { + namespaceFilter = 1; + } else { + for (int i = 0; i < modNamespaces.size(); i++) { + if (modNamespaces.get(i).equals(ns)) { + namespaceFilter = 2 + i; + return; + } + } + namespaceFilter = 0; // Fallback to ALL + } + } + + private String getNamespaceFilterLabel() { + if (namespaceFilter == 0) return "ALL"; + if (namespaceFilter == 1) return "CNPC"; + int modIdx = namespaceFilter - 2; + if (modIdx >= 0 && modIdx < modNamespaces.size()) { + String ns = modNamespaces.get(modIdx); + String display = Register.NAMESPACE_DISPLAY_NAMES.get(ns); + return display != null ? display : ns.toUpperCase(); + } + return "ALL"; + } + + private void cycleNamespaceFilter() { + namespaceFilter++; + // 0=ALL, 1=CNPC, 2..2+N-1=mod namespaces, then wrap + int max = 2 + modNamespaces.size(); + if (namespaceFilter >= max) { + namespaceFilter = 0; + } + // Skip empty mod namespace slots + if (namespaceFilter >= 2) { + int modIdx = namespaceFilter - 2; + if (modIdx >= modNamespaces.size()) { + namespaceFilter = 0; + } + } + } + + private String[] getFilteredTypes() { + if (namespaceFilter == 0) { + return AbilityController.Instance.getConditionTypes(); + } else if (namespaceFilter == 1) { + return AbilityController.Instance.getConditionTypesByNamespace("cnpc"); + } else { + int modIdx = namespaceFilter - 2; + if (modIdx >= 0 && modIdx < modNamespaces.size()) { + return AbilityController.Instance.getConditionTypesByNamespace(modNamespaces.get(modIdx)); + } + return AbilityController.Instance.getConditionTypes(); + } + } + + private AbilityCondition spawnCondition(String typeId) { + if (typeId == null) return null; + Supplier factory = AbilityController.Instance.getConditionType(typeId); + return factory != null ? factory.get() : null; } @Override public void initGui() { + GuiNpcTextField.unfocus(); super.initGui(); - int y = guiTop + 8; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 90; + int leftX = guiLeft + LEFT_MARGIN; + int btnY = guiTop + ySize - 26; - // Title - addLabel(new GuiNpcLabel(0, "condition.edit", labelX, y)); - y += 18; + // Namespace filter button (above left scroll only) + addButton(new GuiNpcButton(BTN_NAMESPACE, leftX, guiTop + 5, LEFT_WIDTH, 20, getNamespaceFilterLabel())); - // Condition Type selector - addLabel(new GuiNpcLabel(1, "gui.type", labelX, y + 5)); - GuiNpcButton typeBtn = new GuiNpcButton(1, fieldX, y, 115, 20, CONDITION_TYPES, selectedTypeIndex); - typeBtn.setHoverText("condition.hover.type"); - addButton(typeBtn); - y += 26; - - // Type-specific fields - String typeId = CONDITION_TYPE_IDS[selectedTypeIndex]; - if (typeId.equals("hit_count")) { - // Hit count fields - addLabel(new GuiNpcLabel(2, "condition.hits", labelX, y + 5)); - GuiNpcTextField hitsField = new GuiNpcTextField(2, this, fontRendererObj, fieldX, y, 40, 20, "" + requiredHits); - hitsField.setIntegersOnly(); - hitsField.setMinMaxDefault(1, 100, 3); - hitsField.setHoverText("condition.hover.hits"); - addTextField(hitsField); - y += 24; - - addLabel(new GuiNpcLabel(3, "condition.within", labelX, y + 5)); - GuiNpcTextField ticksField = new GuiNpcTextField(3, this, fontRendererObj, fieldX, y, 40, 20, "" + withinTicks); - ticksField.setIntegersOnly(); - ticksField.setMinMaxDefault(1, 1200, 60); - ticksField.setHoverText("condition.hover.within"); - addTextField(ticksField); - } else { - // HP threshold field (as percentage) - addLabel(new GuiNpcLabel(2, "condition.percent", labelX, y + 5)); - int percent = (int) (threshold * 100); - GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, "" + percent); - thresholdField.setIntegersOnly(); - thresholdField.setMinMaxDefault(1, 99, 50); - thresholdField.setHoverText("condition.hover.threshold"); - addTextField(thresholdField); - addLabel(new GuiNpcLabel(4, "%", fieldX + 45, y + 5)); + // Build filtered type list + filteredTypeIds = getFilteredTypes(); + displayNameToTypeId.clear(); + List scrollList = new ArrayList<>(); + for (String typeId : filteredTypeIds) { + Supplier factory = AbilityController.Instance.getConditionType(typeId); + String displayName = factory != null ? I18n.format(factory.get().getName()) : typeId; + if (!searchText.isEmpty() && !displayName.toLowerCase().contains(searchText.toLowerCase())) continue; + scrollList.add(displayName); + displayNameToTypeId.put(displayName, typeId); } + // Left panel: condition type scroll list (between namespace button and search bar) + int scrollTop = guiTop + 29; + int scrollBottom = btnY - 24; + int scrollHeight = scrollBottom - scrollTop; + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + } + scroll.guiLeft = leftX; + scroll.guiTop = scrollTop; + scroll.setSize(LEFT_WIDTH, scrollHeight); + scroll.setUnsortedList(scrollList); + + // Pre-select current condition type in scroll + if (selectedTypeId != null) { + for (int i = 0; i < scrollList.size(); i++) { + String typeId = displayNameToTypeId.get(scrollList.get(i)); + if (typeId != null && typeId.equals(selectedTypeId)) { + scroll.selected = i; + break; + } + } + } + addScroll(scroll); + + // Search text field (below left scroll) + GuiNpcTextField searchField = new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, leftX, scrollBottom + 2, LEFT_WIDTH, 20, searchText); + searchField.setHoverText("gui.search"); + addTextField(searchField); + + // Right panel: condition config via FieldDef (full height from top to buttons) + int rightX = leftX + LEFT_WIDTH + RIGHT_GAP; + int rightW = xSize - LEFT_MARGIN * 2 - LEFT_WIDTH - RIGHT_GAP; + int rightTop = guiTop + 5; + int rightHeight = btnY - rightTop - 4; + + List fields = new ArrayList<>(); + if (condition != null) { + fields = condition.getAllDefinitions(); + } + + builder = new AbilityFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START); + builder.contentRight(rightW); + builder.startY(5); + builder.buildScrollWindow(fields, rightX, rightTop, rightW, rightHeight); + // Bottom buttons - addButton(new GuiNpcButton(10, guiLeft + 8, guiTop + ySize - 28, 60, 20, "gui.cancel")); - addButton(new GuiNpcButton(11, guiLeft + xSize - 68, guiTop + ySize - 28, 60, 20, "gui.done")); + addButton(new GuiNpcButton(BTN_CANCEL, leftX, btnY, 60, 20, "gui.cancel")); + GuiNpcButton doneBtn = new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done"); + if (condition == null || !condition.isConfigured()) { + doneBtn.setEnabled(false); + } + addButton(doneBtn); } @Override public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - if (id == 1) { - // Type changed - selectedTypeIndex = ((GuiNpcButton) guibutton).getValue(); + if (id == BTN_NAMESPACE) { + cycleNamespaceFilter(); initGui(); - } else if (id == 10) { - // Cancel - close without saving + return; + } + + if (id == BTN_CANCEL) { result = null; close(); - } else if (id == 11) { - // Done - create condition and close - result = createCondition(); + return; + } + + if (id == BTN_DONE) { + result = condition; close(); + return; + } + + if (builder != null && builder.handleButtonEvent(id, guibutton)) { + if (!hasSubGui()) { + initGui(); + } } } + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && scroll.hasSelected()) { + String displayName = scroll.getSelected(); + String typeId = displayNameToTypeId.get(displayName); + if (typeId != null && !typeId.equals(selectedTypeId)) { + selectedTypeId = typeId; + condition = spawnCondition(selectedTypeId); + initGui(); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + // Same as single click — user still needs to configure fields + } + @Override public void unFocused(GuiNpcTextField textField) { - int id = textField.id; - - if (id == 2) { - requiredHits = textField.getInteger(); - } else if (id == 3) { - withinTicks = textField.getInteger(); - } else if (id == 4) { - int percent = textField.getInteger(); - threshold = percent / 100.0f; + if (textField.id == TF_SEARCH) { + String newText = textField.getText(); + if (!newText.equals(searchText)) { + searchText = newText; + initGui(); + } + return; + } + if (textField.id < DECLARATIVE_ID_START) return; + if (builder != null && builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); } } - private Condition createCondition() { - String typeId = CONDITION_TYPE_IDS[selectedTypeIndex]; - - switch (typeId) { - case "hp_above": - return new Condition.ConditionHPAbove(threshold); - case "hp_below": - return new Condition.ConditionHPBelow(threshold); - case "target_hp_above": - return new Condition.ConditionTargetHPAbove(threshold); - case "target_hp_below": - return new Condition.ConditionTargetHPBelow(threshold); - case "hit_count": - return new Condition.ConditionHitCount(requiredHits, withinTicks); - default: - return null; + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (builder != null && builder.handleSubGuiClosed(subgui)) { + initGui(); } } - /** - * Get the resulting condition after dialog closes. - * Returns null if cancelled or no valid condition. - */ - public Condition getResult() { + public AbilityCondition getResult() { return result; } } diff --git a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java index bb069b8f5..8d7d88d61 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -344,6 +344,9 @@ public class GuiFieldBuilder { String translated = StatCollector.translateToLocal(def.getLabel()); int labelW = fontRenderer.getStringWidth(translated); int fieldX = colLLabel + labelW + labelPadding; + // Clamp field width so it doesn't extend under the scrollbar + int maxW = contentRight - fieldX - 15; + if (maxW > 0 && fieldW > maxW) fieldW = maxW; renderFieldAt(def, colLLabel, fieldX, fieldW, y); } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java index 21ecb1b8d..57df39d20 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageEffects.java @@ -173,7 +173,7 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro int iconWidth = effect.getWidth(); int iconHeight = effect.getHeight(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); diff --git a/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java index aa6d9c21a..cd5ddb2dd 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/CompassHudComponent.java @@ -81,10 +81,10 @@ public class CompassHudComponent extends HudComponent { ConfigClient.CompassEnabledProperty.set(ConfigClient.CompassEnabled); ConfigClient.CompassOverlayX = posX; - ConfigClient.CompassOverlayXProperty.set(ConfigClient.CompassOverlayX); + ConfigClient.CompassOverlayXProperty.set((double) ConfigClient.CompassOverlayX); ConfigClient.CompassOverlayY = posY; - ConfigClient.CompassOverlayYProperty.set(ConfigClient.CompassOverlayY); + ConfigClient.CompassOverlayYProperty.set((double) ConfigClient.CompassOverlayY); ConfigClient.CompassOverlayScale = scale; ConfigClient.CompassOverlayScaleProperty.set(ConfigClient.CompassOverlayScale); diff --git a/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java index fe6eb07b6..7eda9a335 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/EnumHudComponent.java @@ -2,5 +2,6 @@ package noppes.npcs.client.gui.hud; public enum EnumHudComponent { QuestTracker, - QuestCompass + QuestCompass, + AbilityHotbar } diff --git a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java index 5908cf9b8..d36727aad 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java +++ b/src/main/java/noppes/npcs/client/gui/hud/GuiHudEditor.java @@ -173,7 +173,8 @@ public class GuiHudEditor extends GuiScreen { int absHeight = (int) (hud.overlayHeight * effectiveScale); if (mouseX >= actualX && mouseX <= actualX + absWidth && mouseY >= actualY && mouseY <= actualY + absHeight) { - if (mouseX >= actualX + absWidth - HANDLE_SIZE && mouseY >= actualY + absHeight - HANDLE_SIZE) { + int scaledHandle = Math.max(8, (int) (HANDLE_SIZE * effectiveScale)); + if (mouseX >= actualX + absWidth - scaledHandle && mouseY >= actualY + absHeight - scaledHandle) { resizing = true; selectedComponent = hud; initialScale = hud.scale; @@ -214,12 +215,14 @@ public class GuiHudEditor extends GuiScreen { int newY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight) - dragOffsetY; if (newX < 0) newX = 0; if (newY < 0) newY = 0; - if (newX + (int) (selectedComponent.overlayWidth * effectiveScale) > scaledWidth) - newX = scaledWidth - (int) (selectedComponent.overlayWidth * effectiveScale); - if (newY + (int) (selectedComponent.overlayHeight * effectiveScale) > scaledHeight) - newY = scaledHeight - (int) (selectedComponent.overlayHeight * effectiveScale); - selectedComponent.posX = (int) (100F * newX / scaledWidth); - selectedComponent.posY = (int) (100F * newY / scaledHeight); + int compW = (int) Math.ceil(selectedComponent.overlayWidth * effectiveScale); + int compH = (int) Math.ceil(selectedComponent.overlayHeight * effectiveScale); + if (newX + compW > scaledWidth) + newX = scaledWidth - compW; + if (newY + compH > scaledHeight) + newY = scaledHeight - compH; + selectedComponent.posX = 100F * newX / scaledWidth; + selectedComponent.posY = 100F * newY / scaledHeight; } if (resizing) { int currentMouseX = Mouse.getX() * width / mc.displayWidth; @@ -260,8 +263,8 @@ public class GuiHudEditor extends GuiScreen { } int centerX = (res.getScaledWidth() - compWidth) / 2; int centerY = (res.getScaledHeight() - compHeight) / 2; - selectedComponent.posX = (int) (100F * centerX / res.getScaledWidth()); - selectedComponent.posY = (int) (100F * centerY / res.getScaledHeight()); + selectedComponent.posX = 100F * centerX / res.getScaledWidth(); + selectedComponent.posY = 100F * centerY / res.getScaledHeight(); updateCustomButtons(); } } else if (button.id == CYCLE_LEFT_ID) { diff --git a/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java b/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java index 53a7a2170..bc153f890 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/HudComponent.java @@ -8,7 +8,8 @@ import java.util.List; public abstract class HudComponent { // Stored as percentages (0-100) of the current screen resolution. - protected int posX = 50, posY = 50, scale = 100, textAlign = 0; + public float posX = 50, posY = 50; + protected int scale = 100, textAlign = 0; public boolean enabled = true; public boolean hasData = false; diff --git a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java index 8ed5ece3a..ee6a6fe51 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java +++ b/src/main/java/noppes/npcs/client/gui/hud/QuestTrackingComponent.java @@ -113,10 +113,10 @@ public class QuestTrackingComponent extends HudComponent { @Override public void save() { ConfigClient.QuestOverlayX = posX; - ConfigClient.QuestOverlayXProperty.set(ConfigClient.QuestOverlayX); + ConfigClient.QuestOverlayXProperty.set((double) ConfigClient.QuestOverlayX); ConfigClient.QuestOverlayY = posY; - ConfigClient.QuestOverlayYProperty.set(ConfigClient.QuestOverlayY); + ConfigClient.QuestOverlayYProperty.set((double) ConfigClient.QuestOverlayY); ConfigClient.QuestOverlayScale = scale; ConfigClient.QuestOverlayScaleProperty.set(ConfigClient.QuestOverlayScale); @@ -218,8 +218,8 @@ public class QuestTrackingComponent extends HudComponent { int compHeight = (int) (overlayHeight * effectiveScale); int centerX = (res.getScaledWidth() - compWidth) / 2; int centerY = (res.getScaledHeight() - compHeight) / 2; - posX = (int) (100F * centerX / res.getScaledWidth()); - posY = (int) (100F * centerY / res.getScaledHeight()); + posX = 100F * centerX / res.getScaledWidth(); + posY = 100F * centerY / res.getScaledHeight(); } else { super.onEditorButtonPressed(button); } diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java new file mode 100644 index 000000000..4b3be2d6a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarComponent.java @@ -0,0 +1,683 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import net.minecraft.client.Minecraft; +import noppes.npcs.client.ClientProxy; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.hud.HudComponent; +import noppes.npcs.config.ConfigClient; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerAbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +@SideOnly(Side.CLIENT) +public class AbilityHotbarComponent extends HudComponent { + public static final int TOTAL_SLOTS = AbilityHotbarData.TOTAL_SLOTS; + + private static final int BASE_SLOT_SIZE = 24; + private static final int BASE_SPACING = 28; + + private AbilityHotbarSlotRenderer[] slots = new AbilityHotbarSlotRenderer[TOTAL_SLOTS]; + + // Filtered carousel: only filled slots + one deselect entry + // Each entry is a raw slot index (0-11), or -1 for the deselect slot + private int[] activeIndices = new int[0]; + private int activeCenter = 0; + + private float scrollOffset = 0f; + private long scrollStartTime = 0; + private static final long SCROLL_DURATION = 150; + + private long lastUpdateTime = 0; + private static final long UPDATE_INTERVAL = 500; + + // Debounce: delay sending selection packet + private String pendingSelectKey = null; + private long pendingSelectTime = 0; + private static final long SELECT_DEBOUNCE = 300; + + // Grace period: don't let server state override local state after user interaction + private long lastUserCycleTime = 0; + private static final long USER_CYCLE_GRACE = 1000; + + // Fade: when ShowAlways=false, fade in/out when HUD key is held + private float fadeAlpha = 0f; + private long lastFadeTime = 0; + private static final float FADE_SPEED = 3f; // per second — ~333ms full transition + + private Minecraft mc; + + public AbilityHotbarComponent(Minecraft mc) { + this.mc = mc; + updateOverlayDimensions(); + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i] = new AbilityHotbarSlotRenderer(i); + } + load(); + } + + private int getEffectiveVisibleSlots() { + int configMax = ConfigClient.AbilityHotbarVisibleSlots; + if (configMax != 3 && configMax != 5 && configMax != 7) configMax = 5; + int filledCount = activeIndices.length - 1; // subtract deselect slot + if (filledCount < 0) filledCount = 0; + if (filledCount < 5) return Math.min(configMax, 3); + if (filledCount < 7) return Math.min(configMax, 5); + return configMax; + } + + private void updateOverlayDimensions() { + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + int visibleSlots = getEffectiveVisibleSlots(); + int span = BASE_SPACING * (visibleSlots - 1) + BASE_SLOT_SIZE; + int thick = BASE_SLOT_SIZE + 4; + if (isHorizontal) { + overlayWidth = span; + overlayHeight = thick; + } else { + overlayWidth = thick; + overlayHeight = span; + } + } + + @Override + public void loadData(NBTTagCompound compound) { + } + + @Override + public void load() { + posX = ConfigClient.AbilityHotbarX; + posY = ConfigClient.AbilityHotbarY; + scale = ConfigClient.AbilityHotbarScale; + enabled = ConfigClient.AbilityHotbarEnabled; + } + + @Override + public void save() { + ConfigClient.AbilityHotbarX = posX; + ConfigClient.AbilityHotbarXProperty.set((double) posX); + + ConfigClient.AbilityHotbarY = posY; + ConfigClient.AbilityHotbarYProperty.set((double) posY); + + ConfigClient.AbilityHotbarScale = scale; + ConfigClient.AbilityHotbarScaleProperty.set(scale); + + ConfigClient.AbilityHotbarEnabled = enabled; + ConfigClient.AbilityHotbarEnabledProperty.set(enabled); + + ConfigClient.AbilityHotbarHorizontalProperty.set(ConfigClient.AbilityHotbarHorizontal); + ConfigClient.AbilityHotbarAltTextureProperty.set(ConfigClient.AbilityHotbarAltTexture); + ConfigClient.AbilityHotbarTextPositionProperty.set(ConfigClient.AbilityHotbarTextPosition); + ConfigClient.AbilityHotbarVisibleSlotsProperty.set(ConfigClient.AbilityHotbarVisibleSlots); + ConfigClient.AbilityHotbarShowAlwaysProperty.set(ConfigClient.AbilityHotbarShowAlways); + ConfigClient.AbilityHotbarTextVisibilityProperty.set(ConfigClient.AbilityHotbarTextVisibility); + + if (ConfigClient.config.hasChanged()) { + ConfigClient.config.save(); + } + } + + @Override + public void renderOnScreen(float partialTicks) { + if (!enabled || isEditting) return; + if (mc.thePlayer == null || mc.currentScreen != null) return; + if (!hasAnyAbilities()) return; + + // Fade logic: when ShowAlways=false, only show while HUD key is held + boolean showAlways = ConfigClient.AbilityHotbarShowAlways; + long now = Minecraft.getSystemTime(); + if (!showAlways) { + boolean hudKeyHeld = isHudKeyHeld(); + float dt = lastFadeTime > 0 ? (now - lastFadeTime) / 1000f : 0f; + dt = Math.min(dt, 0.1f); // cap to avoid jumps after pauses + lastFadeTime = now; + if (hudKeyHeld || pendingSelectKey != null || scrollOffset != 0f) { + fadeAlpha = Math.min(1f, fadeAlpha + FADE_SPEED * dt); + } else { + fadeAlpha = Math.max(0f, fadeAlpha - FADE_SPEED * dt); + } + if (fadeAlpha <= 0f) return; + } else { + fadeAlpha = 1f; + lastFadeTime = now; + } + + long currentTime = Minecraft.getSystemTime(); + if (currentTime - lastUpdateTime > UPDATE_INTERVAL) { + updateAbilities(); + lastUpdateTime = currentTime; + } + + // Flush debounced selection packet + if (pendingSelectKey != null && currentTime - pendingSelectTime >= SELECT_DEBOUNCE) { + PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(pendingSelectKey)); + pendingSelectKey = null; + } + + updateScrollAnimation(); + updateOverlayDimensions(); + + if (activeIndices.length == 0) return; + + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + float effectiveScale = getEffectiveScale(sr); + int visibleSlots = getEffectiveVisibleSlots(); + int half = visibleSlots / 2; + + int actualX = (int) (posX / 100.0f * sr.getScaledWidth()); + int actualY = (int) (posY / 100.0f * sr.getScaledHeight()); + + GL11.glPushMatrix(); + GL11.glTranslatef(actualX, actualY, 0); + GL11.glScalef(effectiveScale, effectiveScale, 1); + + int centerX = overlayWidth / 2; + int centerY = overlayHeight / 2; + + // Compute text visibility: 0=Shown, 1=Hidden, 2=Held + boolean showText; + int textVis = ConfigClient.AbilityHotbarTextVisibility; + if (textVis == 1) { + showText = false; + } else if (textVis == 2) { + showText = isHudKeyHeld(); + } else { + showText = true; + } + + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i].updateNameFade(); + } + + for (int offset = -half; offset <= half; offset++) { + int activeIdx = ((activeCenter + offset) % activeIndices.length + activeIndices.length) % activeIndices.length; + int rawSlotIndex = activeIndices[activeIdx]; + + float visualPos = offset + scrollOffset; + float absDist = Math.abs(visualPos); + + float slotScale; + if (absDist <= 1f) { + slotScale = 1.0f - 0.25f * absDist; + } else { + slotScale = 0.75f - 0.15f * (absDist - 1f); + } + slotScale = Math.max(0.1f, slotScale); + + int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale)); + + int cx, cy; + if (isHorizontal) { + cx = centerX + (int) (visualPos * BASE_SPACING); + cy = centerY; + } else { + cx = centerX; + cy = centerY + (int) (visualPos * BASE_SPACING); + } + + float maxDist = half + 0.5f; + if (absDist > maxDist) continue; + + float edgeAlpha = absDist > half - 0.5f ? 1f - (absDist - (half - 0.5f)) : 1f; + float slotAlpha = edgeAlpha * fadeAlpha; + boolean isCenter = (offset == 0 && scrollOffset == 0f); + + // Compute per-slot cooldown progress (all slots, not just center) + float slotCooldown = 0f; + if (rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null) { + slotCooldown = getCooldownProgressForSlot(rawSlotIndex); + } + + if (rawSlotIndex == -1) { + // Deselect slot — draw empty marker + drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha); + } else { + slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText); + } + } + + GL11.glPopMatrix(); + } + + private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha) { + float radius = size / 2f; + float baseAlpha = isCenter ? 0.9f : 0.6f; + float a = baseAlpha * alpha; + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + GL11.glPushMatrix(); + GL11.glTranslatef(cx, cy, 0); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + if (isCenter) { + GL11.glColor4f(0.5f, 0.2f, 0.2f, a); + } else { + GL11.glColor4f(0.3f, 0.3f, 0.3f, a); + } + + if (altTexture) { + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(-radius, -radius); + GL11.glVertex2f(radius, -radius); + GL11.glVertex2f(radius, radius); + GL11.glVertex2f(-radius, radius); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + for (int i = 0; i <= 32; i++) { + double angle = 2 * Math.PI * i / 32; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + + // Draw X mark + if (isCenter) { + GL11.glColor4f(0.8f, 0.4f, 0.4f, alpha); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, alpha * 0.8f); + } + float xSize = radius * 0.4f; + GL11.glLineWidth(2.0f); + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(-xSize, -xSize); + GL11.glVertex2f(xSize, xSize); + GL11.glVertex2f(-xSize, xSize); + GL11.glVertex2f(xSize, -xSize); + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + + @Override + public void renderEditing() { + isEditting = true; + updateOverlayDimensions(); + + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + float effectiveScale = getEffectiveScale(sr); + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + FontRenderer fr = mc.fontRenderer; + int visibleSlots = getEffectiveVisibleSlots(); + int half = visibleSlots / 2; + + int actualX = (int) (posX / 100.0f * sr.getScaledWidth()); + int actualY = (int) (posY / 100.0f * sr.getScaledHeight()); + + GL11.glPushMatrix(); + GL11.glTranslatef(actualX, actualY, 0); + GL11.glScalef(effectiveScale, effectiveScale, 1); + + int centerX = overlayWidth / 2; + int centerY = overlayHeight / 2; + + int[] slotCx = new int[visibleSlots]; + int[] slotCy = new int[visibleSlots]; + int[] slotSizes = new int[visibleSlots]; + + for (int offset = -half; offset <= half; offset++) { + float absDist = Math.abs(offset); + float slotScale; + if (absDist <= 1f) { + slotScale = 1.0f - 0.25f * absDist; + } else { + slotScale = 0.75f - 0.15f * (absDist - 1f); + } + slotScale = Math.max(0.1f, slotScale); + int scaledSize = Math.max(1, (int) (BASE_SLOT_SIZE * slotScale)); + + int cx, cy; + if (isHorizontal) { + cx = centerX + offset * BASE_SPACING; + cy = centerY; + } else { + cx = centerX; + cy = centerY + offset * BASE_SPACING; + } + + int idx = offset + half; + slotCx[idx] = cx; + slotCy[idx] = cy; + slotSizes[idx] = scaledSize; + + float radius = scaledSize / 2f; + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + float alpha = offset == 0 ? 0.9f : 0.6f; + if (offset == 0) { + GL11.glColor4f(0.8f, 0.8f, 0.2f, alpha); + } else { + GL11.glColor4f(0.4f, 0.4f, 0.4f, alpha); + } + + if (altTexture) { + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(cx - radius, cy - radius); + GL11.glVertex2f(cx + radius, cy - radius); + GL11.glVertex2f(cx + radius, cy + radius); + GL11.glVertex2f(cx - radius, cy + radius); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(cx, cy); + for (int i = 0; i <= 32; i++) { + double angle = 2 * Math.PI * i / 32; + GL11.glVertex2f(cx + (float) (Math.cos(angle) * radius), cy + (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + } + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + for (int i = 0; i < visibleSlots; i++) { + String label = String.valueOf(i + 1); + float labelScale = slotSizes[i] / 24.0f; + if (labelScale < 0.4f) continue; + + int textColor = (i == half) ? 0xFFFFFFFF : 0xAABBBBBB; + int textW = fr.getStringWidth(label); + + GL11.glPushMatrix(); + GL11.glTranslatef(slotCx[i], slotCy[i], 0); + GL11.glScalef(labelScale, labelScale, 1); + fr.drawString(label, -textW / 2, -fr.FONT_HEIGHT / 2, textColor); + GL11.glPopMatrix(); + } + + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + String modeLabel = altTexture ? "Square" : "Circle"; + int modeLabelW = fr.getStringWidth(modeLabel); + fr.drawStringWithShadow(modeLabel, overlayWidth / 2 - modeLabelW / 2, overlayHeight + 2, 0xAA888888); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(0.2f, 0.8f, 0.2f, 0.8f); + GL11.glLineWidth(1.0f); + GL11.glBegin(GL11.GL_LINE_LOOP); + GL11.glVertex2f(0, 0); + GL11.glVertex2f(overlayWidth, 0); + GL11.glVertex2f(overlayWidth, overlayHeight); + GL11.glVertex2f(0, overlayHeight); + GL11.glEnd(); + + GL11.glColor4f(0.8f, 0.8f, 0.8f, 0.9f); + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(overlayWidth - 10, overlayHeight - 10); + GL11.glVertex2f(overlayWidth, overlayHeight - 10); + GL11.glVertex2f(overlayWidth, overlayHeight); + GL11.glVertex2f(overlayWidth - 10, overlayHeight); + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + GL11.glPopMatrix(); + } + + @Override + public void addEditorButtons(List buttonList) { + super.addEditorButtons(buttonList); + String orientLabel = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical"; + buttonList.add(new GuiButton(1, 0, 0, 120, 20, orientLabel)); + + String texLabel = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; + buttonList.add(new GuiButton(2, 0, 0, 120, 20, texLabel)); + + buttonList.add(new GuiButton(3, 0, 0, 120, 20, getTextPositionLabel())); + buttonList.add(new GuiButton(4, 0, 0, 120, 20, "Slots: " + ConfigClient.AbilityHotbarVisibleSlots)); + buttonList.add(new GuiButton(5, 0, 0, 120, 20, ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key")); + buttonList.add(new GuiButton(6, 0, 0, 120, 20, getTextVisibilityLabel())); + } + + @Override + public void onEditorButtonPressed(GuiButton button) { + if (button.id == 1) { + ConfigClient.AbilityHotbarHorizontal = !ConfigClient.AbilityHotbarHorizontal; + button.displayString = ConfigClient.AbilityHotbarHorizontal ? "Horizontal" : "Vertical"; + updateOverlayDimensions(); + } else if (button.id == 2) { + ConfigClient.AbilityHotbarAltTexture = !ConfigClient.AbilityHotbarAltTexture; + button.displayString = ConfigClient.AbilityHotbarAltTexture ? "Square" : "Circle"; + } else if (button.id == 3) { + // Toggle between 1 (Above/Left) and 2 (Below/Right) + ConfigClient.AbilityHotbarTextPosition = ConfigClient.AbilityHotbarTextPosition == 1 ? 2 : 1; + button.displayString = getTextPositionLabel(); + } else if (button.id == 4) { + int current = ConfigClient.AbilityHotbarVisibleSlots; + if (current <= 3) ConfigClient.AbilityHotbarVisibleSlots = 5; + else if (current <= 5) ConfigClient.AbilityHotbarVisibleSlots = 7; + else ConfigClient.AbilityHotbarVisibleSlots = 3; + button.displayString = "Slots: " + ConfigClient.AbilityHotbarVisibleSlots; + updateOverlayDimensions(); + } else if (button.id == 5) { + ConfigClient.AbilityHotbarShowAlways = !ConfigClient.AbilityHotbarShowAlways; + button.displayString = ConfigClient.AbilityHotbarShowAlways ? "Show: Always" : "Show: Hold Key"; + } else if (button.id == 6) { + ConfigClient.AbilityHotbarTextVisibility = (ConfigClient.AbilityHotbarTextVisibility + 1) % 3; + button.displayString = getTextVisibilityLabel(); + } else { + super.onEditorButtonPressed(button); + } + } + + private String getTextPositionLabel() { + boolean h = ConfigClient.AbilityHotbarHorizontal; + switch (ConfigClient.AbilityHotbarTextPosition) { + case 1: return h ? "Text: Above" : "Text: Left"; + case 2: return h ? "Text: Below" : "Text: Right"; + default: return h ? "Text: Below" : "Text: Right"; + } + } + + private String getTextVisibilityLabel() { + switch (ConfigClient.AbilityHotbarTextVisibility) { + case 0: return "Text: Shown"; + case 1: return "Text: Hidden"; + case 2: return "Text: Held"; + default: return "Text: Shown"; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Ability Update & Scroll + // ═══════════════════════════════════════════════════════════════════ + + private void updateAbilities() { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null) return; + + PlayerAbilityHotbarData hotbarData = playerData.hotbarData; + if (hotbarData == null) return; + + for (int i = 0; i < TOTAL_SLOTS; i++) { + AbilityHotbarData slotData = hotbarData.slots[i]; + String key = slotData.isEmpty() ? null : slotData.abilityKey; + Ability ability = null; + IAbilityAction action = null; + if (key != null && AbilityController.Instance != null) { + if (slotData.isChainKey()) { + action = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + } else { + ability = AbilityController.Instance.resolveAbility(key); + action = ability; + } + if (ability == null && action == null) key = null; + } + slots[i].setAbility(key, ability, action); + } + + // Rebuild active indices: filled slots + one deselect slot (-1) + ArrayList active = new ArrayList<>(); + for (int i = 0; i < TOTAL_SLOTS; i++) { + if (slots[i].abilityKey != null) { + active.add(i); + } + } + active.add(-1); // Deselect slot at the end + activeIndices = new int[active.size()]; + for (int i = 0; i < active.size(); i++) { + activeIndices[i] = active.get(i); + } + + // Clamp activeCenter + if (activeCenter >= activeIndices.length) { + activeCenter = 0; + } + + // Don't override local selection state while user is scrolling, debounce is pending, + // or within the grace period after the last user interaction. + // This prevents the server state from fighting the local carousel position. + long now = Minecraft.getSystemTime(); + if (pendingSelectKey != null || scrollOffset != 0f || (now - lastUserCycleTime < USER_CYCLE_GRACE)) { + return; + } + + // Sync selected state and find which active index is selected + if (playerData.abilityData != null) { + String selectedKey = playerData.abilityData.getSelectedAbilityKey(); + boolean foundSelected = false; + for (int i = 0; i < TOTAL_SLOTS; i++) { + AbilityHotbarData slotData = hotbarData.slots[i]; + boolean sel = selectedKey != null && !slotData.isEmpty() + && selectedKey.equals(slotData.abilityKey); + slots[i].setSelectedState(sel); + if (sel) { + // Find this slot's position in activeIndices + for (int j = 0; j < activeIndices.length; j++) { + if (activeIndices[j] == i) { + activeCenter = j; + foundSelected = true; + break; + } + } + } + } + if (!foundSelected) { + // No ability selected on server — center on deselect slot + for (int j = 0; j < activeIndices.length; j++) { + if (activeIndices[j] == -1) { + activeCenter = j; + break; + } + } + } + } + } + + private boolean isHudKeyHeld() { + if (ClientProxy.AbilityHudKey == null) return false; + int keyCode = ClientProxy.AbilityHudKey.getKeyCode(); + return keyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(keyCode); + } + + public boolean hasAnyAbilities() { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.hotbarData == null) return false; + return playerData.hotbarData.hasAnyAbilities(); + } + + /** + * Get cooldown progress for a hotbar slot. + * Per-ability cooldown abilities use their own cooldown; others use global. + * @return 1.0 = fully on cooldown, 0.0 = ready + */ + private float getCooldownProgressForSlot(int slotIndex) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) return 0f; + + String key = slots[slotIndex].abilityKey; + Ability ability = slots[slotIndex].ability; + + if (ability != null && ability.isPerAbilityCooldown()) { + return playerData.abilityData.getPerAbilityCooldownProgress(key); + } else { + return playerData.abilityData.getGlobalCooldownProgress(); + } + } + + public void onCycleNext() { + cycle(1); + } + + public void onCyclePrev() { + cycle(-1); + } + + private void cycle(int direction) { + if (!enabled) return; + if (mc.thePlayer == null || mc.currentScreen != null) return; + if (activeIndices.length == 0) return; + + activeCenter = ((activeCenter + direction) % activeIndices.length + activeIndices.length) % activeIndices.length; + scrollOffset = direction; + long now = Minecraft.getSystemTime(); + scrollStartTime = now; + lastUserCycleTime = now; + + int rawSlotIndex = activeIndices[activeCenter]; + + // Update selection states locally + for (int i = 0; i < TOTAL_SLOTS; i++) { + slots[i].setSelectedState(i == rawSlotIndex); + } + + // Debounce: queue the selection, don't send immediately + String keyToSend = rawSlotIndex >= 0 && slots[rawSlotIndex].abilityKey != null + ? slots[rawSlotIndex].abilityKey : ""; + pendingSelectKey = keyToSend; + pendingSelectTime = Minecraft.getSystemTime(); + } + + private void updateScrollAnimation() { + if (scrollOffset == 0f) return; + + long now = Minecraft.getSystemTime(); + float t = (float) (now - scrollStartTime) / SCROLL_DURATION; + t = Math.min(t, 1f); + + float eased = easeOutCubic(t); + float initialOffset = scrollOffset < 0 ? -1f : 1f; + scrollOffset = initialOffset * (1f - eased); + + if (t >= 1f) scrollOffset = 0f; + } + + private float easeOutCubic(float x) { + float v = 1 - x; + return 1 - v * v * v; + } + + public void refresh() { + updateAbilities(); + lastUpdateTime = Minecraft.getSystemTime(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java new file mode 100644 index 000000000..c91ad016b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityHotbarSlotRenderer.java @@ -0,0 +1,302 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import noppes.npcs.config.ConfigClient; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.opengl.GL11; + +@SideOnly(Side.CLIENT) +public class AbilityHotbarSlotRenderer extends Gui { + private static final int CIRCLE_SEGMENTS = 32; + private static final long NAME_FADE_DURATION = 180; + + public int index; + public String abilityKey = null; + public Ability ability = null; + public IAbilityAction action = null; + private AbilityIcon icon = null; + + public boolean isSelected = false; + public float nameAlpha = 0f; + private boolean nameFadingIn = false; + private long nameFadeStartTime = 0; + + public AbilityHotbarSlotRenderer(int index) { + this.index = index; + } + + public void setAbility(String key, Ability ability, IAbilityAction action) { + this.abilityKey = key; + this.ability = ability; + this.action = action; + if (ability != null) { + this.icon = AbilityIcon.fromAbility(ability); + } else if (action instanceof ChainedAbility) { + this.icon = AbilityIcon.fromChainedAbility((ChainedAbility) action); + } else { + this.icon = null; + } + } + + public void drawCarousel(Minecraft mc, ScaledResolution sr, float cooldownProgress, + int cx, int cy, int size, boolean isCenter, float slotAlpha, + boolean showText) { + float nameAlpha = this.nameAlpha; + boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal; + if (size <= 0 || slotAlpha <= 0) return; + float radius = size / 2f; + float baseAlpha = isCenter ? 0.9f : 0.6f; + float alpha = baseAlpha * slotAlpha; + + GL11.glPushMatrix(); + GL11.glTranslatef(cx, cy, 0); + + boolean altTexture = ConfigClient.AbilityHotbarAltTexture; + + if (altTexture) { + drawRoundedRect(-radius, -radius, radius, radius, 0.6f, 0.6f, 0.6f, 0.75f * alpha, false); + if (isCenter) { + drawRoundedRect(-radius, -radius, radius, radius, 0.8f, 0.8f, 0.2f, alpha, true); + } else { + drawRoundedRect(-radius, -radius, radius, radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true); + } + } else { + if (isCenter) { + drawCircle(radius, 0.8f, 0.8f, 0.2f, 0.66f * alpha, false); + drawCircle(radius, 0.8f, 0.8f, 0.2f, alpha, true); + } else { + drawCircle(radius, 1f, 1f, 1f, 0.66f * alpha, false); + drawCircle(radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true); + } + } + + // Ability icon + if (icon != null) { + GL11.glPushMatrix(); + float targetSize = size * 0.55f; + float iconNaturalSize = Math.max(icon.width, icon.height); + if (iconNaturalSize <= 0) iconNaturalSize = 16f; + float iconScale = targetSize / iconNaturalSize; + GL11.glScalef(iconScale, iconScale, 1); + GL11.glColor4f(1, 1, 1, slotAlpha); + icon.draw(getToggleState()); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + + // Cooldown overlay (all slots) + if (cooldownProgress > 0 && abilityKey != null) { + drawCooldownOverlay(radius, cooldownProgress, altTexture, slotAlpha); + } + + GL11.glPopMatrix(); + + // Ability name on center slot (respects text position and visibility config) + int textPos = ConfigClient.AbilityHotbarTextPosition; + if (showText && isCenter && action != null && nameAlpha > 0) { + FontRenderer fr = mc.fontRenderer; + String name = getAbilityName(); + if (name != null && !name.isEmpty()) { + int a = (int) (nameAlpha * 255) & 0xFF; + int nameColor = (a << 24) | (getNameColor() & 0x00FFFFFF); + int nameX, nameY; + if (isHorizontal) { + nameX = cx - fr.getStringWidth(name) / 2; + if (textPos == 1) { + nameY = cy - (int) radius - fr.FONT_HEIGHT - 2; // Above + } else { + nameY = cy + (int) radius + 2; // Below + } + } else { + nameY = cy - fr.FONT_HEIGHT / 2; + if (textPos == 1) { + nameX = cx - (int) radius - fr.getStringWidth(name) - 4; // Left + } else { + nameX = cx + (int) radius + 4; // Right + } + } + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, nameAlpha); + fr.drawStringWithShadow(name, nameX, nameY, nameColor); + GL11.glDisable(GL11.GL_BLEND); + GL11.glColor4f(1, 1, 1, 1); + } + } + } + + private void drawRoundedRect(float x1, float y1, float x2, float y2, + float r, float g, float b, float a, boolean outline) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(r, g, b, a); + + if (outline) { + GL11.glLineWidth(2.0f); + GL11.glBegin(GL11.GL_LINE_LOOP); + } else { + GL11.glBegin(GL11.GL_QUADS); + } + + GL11.glVertex2f(x1, y1); + GL11.glVertex2f(x2, y1); + GL11.glVertex2f(x2, y2); + GL11.glVertex2f(x1, y2); + GL11.glEnd(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawCircle(float radius, float r, float g, float b, float a, boolean outline) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(r, g, b, a); + + if (outline) { + GL11.glLineWidth(1.5f); + GL11.glBegin(GL11.GL_LINE_LOOP); + } else { + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + } + + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + /** + * Draw a cooldown overlay on the slot. + * progress: 1.0 = fully on cooldown (just started), 0.0 = ready + * Renders a filled shape covering the entire slot that transitions from red to green. + */ + private void drawCooldownOverlay(float radius, float progress, boolean altTexture, float slotAlpha) { + progress = Math.min(1f, Math.max(0f, progress)); + if (progress <= 0f) return; + + // Color: red (progress=1.0) → orange → yellow-green → green (progress→0.0) + float cr, cg, cb; + if (progress > 0.5f) { + float t = (progress - 0.5f) * 2f; // 1.0 at progress=1.0, 0.0 at progress=0.5 + cr = 0.8f; + cg = 0.15f + 0.25f * (1f - t); // 0.15 → 0.4 + cb = 0.1f; + } else if (progress > 0.2f) { + float t = (progress - 0.2f) / 0.3f; // 1.0 at 0.5, 0.0 at 0.2 + cr = 0.8f * t + 0.3f * (1f - t); // 0.8 → 0.3 + cg = 0.4f * t + 0.7f * (1f - t); // 0.4 → 0.7 + cb = 0.1f; + } else { + float t = progress / 0.2f; // 1.0 at 0.2, 0.0 at 0.0 + cr = 0.3f * t + 0.1f * (1f - t); // 0.3 → 0.1 + cg = 0.7f * t + 0.7f * (1f - t); // 0.7 + cb = 0.1f + 0.1f * (1f - t); // 0.1 → 0.2 + } + + // Semi-transparent so icon is visible underneath; fade out near end + float overlayAlpha = 0.5f * slotAlpha * Math.min(1f, progress * 3f); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(cr, cg, cb, overlayAlpha); + + if (altTexture) { + // Square slot: full filled rectangle + GL11.glBegin(GL11.GL_QUADS); + GL11.glVertex2f(-radius, -radius); + GL11.glVertex2f(radius, -radius); + GL11.glVertex2f(radius, radius); + GL11.glVertex2f(-radius, radius); + GL11.glEnd(); + } else { + // Circle slot: full filled circle + GL11.glBegin(GL11.GL_TRIANGLE_FAN); + GL11.glVertex2f(0, 0); + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = 2 * Math.PI * i / CIRCLE_SEGMENTS; + GL11.glVertex2f((float) (Math.cos(angle) * radius), (float) (Math.sin(angle) * radius)); + } + GL11.glEnd(); + } + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1); + } + + private String getAbilityName() { + if (ability != null) { + int state = getToggleState(); + if (state > 0) { + String label = ability.getToggleStateLabel(state); + if (label != null) return label; + } + return ability.getDisplayName(); + } + if (action instanceof ChainedAbility) return ((ChainedAbility) action).getDisplayName(); + return action != null ? action.getName() : ""; + } + + private int getToggleState() { + if (ability == null || !ability.isToggleable()) return 0; + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer == null) return 0; + PlayerData playerData = PlayerData.get(mc.thePlayer); + if (playerData == null || playerData.abilityData == null) return 0; + return playerData.abilityData.getToggleState(abilityKey); + } + + private int getNameColor() { + if (ability != null && ability.isToggleable()) { + return getToggleState() > 0 ? 0xFF55FF55 : 0xFFFF5555; + } + return 0xFFFFFFFF; + } + + public void setSelectedState(boolean newSelectState) { + if (!isSelected && newSelectState) { + nameFadingIn = true; + nameFadeStartTime = Minecraft.getSystemTime(); + } + if (isSelected && !newSelectState) { + nameFadingIn = false; + nameFadeStartTime = Minecraft.getSystemTime(); + } + isSelected = newSelectState; + } + + public void updateNameFade() { + long now = Minecraft.getSystemTime(); + float t = (float) (now - nameFadeStartTime) / NAME_FADE_DURATION; + t = Math.min(1f, Math.max(0f, t)); + if (nameFadingIn) { + nameAlpha = t; + } else { + nameAlpha = 1f - t; + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java new file mode 100644 index 000000000..1371bcc2a --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java @@ -0,0 +1,140 @@ +package noppes.npcs.client.gui.hud.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityIconData; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.ImageData; +import org.lwjgl.opengl.GL11; + +@SideOnly(Side.CLIENT) +public class AbilityIcon extends Gui { + private static final ResourceLocation FALLBACK_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/ability_fallback.png"); + + // Backed by AbilityIconData + private final AbilityIconData data; + public int width; + public int height; + + private AbilityIcon(AbilityIconData data) { + this.data = data; + this.width = data.width; + this.height = data.height; + } + + public static AbilityIcon fromAbility(Ability ability) { + if (ability != null) { + return new AbilityIcon(AbilityIconData.fromAbility(ability)); + } + return fromDefaults(); + } + + public static AbilityIcon fromChainedAbility(ChainedAbility chain) { + if (chain != null) { + return new AbilityIcon(AbilityIconData.fromChainedAbility(chain)); + } + return fromDefaults(); + } + + public static AbilityIcon fromAction(IAbilityAction action) { + if (action instanceof Ability) return fromAbility((Ability) action); + if (action instanceof ChainedAbility) return fromChainedAbility((ChainedAbility) action); + return fromDefaults(); + } + + private static AbilityIcon fromDefaults() { + return new AbilityIcon(AbilityIconData.fromCustomData(new NBTTagCompound())); + } + + public void draw() { + draw(0); + } + + public void draw(int state) { + TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; + + ImageData imageData = null; + if (data.hasTexture()) { + imageData = ClientCacheHandler.getImageData(data.texture); + } + + GL11.glPushMatrix(); + GL11.glColor4f(1, 1, 1, 1); + + Tessellator t; + + if (imageData == null || !imageData.imageLoaded()) { + GL11.glScalef(1.0f, 1.0f, 1); + renderEngine.bindTexture(FALLBACK_TEXTURE); + t = getFallbackTessellator(); + } else { + GL11.glScalef(data.scale, data.scale, 1); + renderEngine.bindTexture(imageData.getLocation()); + t = getTessellator(imageData, state); + } + + t.draw(); + GL11.glPopMatrix(); + } + + private Tessellator getTessellator(ImageData imageData, int state) { + float hw = data.width / 2f; + float hh = data.height / 2f; + + float texW = imageData.getTotalWidth(); + float texH = imageData.getTotalHeight(); + + int ix = data.getIconXForState(state); + int iy = data.getIconYForState(state); + + float u1 = ix / texW; + float v1 = iy / texH; + float u2 = (ix + data.width) / texW; + float v2 = (iy + data.height) / texH; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, u1, v2); + t.addVertexWithUV(hw, hh, zLevel, u2, v2); + t.addVertexWithUV(hw, -hh, zLevel, u2, v1); + t.addVertexWithUV(-hw, -hh, zLevel, u1, v1); + return t; + } + + private Tessellator getFallbackTessellator() { + float hw = 16f; + float hh = 16f; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, 0, 1); + t.addVertexWithUV(hw, hh, zLevel, 1, 1); + t.addVertexWithUV(hw, -hh, zLevel, 1, 0); + t.addVertexWithUV(-hw, -hh, zLevel, 0, 0); + return t; + } + + public boolean hasTexture() { + return data.hasTexture(); + } + + /** + * Returns the approximate visual size (max dimension) that draw() produces. + * Textured: max(width,height) * scale. Fallback: 32. + */ + public float getDrawSize() { + if (data.hasTexture()) { + return Math.max(width, height) * data.scale; + } + return 32f; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java index 45a527dca..05e83c5bc 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java @@ -88,10 +88,16 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); - if (listing != null && tradesContainer.isSellingAt(slot) && mouseButton == 1) { - // Right-click on own listing = show cancel - setPending(slot, PendingOp.CANCEL); - NoppesUtil.clickSound(); + if (listing != null && tradesContainer.isSellingAt(slot)) { + if (mouseButton == 0) { + // Left-click on own listing = view details + AuctionActionPacket.openBidding(listing.id); + NoppesUtil.clickSound(); + } else if (mouseButton == 1) { + // Right-click on own listing = show cancel + setPending(slot, PendingOp.CANCEL); + NoppesUtil.clickSound(); + } } else if (listing != null && tradesContainer.isBiddingAt(slot) && mouseButton == 0) { // Left-click on active bid = open bidding GUI to increase bid AuctionActionPacket.openBidding(listing.id); @@ -315,16 +321,13 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { AuctionListing listing = tradesContainer.getListingAt(slot); AuctionClaim claim = tradesContainer.getClaimAt(slot); - if (listing != null) { - if (tradesContainer.isSellingAt(slot)) { - tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.trades.activeListing")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel")); - } else if (tradesContainer.isBiddingAt(slot)) { - tooltip.add(EnumChatFormatting.AQUA + StatCollector.translateToLocal("auction.trades.activeBid")); - tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.winningBid")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToIncrease")); - } - } else if (claim != null) { + // Slots with items have tooltips handled by AuctionTooltipHandler via ItemTooltipEvent + if (listing != null) return; + if (claim != null && (claim.type == EnumClaimType.ITEM || + (claim.type == EnumClaimType.REFUND && claim.item != null))) return; + + // Non-item slots (currency claims, refund without item, unavailable) + if (claim != null) { switch (claim.type) { case CURRENCY: tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.soldClaim")); @@ -342,20 +345,6 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.outbidBy") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName); } tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName()); - // Show rebid option if item is present (active listing) - if (claim.item != null) { - tooltip.add(""); - tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid")); - tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund")); - return; // Skip the generic claim message - } - break; - case ITEM: - if (claim.isReturned) { - tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expiredClaim")); - } else { - tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.wonClaim")); - } break; } tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToClaim")); diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java new file mode 100644 index 000000000..1d0180463 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiAbilities.java @@ -0,0 +1,1004 @@ +package noppes.npcs.client.gui.player.inventory; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import kamkeel.npcs.controllers.data.ability.IAbilityAction; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket; +import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket; +import kamkeel.npcs.network.packets.player.ability.AbilityTogglePacket; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.hud.ability.AbilityIcon; +import noppes.npcs.client.gui.util.GuiMenuTopButton; +import noppes.npcs.client.gui.util.ISubGuiListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import tconstruct.client.tabs.AbstractTab; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener { + private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/standardbg.png"); + + // Sub-tab: 0 = Abilities, 1 = Toggles + private int subTab = 0; + private static final int BTN_TAB_ABILITIES = -200; + private static final int BTN_TAB_TOGGLES = -201; + + // ═══ Panel Bounds (relative to guiLeft/guiTop) ═══ + // Selection panel (RIGHT side - icon grid) + private int selLeft = 140; + private int selTop = 4; + private int selRight = 316; + private int selBottom = 150; + + // Information panel (LEFT side - ability details) + private int infoLeft = 5; + private int infoTop = 4; + private int infoRight = 137; + private int infoBottom = 150; + + // Hotbar panel (BOTTOM) + private int hbLeft = 5; + private int hbTop = 153; + private int hbRight = 316; + private int hbBottom = 190; + + // ═══ Grid Settings ═══ + private int gridPad = 3; + private int gridCellSize = 22; + private int gridCols = 7; + + // ═══ Hotbar Settings ═══ + private int hbSlotSize = 18; + private int hbSlotGap = 2; + private int hbSlots = AbilityHotbarData.TOTAL_SLOTS; + + // ═══ Info Panel Settings ═══ + private int infoPad = 5; + private int infoIconSize = 40; + + // ═══ Drag Settings ═══ + private int dragThreshold = 3; + + // ═══ Filtered ability data ═══ + private List filteredKeys = new ArrayList<>(); + private List filteredDisplayNames = new ArrayList<>(); + private List filteredIcons = new ArrayList<>(); + private List filteredAbilities = new ArrayList<>(); + private List filteredActions = new ArrayList<>(); + + // ═══ Grid state ═══ + private int scrollRow = 0; + private int hoveredGridIndex = -1; + private float[] gridHoverScale; + private int selectedIndex = -1; + + // ═══ Detail panel cache ═══ + private AbilityIcon cachedDetailIcon = null; + private int cachedDetailIndex = -1; + + // ═══ Hotbar state ═══ + private int hoveredSlotIndex = -1; + private AbilityIcon[] hotbarIcons = new AbilityIcon[AbilityHotbarData.TOTAL_SLOTS]; + + // ═══ Drag state ═══ + private boolean isDragging = false; + private boolean dragPending = false; + private String draggedKey = null; + private AbilityIcon draggedIcon = null; + private int dragSourceSlot = -1; + private int dragStartX, dragStartY; + private int dragMouseX, dragMouseY; + + // ═══ Close sync ═══ + private String initialSelectedKey = null; + + // ═══ Toggle double-tap ═══ + private long lastToggleClickTime = 0; + private int lastToggleClickIndex = -1; + + public GuiAbilities() { + super(); + xSize = 280; + ySize = 180; + + hbSlotSize = 23; + gridCellSize = 24; + gridCols = 7; + } + + @Override + public void initGui() { + super.initGui(); + + GuiMenuTopButton tabAbilities = new GuiMenuTopButton(BTN_TAB_ABILITIES, guiLeft + xSize - 10, guiTop - 17, "gui.abilities"); + tabAbilities.active = (subTab == 0); + addTopButton(tabAbilities); + + GuiMenuTopButton tabToggles = new GuiMenuTopButton(BTN_TAB_TOGGLES, "gui.toggles", tabAbilities); + tabToggles.active = (subTab == 1); + addTopButton(tabToggles); + + buildFilteredList(); + updateHotbarIcons(); + + // Capture initial selected key for close sync + if (initialSelectedKey == null) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + initialSelectedKey = playerData.abilityData.getSelectedAbilityKey(); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Data Building + // ═══════════════════════════════════════════════════════════════════ + + private void buildFilteredList() { + filteredKeys.clear(); + filteredDisplayNames.clear(); + filteredIcons.clear(); + filteredAbilities.clear(); + filteredActions.clear(); + cachedDetailIcon = null; + cachedDetailIndex = -1; + + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) return; + + List abilities = playerData.abilityData.getUnlockedAbilityList(); + + // Build temporary lists before sorting + List tempKeys = new ArrayList<>(); + List tempNames = new ArrayList<>(); + List tempIcons = new ArrayList<>(); + List tempAbilities = new ArrayList<>(); + List tempActions = new ArrayList<>(); + + for (String key : abilities) { + Ability ability = null; + IAbilityAction action = null; + + if (key.startsWith(AbilityHotbarData.CHAIN_PREFIX)) { + String chainKey = key.substring(AbilityHotbarData.CHAIN_PREFIX.length()); + if (AbilityController.Instance != null) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey); + action = chain; + } + } else if (AbilityController.Instance != null) { + ability = AbilityController.Instance.resolveAbility(key); + action = ability; + } + + boolean isToggle = ability != null && ability.isToggleable(); + if (subTab == 0 && isToggle) continue; + if (subTab == 1 && !isToggle) continue; + + String displayName; + if (action instanceof ChainedAbility) { + displayName = "\u00A76\u2726 " + ((ChainedAbility) action).getDisplayName(); + } else if (ability != null) { + displayName = ability.getDisplayName(); + } else { + displayName = key; + } + + tempKeys.add(key); + tempNames.add(displayName); + tempIcons.add(AbilityIcon.fromAction(action)); + tempAbilities.add(ability); + tempActions.add(action); + } + + // Sort: toggles tab sorts enabled first, then alphabetically + List indices = new ArrayList<>(); + for (int i = 0; i < tempNames.size(); i++) indices.add(i); + final boolean sortTogglesFirst = (subTab == 1); + Collections.sort(indices, new Comparator() { + @Override + public int compare(Integer a, Integer b) { + if (sortTogglesFirst && playerData != null && playerData.abilityData != null) { + boolean aToggled = playerData.abilityData.isAbilityToggled(tempKeys.get(a)); + boolean bToggled = playerData.abilityData.isAbilityToggled(tempKeys.get(b)); + if (aToggled != bToggled) return aToggled ? -1 : 1; + } + return stripFormatting(tempNames.get(a)).compareToIgnoreCase(stripFormatting(tempNames.get(b))); + } + }); + + for (int idx : indices) { + filteredKeys.add(tempKeys.get(idx)); + filteredDisplayNames.add(tempNames.get(idx)); + filteredIcons.add(tempIcons.get(idx)); + filteredAbilities.add(tempAbilities.get(idx)); + filteredActions.add(tempActions.get(idx)); + } + + gridHoverScale = new float[filteredKeys.size()]; + Arrays.fill(gridHoverScale, 1.0f); + scrollRow = 0; + selectedIndex = -1; + } + + private String stripFormatting(String s) { + return s.replaceAll("\u00A7.", "").trim(); + } + + private void updateHotbarIcons() { + PlayerData playerData = ClientCacheHandler.playerData; + for (int i = 0; i < hbSlots; i++) { + hotbarIcons[i] = null; + if (playerData == null || playerData.hotbarData == null) continue; + AbilityHotbarData slotData = playerData.hotbarData.getSlot(i); + if (slotData == null || slotData.isEmpty()) continue; + + if (AbilityController.Instance != null) { + if (slotData.isChainKey()) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + if (chain != null) hotbarIcons[i] = AbilityIcon.fromChainedAbility(chain); + } else { + Ability ability = AbilityController.Instance.resolveAbility(slotData.abilityKey); + if (ability != null) hotbarIcons[i] = AbilityIcon.fromAbility(ability); + } + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Grid Positioning Helpers + // ═══════════════════════════════════════════════════════════════════ + + private int getGridVisibleRows() { + int usableHeight = (selBottom - selTop) - gridPad * 2; + return usableHeight / gridCellSize; + } + + private int getGridStartX() { + int panelWidth = selRight - selLeft; + int usableWidth = panelWidth - gridPad * 2; + int gridWidth = gridCols * gridCellSize; + int offsetX = (usableWidth - gridWidth) / 2; + return guiLeft + selLeft + gridPad + offsetX; + } + + private int getGridStartY() { + int panelHeight = selBottom - selTop; + int usableHeight = panelHeight - gridPad * 2; + int visibleRows = getGridVisibleRows(); + int gridHeight = visibleRows * gridCellSize; + int offsetY = (usableHeight - gridHeight) / 2; + return guiTop + selTop + gridPad + offsetY; + } + + private int getMaxScrollRow() { + int totalRows = (filteredKeys.size() + gridCols - 1) / gridCols; + return Math.max(0, totalRows - getGridVisibleRows()); + } + + // ═══════════════════════════════════════════════════════════════════ + // Drawing + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.renderEngine.bindTexture(resource); + drawTexturedModalRect(guiLeft, guiTop, 0, 0, 252, 195); + drawTexturedModalRect(guiLeft + 252, guiTop, 188, 0, 67, 195); + super.drawScreen(mouseX, mouseY, partialTicks); + + updateHoverState(mouseX, mouseY); + updateHoverScales(); + + // Panel backgrounds + drawGradientRect(guiLeft + selLeft, guiTop + selTop, guiLeft + selRight, guiTop + selBottom, 0xC0101010, 0xC0101010); + drawGradientRect(guiLeft + infoLeft, guiTop + infoTop, guiLeft + infoRight, guiTop + infoBottom, 0xC0101010, 0xC0101010); + drawGradientRect(guiLeft + hbLeft, guiTop + hbTop, guiLeft + hbRight, guiTop + hbBottom, 0xC0101010, 0xC0101010); + + // RIGHT panel: Selection grid (with scissor clipping) + drawIconGrid(mouseX, mouseY); + + // LEFT panel: Ability information + drawInfoPanel(); + + // BOTTOM panel: Hotbar + drawHotbarSection(mouseX, mouseY); + + // Drag ghost + if (isDragging && draggedIcon != null) { + drawDragGhost(mouseX, mouseY); + } + + // Tooltip (last - renders on top) + drawTooltip(mouseX, mouseY); + } + + private void drawIconGrid(int mouseX, int mouseY) { + int visibleRows = getGridVisibleRows(); + int gridStartX = getGridStartX(); + int gridStartY = getGridStartY(); + int startIndex = scrollRow * gridCols; + + // GL Scissor to clip grid content within the selection panel + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int scaleFactor = sr.getScaleFactor(); + int scissorX = (guiLeft + selLeft) * scaleFactor; + int scissorY = mc.displayHeight - (guiTop + selBottom) * scaleFactor; + int scissorW = (selRight - selLeft) * scaleFactor; + int scissorH = (selBottom - selTop) * scaleFactor; + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(scissorX, scissorY, scissorW, scissorH); + + int maxVisibleCount = gridCols * visibleRows; + for (int vi = 0; vi < maxVisibleCount; vi++) { + int absIndex = startIndex + vi; + if (absIndex >= filteredKeys.size()) break; + + int col = vi % gridCols; + int row = vi / gridCols; + int cellX = gridStartX + col * gridCellSize; + int cellY = gridStartY + row * gridCellSize; + + boolean isHovered = (hoveredGridIndex == absIndex) && !isDragging; + boolean isSelected = (selectedIndex == absIndex); + boolean isDragSource = isDragging && dragSourceSlot == -1 && draggedKey != null + && draggedKey.equals(filteredKeys.get(absIndex)); + + // Cell background + int bgColor; + if (isDragSource) bgColor = 0x40333333; + else if (isSelected) bgColor = 0x60505070; + else if (isHovered) bgColor = 0x60404060; + else bgColor = 0x40202030; + drawRect(cellX, cellY, cellX + gridCellSize - 1, cellY + gridCellSize - 1, bgColor); + + // Cell border + int borderColor; + if (isSelected) borderColor = 0xAA9999DD; + else if (isHovered) borderColor = 0xAA8888CC; + else borderColor = 0x40404060; + drawHorizontalLine(cellX, cellX + gridCellSize - 2, cellY, borderColor); + drawHorizontalLine(cellX, cellX + gridCellSize - 2, cellY + gridCellSize - 2, borderColor); + drawVerticalLine(cellX, cellY, cellY + gridCellSize - 2, borderColor); + drawVerticalLine(cellX + gridCellSize - 2, cellY, cellY + gridCellSize - 2, borderColor); + + GL11.glColor4f(1, 1, 1, 1); + + // Icon (state-aware for multi-state toggles) + AbilityIcon icon = filteredIcons.get(absIndex); + if (icon != null) { + float hoverScale = gridHoverScale[absIndex]; + float targetPixels = (gridCellSize - 4) * hoverScale; + float drawSize = icon.getDrawSize(); + float iconScale = targetPixels / drawSize; + + int iconCenterX = cellX + (gridCellSize - 1) / 2; + int iconCenterY = cellY + (gridCellSize - 1) / 2; + + int cellToggleState = 0; + Ability cellAbility = filteredAbilities.get(absIndex); + PlayerData cellPlayerData = ClientCacheHandler.playerData; + if (cellAbility != null && cellAbility.isToggleable() && cellPlayerData != null && cellPlayerData.abilityData != null) { + cellToggleState = cellPlayerData.abilityData.getToggleState(filteredKeys.get(absIndex)); + } + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCenterX, iconCenterY, 0); + GL11.glScalef(iconScale, iconScale, 1); + + float alpha = isDragSource ? 0.3f : 1.0f; + GL11.glColor4f(1, 1, 1, alpha); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + icon.draw(cellToggleState); + GL11.glColor4f(1, 1, 1, 1); + GL11.glPopMatrix(); + } + } + + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Restore GL state + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + // Scroll indicator (drawn outside scissor) + int totalRows = (filteredKeys.size() + gridCols - 1) / gridCols; + if (totalRows > visibleRows) { + FontRenderer fr = mc.fontRenderer; + String scrollText = (scrollRow + 1) + "/" + (totalRows - visibleRows + 1); + int textX = guiLeft + selRight - fr.getStringWidth(scrollText) - 4; + int textY = guiTop + selBottom + 1; + fr.drawStringWithShadow(scrollText, textX, textY, 0x888888); + } + } + + private void drawInfoPanel() { + int infoIndex = hoveredGridIndex >= 0 ? hoveredGridIndex : selectedIndex; + if (infoIndex < 0 || infoIndex >= filteredKeys.size()) return; + + FontRenderer fr = mc.fontRenderer; + int panelInnerLeft = guiLeft + infoLeft + infoPad; + int panelInnerTop = guiTop + infoTop + infoPad; + int panelInnerWidth = (infoRight - infoLeft) - infoPad * 2; + int y = panelInnerTop; + + // Cached icon for detail preview + if (cachedDetailIndex != infoIndex) { + cachedDetailIcon = filteredIcons.get(infoIndex); + cachedDetailIndex = infoIndex; + } + + // Get toggle state for icon rendering and state display + int toggleState = 0; + PlayerData togglePlayerData = ClientCacheHandler.playerData; + Ability infoAbility = filteredAbilities.get(infoIndex); + if (infoAbility != null && infoAbility.isToggleable() && togglePlayerData != null && togglePlayerData.abilityData != null) { + toggleState = togglePlayerData.abilityData.getToggleState(filteredKeys.get(infoIndex)); + } + + // Preview icon (centered, state-aware for multi-state toggles) + if (cachedDetailIcon != null) { + float drawSize = cachedDetailIcon.getDrawSize(); + float iconScale = (float) infoIconSize / drawSize; + + int iconCX = panelInnerLeft + panelInnerWidth / 2; + int iconCY = y + infoIconSize / 2 + 4; + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCX, iconCY, 0); + GL11.glScalef(iconScale, iconScale, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, 1); + cachedDetailIcon.draw(toggleState); + GL11.glPopMatrix(); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + + y += infoIconSize + 12; + } + + // Ability name (centered, wrapped) + String name = filteredDisplayNames.get(infoIndex); + List nameLines = fr.listFormattedStringToWidth(name, panelInnerWidth); + for (String line : nameLines) { + int lineX = panelInnerLeft + (panelInnerWidth - fr.getStringWidth(line)) / 2; + fr.drawStringWithShadow(line, lineX, y, 0xFFFFFF); + y += fr.FONT_HEIGHT + 1; + } + y += 4; + + // Type info + Ability ability = filteredAbilities.get(infoIndex); + if (ability != null) { + String typeId = ability.getTypeId(); + if (typeId != null && !typeId.isEmpty()) { + String translated = StatCollector.translateToLocal(typeId); + if (!translated.equals(typeId)) { + int textW = fr.getStringWidth(translated); + fr.drawStringWithShadow("\u00A77" + translated, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xAAAAAA); + y += fr.FONT_HEIGHT + 3; + } + } + + if (ability.isToggleable()) { + String toggleText = "[" + StatCollector.translateToLocal("gui.toggle") + "]"; + int textW = fr.getStringWidth(toggleText); + fr.drawStringWithShadow("\u00A7a" + toggleText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FF55); + y += fr.FONT_HEIGHT + 3; + } + + // Toggle state (uses pre-computed toggleState) + if (ability.isToggleable()) { + String stateText; + String prefix; + if (toggleState > 0) { + // Active — check for state label (multi-state toggles like Ki Weapon) + String stateLabel = ability.getToggleStateLabel(toggleState); + stateText = stateLabel != null ? stateLabel : StatCollector.translateToLocal("gui.toggle.active"); + prefix = "\u00A72"; + } else { + stateText = StatCollector.translateToLocal("gui.toggle.inactive"); + prefix = "\u00A78"; + } + int textW = fr.getStringWidth(stateText); + fr.drawStringWithShadow(prefix + stateText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, toggleState > 0 ? 0x55FF55 : 0x888888); + y += fr.FONT_HEIGHT + 3; + } + + // Cooldown info + if (ability.getCooldownTicks() > 0) { + float seconds = ability.getCooldownTicks() / 20.0f; + String cdText = StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s"; + int textW2 = fr.getStringWidth(cdText); + fr.drawStringWithShadow("\u00A77" + cdText, panelInnerLeft + (panelInnerWidth - textW2) / 2, y, 0xAAAAAA); + y += fr.FONT_HEIGHT + 3; + + if (ability.isPerAbilityCooldown()) { + String perText = "[" + StatCollector.translateToLocal("ability.perAbilityCooldown") + "]"; + int ptW = fr.getStringWidth(perText); + fr.drawStringWithShadow("\u00A7e" + perText, panelInnerLeft + (panelInnerWidth - ptW) / 2, y, 0xFFFF55); + } + } + } + } + + private void drawHotbarSection(int mouseX, int mouseY) { + FontRenderer fr = mc.fontRenderer; + + // Get selected ability key for yellow border + PlayerData selPlayerData = ClientCacheHandler.playerData; + String selectedKey = null; + if (selPlayerData != null && selPlayerData.abilityData != null) { + selectedKey = selPlayerData.abilityData.getSelectedAbilityKey(); + } + + // Hotbar slots centered within the panel + int panelWidth = hbRight - hbLeft; + int panelHeight = hbBottom - hbTop; + int totalSlotsWidth = hbSlots * (hbSlotSize + hbSlotGap) - hbSlotGap; + int hotbarStartX = guiLeft + hbLeft + (panelWidth - totalSlotsWidth) / 2; + int hotbarStartY = guiTop + hbTop + (panelHeight - hbSlotSize) / 2; + + for (int i = 0; i < hbSlots; i++) { + int sx = hotbarStartX + i * (hbSlotSize + hbSlotGap); + int sy = hotbarStartY; + + boolean isHovered = (hoveredSlotIndex == i); + boolean isDragHover = isDragging && isHovered; + + // Check if this slot's ability is the currently selected one + boolean isSelectedSlot = false; + if (selectedKey != null && !selectedKey.isEmpty() && selPlayerData.hotbarData != null) { + AbilityHotbarData slotData = selPlayerData.hotbarData.getSlot(i); + if (slotData != null && !slotData.isEmpty() && selectedKey.equals(slotData.abilityKey)) { + isSelectedSlot = true; + } + } + + // Slot background + int bgColor = isDragHover ? 0x80606030 : (isSelectedSlot ? 0x60505020 : (isHovered ? 0x60505050 : 0x50303030)); + drawRect(sx, sy, sx + hbSlotSize, sy + hbSlotSize, bgColor); + + // Slot border - yellow for selected, drag color, hover color, or default + int borderColor; + if (isDragHover) borderColor = 0xFFCCCC44; + else if (isSelectedSlot) borderColor = 0xFFCCCC00; + else if (isHovered) borderColor = 0xAA888888; + else borderColor = 0x60505050; + drawHorizontalLine(sx, sx + hbSlotSize - 1, sy, borderColor); + drawHorizontalLine(sx, sx + hbSlotSize - 1, sy + hbSlotSize - 1, borderColor); + drawVerticalLine(sx, sy, sy + hbSlotSize - 1, borderColor); + drawVerticalLine(sx + hbSlotSize - 1, sy, sy + hbSlotSize - 1, borderColor); + + GL11.glColor4f(1, 1, 1, 1); + + // Icon or slot number + AbilityIcon icon = hotbarIcons[i]; + boolean isSourceSlot = isDragging && dragSourceSlot == i; + + if (icon != null && !isSourceSlot) { + int iconCX = sx + hbSlotSize / 2; + int iconCY = sy + hbSlotSize / 2; + float targetPixels = hbSlotSize - 4; + float drawSize = icon.getDrawSize(); + float s = targetPixels / drawSize; + + // Compute toggle state for this hotbar slot's ability + int hbToggleState = 0; + if (selPlayerData != null && selPlayerData.abilityData != null && selPlayerData.hotbarData != null) { + AbilityHotbarData slotData = selPlayerData.hotbarData.getSlot(i); + if (slotData != null && !slotData.isEmpty()) { + hbToggleState = selPlayerData.abilityData.getToggleState(slotData.abilityKey); + } + } + + GL11.glPushMatrix(); + GL11.glTranslatef(iconCX, iconCY, 0); + GL11.glScalef(s, s, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + icon.draw(hbToggleState); + GL11.glPopMatrix(); + GL11.glColor4f(1, 1, 1, 1); + } else { + String slotLabel = String.valueOf(i + 1); + int labelColor = isSourceSlot ? 0x333333 : 0x666666; + int lx = sx + (hbSlotSize - fr.getStringWidth(slotLabel)) / 2; + int ly = sy + (hbSlotSize - fr.FONT_HEIGHT) / 2 + 1; + fr.drawString(slotLabel, lx, ly, labelColor); + } + } + + // Restore GL + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawDragGhost(int mouseX, int mouseY) { + if (draggedIcon == null) return; + + float targetPixels = gridCellSize; + float drawSize = draggedIcon.getDrawSize(); + float ghostScale = targetPixels / drawSize; + + GL11.glPushMatrix(); + GL11.glTranslatef(mouseX, mouseY, 100); + GL11.glScalef(ghostScale, ghostScale, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1, 1, 1, 0.8f); + draggedIcon.draw(0); + GL11.glColor4f(1, 1, 1, 1); + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(1, 1, 1, 1); + } + + private void drawTooltip(int mouseX, int mouseY) { + if (isDragging) return; + + if (hoveredGridIndex >= 0 && hoveredGridIndex < filteredDisplayNames.size()) { + List lines = new ArrayList<>(); + lines.add(filteredDisplayNames.get(hoveredGridIndex)); + + Ability ability = filteredAbilities.get(hoveredGridIndex); + if (ability != null) { + String typeId = ability.getTypeId(); + if (typeId != null && !typeId.isEmpty()) { + String translated = StatCollector.translateToLocal(typeId); + if (!translated.equals(typeId)) { + lines.add("\u00A77" + translated); + } + } + if (ability.isToggleable()) { + lines.add("\u00A7a[" + StatCollector.translateToLocal("gui.toggle") + "]"); + } + if (ability.getCooldownTicks() > 0) { + float seconds = ability.getCooldownTicks() / 20.0f; + lines.add("\u00A77" + StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s"); + } + } + + drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); + GL11.glDisable(GL11.GL_LIGHTING); + } + + if (hoveredSlotIndex >= 0 && hoveredSlotIndex < hbSlots) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slotData = playerData.hotbarData.getSlot(hoveredSlotIndex); + if (slotData != null && !slotData.isEmpty()) { + String name = getHotbarSlotDisplayName(slotData); + if (name != null) { + List lines = new ArrayList<>(); + lines.add(name); + lines.add("\u00A78Right-click to remove"); + drawHoveringText(lines, mouseX, mouseY, mc.fontRenderer); + GL11.glDisable(GL11.GL_LIGHTING); + } + } + } + } + } + + private String getHotbarSlotDisplayName(AbilityHotbarData slotData) { + if (AbilityController.Instance == null) return null; + if (slotData.isChainKey()) { + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(slotData.getResolveKey()); + return chain != null ? chain.getDisplayName() : null; + } + Ability ability = AbilityController.Instance.resolveAbility(slotData.abilityKey); + return ability != null ? ability.getDisplayName() : null; + } + + // ═══════════════════════════════════════════════════════════════════ + // Hover & Animation + // ═══════════════════════════════════════════════════════════════════ + + private void updateHoverState(int mouseX, int mouseY) { + hoveredGridIndex = -1; + hoveredSlotIndex = -1; + + // Grid hit test (RIGHT panel - selection) + int visibleRows = getGridVisibleRows(); + int gridStartX = getGridStartX(); + int gridStartY = getGridStartY(); + int startIndex = scrollRow * gridCols; + + if (mouseX >= guiLeft + selLeft && mouseX < guiLeft + selRight + && mouseY >= guiTop + selTop && mouseY < guiTop + selBottom) { + for (int vi = 0; vi < gridCols * visibleRows; vi++) { + int absIndex = startIndex + vi; + if (absIndex >= filteredKeys.size()) break; + + int col = vi % gridCols; + int row = vi / gridCols; + int cellX = gridStartX + col * gridCellSize; + int cellY = gridStartY + row * gridCellSize; + + if (mouseX >= cellX && mouseX < cellX + gridCellSize - 1 + && mouseY >= cellY && mouseY < cellY + gridCellSize - 1) { + hoveredGridIndex = absIndex; + break; + } + } + } + + // Hotbar hit test + int panelWidth = hbRight - hbLeft; + int panelHeight = hbBottom - hbTop; + int totalSlotsWidth = hbSlots * (hbSlotSize + hbSlotGap) - hbSlotGap; + int hotbarStartX = guiLeft + hbLeft + (panelWidth - totalSlotsWidth) / 2; + int hotbarStartY = guiTop + hbTop + (panelHeight - hbSlotSize) / 2; + + for (int i = 0; i < hbSlots; i++) { + int sx = hotbarStartX + i * (hbSlotSize + hbSlotGap); + if (mouseX >= sx && mouseX < sx + hbSlotSize + && mouseY >= hotbarStartY && mouseY < hotbarStartY + hbSlotSize) { + hoveredSlotIndex = i; + break; + } + } + } + + private void updateHoverScales() { + if (gridHoverScale == null) return; + for (int i = 0; i < gridHoverScale.length; i++) { + float target = (i == hoveredGridIndex && !isDragging) ? 1.12f : 1.0f; + gridHoverScale[i] += (target - gridHoverScale[i]) * 0.3f; + if (Math.abs(gridHoverScale[i] - target) < 0.005f) { + gridHoverScale[i] = target; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Mouse Handlers + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void mouseClicked(int mouseX, int mouseY, int button) { + if (hasSubGui()) { + super.mouseClicked(mouseX, mouseY, button); + return; + } + + // Right-click on hotbar slot -> clear + if (button == 1 && hoveredSlotIndex >= 0) { + saveHotbarSlot(hoveredSlotIndex, ""); + updateHotbarIcons(); + return; + } + + // Left-click: start potential drag or select + if (button == 0) { + if (hoveredGridIndex >= 0 && hoveredGridIndex < filteredKeys.size()) { + // Toggle double-tap detection on toggle tab + if (subTab == 1) { + long now = System.currentTimeMillis(); + if (lastToggleClickIndex == hoveredGridIndex && (now - lastToggleClickTime) < 400) { + String key = filteredKeys.get(hoveredGridIndex); + Ability ability = filteredAbilities.get(hoveredGridIndex); + if (ability != null && ability.isToggleable()) { + PacketHandler.Instance.sendToServer(new AbilityTogglePacket(key)); + lastToggleClickIndex = -1; + lastToggleClickTime = 0; + // Rebuild list after a short delay to reflect new state + // For now just select and return - the list rebuilds on next initGui + selectedIndex = hoveredGridIndex; + cachedDetailIcon = null; + cachedDetailIndex = -1; + return; + } + } + lastToggleClickIndex = hoveredGridIndex; + lastToggleClickTime = now; + } + + selectedIndex = hoveredGridIndex; + cachedDetailIcon = null; + cachedDetailIndex = -1; + dragPending = true; + draggedKey = filteredKeys.get(hoveredGridIndex); + draggedIcon = filteredIcons.get(hoveredGridIndex); + dragSourceSlot = -1; + dragStartX = mouseX; + dragStartY = mouseY; + return; + } + + if (hoveredSlotIndex >= 0 && hotbarIcons[hoveredSlotIndex] != null) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slotData = playerData.hotbarData.getSlot(hoveredSlotIndex); + if (slotData != null && !slotData.isEmpty()) { + dragPending = true; + draggedKey = slotData.abilityKey; + draggedIcon = hotbarIcons[hoveredSlotIndex]; + dragSourceSlot = hoveredSlotIndex; + dragStartX = mouseX; + dragStartY = mouseY; + return; + } + } + } + } + + super.mouseClicked(mouseX, mouseY, button); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int button, long timeSinceLastClick) { + if (dragPending && !isDragging) { + int dx = mouseX - dragStartX; + int dy = mouseY - dragStartY; + if (dx * dx + dy * dy > dragThreshold * dragThreshold) { + isDragging = true; + } + } + if (isDragging) { + dragMouseX = mouseX; + dragMouseY = mouseY; + } + + super.mouseClickMove(mouseX, mouseY, button, timeSinceLastClick); + } + + @Override + protected void mouseMovedOrUp(int mouseX, int mouseY, int state) { + if (isDragging && draggedKey != null) { + updateHoverState(mouseX, mouseY); + + if (hoveredSlotIndex >= 0) { + if (dragSourceSlot >= 0) { + swapHotbarSlots(dragSourceSlot, hoveredSlotIndex); + } else { + saveHotbarSlot(hoveredSlotIndex, draggedKey); + } + updateHotbarIcons(); + } else if (dragSourceSlot >= 0 && hoveredGridIndex >= 0) { + saveHotbarSlot(dragSourceSlot, ""); + updateHotbarIcons(); + } + } + + isDragging = false; + dragPending = false; + draggedKey = null; + draggedIcon = null; + dragSourceSlot = -1; + + super.mouseMovedOrUp(mouseX, mouseY, state); + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + + int wheel = Mouse.getEventDWheel(); + if (wheel != 0) { + int maxScroll = getMaxScrollRow(); + if (wheel > 0) { + scrollRow = Math.max(0, scrollRow - 1); + } else { + scrollRow = Math.min(maxScroll, scrollRow + 1); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // Actions & Network + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void actionPerformed(GuiButton btn) { + if (btn instanceof AbstractTab) return; + + if (btn.id <= -100 && btn.id > -200) { + super.actionPerformed(btn); + return; + } + + if (btn.id == BTN_TAB_ABILITIES) { + subTab = 0; + initGui(); + return; + } + if (btn.id == BTN_TAB_TOGGLES) { + subTab = 1; + initGui(); + return; + } + } + + private void saveHotbarSlot(int slotIndex, String abilityKey) { + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.hotbarData != null) { + AbilityHotbarData slot = playerData.hotbarData.getSlot(slotIndex); + if (slot != null) { + slot.abilityKey = abilityKey; + } + } + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagCompound slotTag = new NBTTagCompound(); + slotTag.setInteger("slot", slotIndex); + slotTag.setString("abilityKey", abilityKey != null ? abilityKey : ""); + compound.setTag("AbilityHotbar" + slotIndex, slotTag); + PacketHandler.Instance.sendToServer(new AbilityHotbarSavePacket(slotIndex, compound)); + } + + private void swapHotbarSlots(int fromSlot, int toSlot) { + if (fromSlot == toSlot) return; + + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.hotbarData == null) return; + + AbilityHotbarData fromData = playerData.hotbarData.getSlot(fromSlot); + AbilityHotbarData toData = playerData.hotbarData.getSlot(toSlot); + if (fromData == null || toData == null) return; + + String fromKey = fromData.abilityKey; + String toKey = toData.abilityKey; + + saveHotbarSlot(fromSlot, toKey != null ? toKey : ""); + saveHotbarSlot(toSlot, fromKey != null ? fromKey : ""); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + // Send selection sync if changed + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData != null && playerData.abilityData != null) { + String currentKey = playerData.abilityData.getSelectedAbilityKey(); + boolean changed = (initialSelectedKey == null && currentKey != null && !currentKey.isEmpty()) + || (initialSelectedKey != null && !initialSelectedKey.equals(currentKey)); + if (changed) { + PacketHandler.Instance.sendToServer(new AbilityHotbarSelectPacket(currentKey != null ? currentKey : "")); + } + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (i == 1 || isInventoryKey(i)) { + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java index f27913d89..3e4b9706a 100644 --- a/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/GuiCNPCInventory.java @@ -73,6 +73,14 @@ public class GuiCNPCInventory extends GuiNPCInterface { addSideButton(profileButton); } + y += 21; + GuiMenuSideButton abilitiesButton = new GuiMenuSideButton(-105, guiLeft + xSize + 37, this.guiTop + y, 22, 22, ""); + abilitiesButton.rightSided = true; + abilitiesButton.active = activeTab == -105; + abilitiesButton.renderIconPosX = 80; + abilitiesButton.renderResource = specialIcons; + addSideButton(abilitiesButton); + y += 21; GuiMenuSideButton clientButton = new GuiMenuSideButton(-103, guiLeft + xSize + 37, this.guiTop + y, 22, 22, ""); clientButton.rightSided = true; @@ -154,6 +162,10 @@ public class GuiCNPCInventory extends GuiNPCInterface { activeTab = -104; mc.displayGuiScreen(new GuiProfiles()); } + if (guibutton.id == -105 && activeTab != -105) { + activeTab = -105; + mc.displayGuiScreen(new GuiAbilities()); + } } } diff --git a/src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java b/src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java new file mode 100644 index 000000000..a3d85f7e4 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/player/inventory/SubGuiSelectAbilityForSlot.java @@ -0,0 +1,155 @@ +package noppes.npcs.client.gui.player.inventory; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.ChainedAbility; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.AbilityHotbarData; +import noppes.npcs.controllers.data.PlayerData; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * SubGui for selecting an ability to assign to a hotbar slot. + */ +public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + private HashMap displayToKey = new HashMap<>(); + private GuiCustomScroll scrollAbilities; + private String selected = null; + private String search = ""; + + public boolean confirmed = false; + public String selectedAbilityKey = null; + public int slotIndex; + public boolean removeAbility = false; + + public SubGuiSelectAbilityForSlot(int slotIndex) { + this.slotIndex = slotIndex; + this.closeOnEsc = true; + this.drawDefaultBackground = true; + guiLeft -= 10; + xSize = 256 + 10; + this.setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + guiTop += 10; + + if (scrollAbilities == null) { + scrollAbilities = new GuiCustomScroll(this, 0, 0); + scrollAbilities.setSize(177, 185); + } + + scrollAbilities.guiLeft = guiLeft + 4; + scrollAbilities.guiTop = guiTop + 4; + addScroll(scrollAbilities); + + loadAbilities(); + scrollAbilities.setList(getSearchList()); + + addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 192, 177, 20, search)); + + addButton(new GuiNpcButton(0, guiLeft + 183, guiTop + 4, 79, 20, "gui.add")); + addButton(new GuiNpcButton(1, guiLeft + 183, guiTop + 26, 79, 20, "gui.cancel")); + addButton(new GuiNpcButton(2, guiLeft + 183, guiTop + 88, 79, 20, "gui.remove")); + } + + private void loadAbilities() { + displayToKey.clear(); + PlayerData playerData = ClientCacheHandler.playerData; + if (playerData == null || playerData.abilityData == null) { + return; + } + + List abilities = playerData.abilityData.getUnlockedAbilityList(); + for (String key : abilities) { + String displayName; + if (key.startsWith(AbilityHotbarData.CHAIN_PREFIX)) { + String chainKey = key.substring(AbilityHotbarData.CHAIN_PREFIX.length()); + ChainedAbility chain = AbilityController.Instance != null ? + AbilityController.Instance.resolveChainedAbility(chainKey) : null; + displayName = chain != null ? "\u00A76\u2726 " + chain.getDisplayName() : key; + } else { + Ability ability = AbilityController.Instance != null ? + AbilityController.Instance.resolveAbility(key) : null; + displayName = ability != null ? ability.getDisplayName() : key; + } + displayToKey.put(displayName, key); + } + } + + @Override + public void actionPerformed(GuiButton button) { + int id = button.id; + + if (id == 0 && selected != null) { + confirmed = true; + selectedAbilityKey = displayToKey.get(selected); + this.close(); + } + if (id == 1) { + this.close(); + } + if (id == 2) { + this.removeAbility = true; + this.close(); + } + } + + @Override + public void customScrollClicked(int i, int i1, int i2, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll == scrollAbilities) + selected = scrollAbilities.getSelected(); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll == scrollAbilities && selection != null) { + confirmed = true; + selectedAbilityKey = displayToKey.get(selection); + this.close(); + } + } + + @Override + public void unFocused(GuiNpcTextField guiNpcTextField) { + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(55) != null) { + if (getTextField(55).isFocused()) { + if (search.equals(getTextField(55).getText())) + return; + search = getTextField(55).getText().toLowerCase(); + scrollAbilities.resetScroll(); + scrollAbilities.setList(getSearchList()); + } + } + } + + private List getSearchList() { + if (search.isEmpty()) { + return new ArrayList<>(displayToKey.keySet()); + } + + List list = new ArrayList<>(); + for (String name : displayToKey.keySet()) { + if (name.toLowerCase().contains(search)) + list.add(name); + } + return list; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java index a390ddfc1..29cf26134 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java @@ -80,9 +80,10 @@ public class GuiEffectBar extends GuiScreen { int iconWidth = entry.effect.getWidth(); int iconHeight = entry.effect.getHeight(); int texWidth = imageData.getTotalWidth(); + int texHeight = imageData.getTotalHeight(); // Use iconYOffset to vertically center the icon - func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texWidth); + func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight); GL11.glDisable(GL11.GL_DEPTH_TEST); Minecraft.getMinecraft().getTextureManager().bindTexture(specialIcons); @@ -190,7 +191,7 @@ public class GuiEffectBar extends GuiScreen { if (imageData != null && imageData.imageLoaded()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); imageData.bindTexture(); - func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalWidth()); + func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalHeight()); } textureManager.bindTexture(specialIcons); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java index 413ca7b39..8c8eca60d 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiMenuTopButton.java @@ -24,10 +24,21 @@ public class GuiMenuTopButton extends GuiNpcButton { height = 20; } + /** + * Place to the RIGHT of the given button. + */ public GuiMenuTopButton(int i, GuiButton parent, String s) { this(i, parent.xPosition + parent.width, parent.yPosition, s); } + /** + * Place to the LEFT of the given button. + */ + public GuiMenuTopButton(int i, String s, GuiButton rightNeighbor) { + this(i, rightNeighbor.xPosition - (Minecraft.getMinecraft().fontRenderer.getStringWidth(StatCollector.translateToLocal(s)) + 12), + rightNeighbor.yPosition, s); + } + public GuiMenuTopButton(int i, GuiButton parent, String s, IButtonListener listener) { this(i, parent, s); diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index d8c093382..3616627f4 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -69,10 +69,10 @@ public class ConfigClient { // HUD PROPERTIES public static Property QuestOverlayXProperty; - public static int QuestOverlayX = 0; + public static float QuestOverlayX = 0; public static Property QuestOverlayYProperty; - public static int QuestOverlayY = 31; + public static float QuestOverlayY = 31; public static Property QuestOverlayScaleProperty; public static int QuestOverlayScale = 223; @@ -84,10 +84,10 @@ public class ConfigClient { public static boolean CompassEnabled = true; public static Property CompassOverlayXProperty; - public static int CompassOverlayX = 37; + public static float CompassOverlayX = 37; public static Property CompassOverlayYProperty; - public static int CompassOverlayY = 0; + public static float CompassOverlayY = 0; public static Property CompassOverlayScaleProperty; public static int CompassOverlayScale = 276; @@ -95,6 +95,41 @@ public class ConfigClient { public static Property CompassOverlayWidthProperty; public static int CompassOverlayWidth = 200; + // Ability Hotbar HUD + public static Property AbilityHotbarEnabledProperty; + public static boolean AbilityHotbarEnabled = true; + + public static Property AbilityHotbarXProperty; + public static float AbilityHotbarX = 3; + + public static Property AbilityHotbarYProperty; + public static float AbilityHotbarY = 50; + + public static Property AbilityHotbarScaleProperty; + public static int AbilityHotbarScale = 100; + + public static Property AbilityHotbarHorizontalProperty; + public static boolean AbilityHotbarHorizontal = false; + + public static Property AbilityHotbarAltTextureProperty; + public static boolean AbilityHotbarAltTexture = false; + + // 1=Above(H)/Left(V), 2=Below(H)/Right(V) + public static Property AbilityHotbarTextPositionProperty; + public static int AbilityHotbarTextPosition = 2; + + // Max visible slots: 3, 5, or 7 + public static Property AbilityHotbarVisibleSlotsProperty; + public static int AbilityHotbarVisibleSlots = 5; + + // Show Always: true = always visible, false = only visible while HUD key held + public static Property AbilityHotbarShowAlwaysProperty; + public static boolean AbilityHotbarShowAlways = true; + + // Text Visibility: 0=Shown, 1=Hidden, 2=Held (only while HUD key held) + public static Property AbilityHotbarTextVisibilityProperty; + public static int AbilityHotbarTextVisibility = 0; + /** * Texture Properties **/ @@ -125,11 +160,11 @@ public class ConfigClient { config.load(); // Hud Quest Overlay settings - QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0, "X position of the quest overlay."); - QuestOverlayX = QuestOverlayXProperty.getInt(0); + QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0.0, "X position of the quest overlay."); + QuestOverlayX = (float) QuestOverlayXProperty.getDouble(0); - QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31, "Y position of the quest overlay."); - QuestOverlayY = QuestOverlayYProperty.getInt(31); + QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31.0, "Y position of the quest overlay."); + QuestOverlayY = (float) QuestOverlayYProperty.getDouble(31); QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 223, "Scale percentage of the quest overlay."); QuestOverlayScale = QuestOverlayScaleProperty.getInt(223); @@ -149,22 +184,18 @@ public class ConfigClient { CompassOverlayXProperty = config.get( HUD, "Compass Hud X", - 37, - "Horizontal position of compass overlay (0-100 percentage)", - 0, - 100 + 37.0, + "Horizontal position of compass overlay (0-100 percentage)" ); - CompassOverlayX = CompassOverlayXProperty.getInt(); + CompassOverlayX = (float) CompassOverlayXProperty.getDouble(); CompassOverlayYProperty = config.get( HUD, "Compass Hud Y", - 0, - "Vertical position of compass overlay (0-100 percentage)", - 0, - 100 + 0.0, + "Vertical position of compass overlay (0-100 percentage)" ); - CompassOverlayY = CompassOverlayYProperty.getInt(); + CompassOverlayY = (float) CompassOverlayYProperty.getDouble(); CompassOverlayScaleProperty = config.get( HUD, @@ -186,6 +217,36 @@ public class ConfigClient { ); CompassOverlayWidth = CompassOverlayWidthProperty.getInt(); + // Ability Hotbar HUD Configs + AbilityHotbarEnabledProperty = config.get(HUD, "Ability Hotbar Enabled", true, "Enable Ability Hotbar HUD Component"); + AbilityHotbarEnabled = AbilityHotbarEnabledProperty.getBoolean(); + + AbilityHotbarXProperty = config.get(HUD, "Ability Hotbar X", 3.0, "Horizontal position (0-100 percentage)"); + AbilityHotbarX = (float) AbilityHotbarXProperty.getDouble(); + + AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 50.0, "Vertical position (0-100 percentage)"); + AbilityHotbarY = (float) AbilityHotbarYProperty.getDouble(); + + AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 100, "Scale percentage", 50, 300); + AbilityHotbarScale = AbilityHotbarScaleProperty.getInt(); + + AbilityHotbarHorizontalProperty = config.get(HUD, "Ability Hotbar Horizontal", false, "Display horizontally instead of vertically"); + AbilityHotbarHorizontal = AbilityHotbarHorizontalProperty.getBoolean(); + + AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", false, "Use rounded square instead of circle slots"); + AbilityHotbarAltTexture = AbilityHotbarAltTextureProperty.getBoolean(); + + AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (1=Above/Left, 2=Below/Right)"); + AbilityHotbarTextPosition = AbilityHotbarTextPositionProperty.getInt(2); + + AbilityHotbarVisibleSlotsProperty = config.get(HUD, "Ability Hotbar Visible Slots", 5, "Max visible slots in hotbar (3, 5, or 7)"); + AbilityHotbarVisibleSlots = AbilityHotbarVisibleSlotsProperty.getInt(5); + + AbilityHotbarShowAlwaysProperty = config.get(HUD, "Ability Hotbar Show Always", true, "Always show hotbar (false = only while HUD key is held)"); + AbilityHotbarShowAlways = AbilityHotbarShowAlwaysProperty.getBoolean(true); + + AbilityHotbarTextVisibilityProperty = config.get(HUD, "Ability Hotbar Text Visibility", 0, "Text visibility (0=Shown, 1=Hidden, 2=Held)"); + AbilityHotbarTextVisibility = AbilityHotbarTextVisibilityProperty.getInt(0); // General AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side."); diff --git a/src/main/java/noppes/npcs/config/ConfigEnergy.java b/src/main/java/noppes/npcs/config/ConfigEnergy.java new file mode 100644 index 000000000..f3b36a948 --- /dev/null +++ b/src/main/java/noppes/npcs/config/ConfigEnergy.java @@ -0,0 +1,37 @@ +package noppes.npcs.config; + +import cpw.mods.fml.common.FMLLog; +import net.minecraftforge.common.config.Configuration; +import org.apache.logging.log4j.Level; + +import java.io.File; + +public class ConfigEnergy { + public static Configuration config; + + public final static String DOMES = "Domes"; + + public static String[] DomeItemBlacklist; + + public static void init(File configFile) { + config = new Configuration(configFile); + + try { + config.load(); + + DomeItemBlacklist = config.getStringList( + "Item Blacklist", DOMES, + new String[]{"minecraft:ender_pearl"}, + "Items that cannot be used while inside an Energy Dome.\n" + + "Format: modid:itemname (e.g., minecraft:ender_pearl)" + ); + + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "CustomNPC+ has had a problem loading its energy configuration"); + } finally { + if (config.hasChanged()) { + config.save(); + } + } + } +} diff --git a/src/main/java/noppes/npcs/config/LoadConfiguration.java b/src/main/java/noppes/npcs/config/LoadConfiguration.java index dfac43d90..0fc46e3e3 100644 --- a/src/main/java/noppes/npcs/config/LoadConfiguration.java +++ b/src/main/java/noppes/npcs/config/LoadConfiguration.java @@ -10,6 +10,7 @@ public class LoadConfiguration { public static File clientConfigFile; public static File experimentalConfigFile; public static File marketConfigFile; + public static File energyConfigFile; public static void init(String configpath) { mainConfigFile = new File(configpath + "main.cfg"); @@ -19,6 +20,7 @@ public class LoadConfiguration { debugConfigFile = new File(configpath + "debug.cfg"); experimentalConfigFile = new File(configpath + "experimental.cfg"); marketConfigFile = new File(configpath + "market.cfg"); + energyConfigFile = new File(configpath + "energy.cfg"); ConfigMain.init(mainConfigFile); ConfigItem.init(itemConfigFile); @@ -27,5 +29,6 @@ public class LoadConfiguration { ConfigDebug.init(debugConfigFile); ConfigExperimental.init(experimentalConfigFile); ConfigMarket.init(marketConfigFile); + ConfigEnergy.init(energyConfigFile); } } diff --git a/src/main/java/noppes/npcs/controllers/AnimationController.java b/src/main/java/noppes/npcs/controllers/AnimationController.java index bfbf978d2..e9a64bfe1 100644 --- a/src/main/java/noppes/npcs/controllers/AnimationController.java +++ b/src/main/java/noppes/npcs/controllers/AnimationController.java @@ -213,6 +213,18 @@ public class AnimationController implements IAnimationHandler { } } + /** + * Loads built-in animations for client-side usage. + * On dedicated servers, AnimationController.load() never runs on the client JVM, + * so built-in animations would be missing for client-only systems like ability preview. + * This method loads just the built-in animations (from assets and registered addons) + * without touching user animations or world save data. + */ + public void loadClientBuiltIns() { + loadBuiltInAnimations(); + loadRegisteredBuiltIns(); + } + private File getDir() { return new File(CustomNpcs.getWorldSaveDirectory(), "animations"); } diff --git a/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java b/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java new file mode 100644 index 000000000..7941c81f1 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AbilityHotbarData.java @@ -0,0 +1,47 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class AbilityHotbarData { + public static final String CHAIN_PREFIX = "chain:"; + public static final int TOTAL_SLOTS = 12; + + public int slot = -1; + public String abilityKey = ""; + + public AbilityHotbarData() { + } + + public AbilityHotbarData(int slot) { + this.slot = slot; + } + + public boolean isChainKey() { + return abilityKey != null && abilityKey.startsWith(CHAIN_PREFIX); + } + + public String getResolveKey() { + if (isChainKey()) return abilityKey.substring(CHAIN_PREFIX.length()); + return abilityKey; + } + + public NBTTagCompound writeToNBT(NBTTagCompound compound) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("slot", slot); + tag.setString("abilityKey", abilityKey != null ? abilityKey : ""); + compound.setTag("AbilityHotbar" + slot, tag); + return compound; + } + + public void readFromNBT(NBTTagCompound compound) { + abilityKey = compound.getString("abilityKey"); + } + + public void reset() { + abilityKey = ""; + } + + public boolean isEmpty() { + return abilityKey == null || abilityKey.isEmpty(); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index d2afe1c64..79890baeb 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -8,6 +8,7 @@ import kamkeel.npcs.controllers.data.ability.IAbilityAction; import kamkeel.npcs.controllers.data.ability.ToggleEntry; import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; @@ -22,6 +23,7 @@ import net.minecraft.util.DamageSource; import noppes.npcs.AbstractDataAbilities; import noppes.npcs.EventHooks; import noppes.npcs.LogWriter; +import noppes.npcs.NoppesUtilPlayer; import noppes.npcs.api.ability.IPlayerAbilityData; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.controllers.ScriptController; @@ -89,6 +91,16 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA */ private transient byte lastSyncedFlags = 0; + /** + * World time when the last ability was activated (for double-press cancel detection). + */ + private transient long lastAbilityActivationTime = -1; + + /** + * Ticks after activation during which a second key press will cancel the ability. + */ + private static final int CANCEL_WINDOW_TICKS = 10; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -225,14 +237,30 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA @Override protected void rollCooldown(Ability ability) { - if (!ability.isIgnoreCooldown()) { - cooldownEndTime = getWorldTime() + ability.getCooldownTicks(); + if (ability.isIgnoreCooldown()) return; + + int duration = ability.getCooldownTicks(); + long endTime = getWorldTime() + duration; + + if (ability.isPerAbilityCooldown()) { + // Per-ability: only this ability goes on cooldown + if (currentAbilityKey != null) { + setPerAbilityCooldown(currentAbilityKey, endTime, duration); + } + } else { + // Global: all global-cooldown abilities share this cooldown + cooldownEndTime = endTime; + globalCooldownDuration = duration; } + syncCooldownToClient(); } @Override protected void rollChainCooldown(ChainedAbility chain) { - cooldownEndTime = getWorldTime() + chain.getCooldownTicks(); + int duration = chain.getCooldownTicks(); + cooldownEndTime = getWorldTime() + duration; + globalCooldownDuration = duration; + syncCooldownToClient(); } @Override @@ -240,6 +268,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = null; currentAbilityKey = null; currentTarget = null; + lastAbilityActivationTime = -1; syncAbilityStateClear(playerData.player); } @@ -250,9 +279,12 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA @Override protected void onInterruptComplete() { // Player clears state immediately (unlike NPC which ticks through DAZED) + // Stop the dazed animation that was started in interruptCurrentAbility() + stopAbilityAnimation(); currentAbility = null; currentAbilityKey = null; currentTarget = null; + lastAbilityActivationTime = -1; syncAbilityStateClear(playerData.player); } @@ -358,14 +390,27 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbilityKey = key; currentTarget = null; + lastAbilityActivationTime = getWorldTime(); return startChain((ChainedAbility) action, null); } // Regular ability activation Ability ability = (Ability) action; - // Check universal cooldown (abilities can optionally ignore it) - if (!ability.isIgnoreCooldown() && isOnCooldown()) return false; + // Toggle abilities cycle state instead of executing + if (ability.isToggleable()) { + toggleAbility(key); + return true; + } + + // Check cooldown (per-ability cooldowns are independent from global) + if (!ability.isIgnoreCooldown()) { + if (ability.isPerAbilityCooldown()) { + if (isOnPerAbilityCooldown(key)) return false; + } else { + if (isOnCooldown()) return false; + } + } // Fire extender start hook (e.g., resource cost checks) if (!AbilityController.Instance.fireOnAbilityStart(ability, player, null)) { @@ -381,6 +426,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = ability; currentAbilityKey = key; currentTarget = null; // Players don't have auto-targets + lastAbilityActivationTime = getWorldTime(); ability.start(null); if (ability.getPhase() == AbilityPhase.ACTIVE) { @@ -420,6 +466,18 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA EntityPlayer player = playerData.player; if (player instanceof EntityPlayerMP) { PlayerAbilitySyncPacket.sendToPlayer((EntityPlayerMP) player); + syncCooldownToClient(); + } + } + + /** + * Sync cooldown state (global + per-ability) to the client. + * Sent as a lightweight packet separate from full ability sync. + */ + public void syncCooldownToClient() { + EntityPlayer player = playerData.player; + if (player instanceof EntityPlayerMP) { + AbilityCooldownSyncPacket.sendToPlayer((EntityPlayerMP) player); } } @@ -460,7 +518,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } public void setSelectedIndex(int index) { - if (index >= 0 && index < unlockedAbilities.size()) { + if (index == -1 || (index >= 0 && index < unlockedAbilities.size())) { this.selectedIndex = index; syncToClient(); } @@ -539,9 +597,15 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA /** * Check if a specific ability key is on cooldown. - * Currently uses universal cooldown (same for all abilities). + * Respects per-ability cooldown if the ability has it enabled. */ public boolean isOnCooldown(String key, EntityPlayer player) { + if (AbilityController.Instance != null) { + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability != null && ability.isPerAbilityCooldown()) { + return isOnPerAbilityCooldown(key); + } + } return isOnCooldown(player); } @@ -552,17 +616,21 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA /** * Reset cooldown for a specific ability key. - * Currently resets the universal cooldown. + * Resets per-ability cooldown if applicable, and global cooldown. */ public void resetCooldown(String key) { + resetPerAbilityCooldown(key); cooldownEndTime = 0; + syncCooldownToClient(); } /** - * Reset all cooldowns. + * Reset all cooldowns (global + all per-ability). */ public void resetAllCooldowns() { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + syncCooldownToClient(); } // ═══════════════════════════════════════════════════════════════════ @@ -596,6 +664,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA @Override public void resetCooldown() { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); + syncCooldownToClient(); } // ═══════════════════════════════════════════════════════════════════ @@ -606,6 +676,38 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA interruptCurrentAbility(null, 0); } + /** + * Try to cancel the current ability via double-press. + * Only succeeds if within the cancel window and not in DAZED phase. + * Also handles cancellation during chain delay (between chain entries). + * + * @return true if the ability was cancelled + */ + public boolean tryCancelAbility() { + boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting(); + boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0; + + if (!hasExecutingAbility && !isInChainDelay) return false; + + // Don't allow cancel during DAZED + if (hasExecutingAbility) { + AbilityPhase phase = currentAbility.getPhase(); + if (phase == AbilityPhase.DAZED) return false; + if (phase != AbilityPhase.WINDUP && phase != AbilityPhase.ACTIVE + && phase != AbilityPhase.BURST_DELAY) return false; + } + + long worldTime = getWorldTime(); + if (lastAbilityActivationTime < 0 || (worldTime - lastAbilityActivationTime) > CANCEL_WINDOW_TICKS) { + // Outside cancel window — update time so a quick follow-up press can cancel + lastAbilityActivationTime = worldTime; + return false; + } + + cancelCurrentAbility(); + return true; + } + // ═══════════════════════════════════════════════════════════════════ // ENTITY RECONSTRUCTION RESET // ═══════════════════════════════════════════════════════════════════ @@ -645,9 +747,11 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA currentAbility = null; currentAbilityKey = null; currentTarget = null; + lastAbilityActivationTime = -1; if (clearCooldowns) { cooldownEndTime = 0; + resetAllPerAbilityCooldowns(); } interruptCooldownRolled = false; @@ -935,8 +1039,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } /** - * Remove any unlocked ability keys that can no longer be resolved. - * Called during load to clean up references to deleted abilities. + * Remove any unlocked ability keys that can no longer be resolved or + * are no longer allowed for players (e.g. NPC-only abilities). + * Called during load to clean up references to deleted/restricted abilities. * Supports both regular ability keys and "chain:" prefixed chained ability keys. */ private void validateUnlockedAbilities() { @@ -949,6 +1054,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA if (resolved == null) { it.remove(); LogWriter.info("Removed invalid ability reference from player data: " + key); + } else if (!resolved.getAllowedBy().allowsPlayer()) { + it.remove(); + LogWriter.info("Removed non-player ability from player data: " + key); } } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java new file mode 100644 index 000000000..f062d891c --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityHotbarData.java @@ -0,0 +1,84 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +public class PlayerAbilityHotbarData { + public AbilityHotbarData[] slots = new AbilityHotbarData[AbilityHotbarData.TOTAL_SLOTS]; + + public PlayerAbilityHotbarData() { + for (int i = 0; i < slots.length; i++) { + slots[i] = new AbilityHotbarData(i); + } + } + + public AbilityHotbarData getSlot(int index) { + if (index < 0 || index >= slots.length) return null; + return slots[index]; + } + + public void setSlot(int index, String abilityKey) { + if (index < 0 || index >= slots.length) return; + slots[index].abilityKey = abilityKey != null ? abilityKey : ""; + } + + public void clearSlot(int index) { + if (index < 0 || index >= slots.length) return; + slots[index].reset(); + } + + public boolean hasAnyAbilities() { + for (AbilityHotbarData slot : slots) { + if (!slot.isEmpty()) return true; + } + return false; + } + + public void writeToNBT(NBTTagCompound compound) { + for (int i = 0; i < slots.length; i++) { + slots[i].writeToNBT(compound); + } + } + + public void readFromNBT(NBTTagCompound compound) { + for (int i = 0; i < slots.length; i++) { + NBTTagCompound slotTag = compound.getCompoundTag("AbilityHotbar" + i); + slots[i].readFromNBT(slotTag); + } + validateSlots(); + } + + public void validateSlots() { + if (AbilityController.Instance == null) return; + for (AbilityHotbarData slot : slots) { + if (slot.isEmpty()) continue; + boolean valid; + if (slot.isChainKey()) { + valid = AbilityController.Instance.canResolveChainedAbility(slot.getResolveKey()); + } else { + valid = AbilityController.Instance.canResolveAbility(slot.abilityKey); + // Also check that resolved ability allows player usage + if (valid) { + Ability ability = AbilityController.Instance.resolveAbility(slot.abilityKey); + if (ability != null && !ability.getAllowedBy().allowsPlayer()) { + valid = false; + } + } + } + if (!valid) { + slot.reset(); + } + } + } + + public void syncToClient(EntityPlayer player) { + if (player instanceof EntityPlayerMP) { + AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player); + } + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index 9052811cf..8283d4f6c 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -65,6 +65,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { public PlayerTradeData tradeData = new PlayerTradeData(this); public PlayerAbilityData abilityData = new PlayerAbilityData(this); + public PlayerAbilityHotbarData hotbarData = new PlayerAbilityHotbarData(); public ActionManager actionManager = new ActionManager(); public PlayerDataScript scriptData; @@ -119,6 +120,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { // Sync player ability data to client abilityData.syncToClient(); + + // Sync hotbar data to client + hotbarData.syncToClient(player); } public void onLogout() { @@ -151,6 +155,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { magicData.readToNBT(data); tradeData.readFromNBT(data); abilityData.readFromNBT(data); + hotbarData.readFromNBT(data); if (player != null) { playername = player.getCommandSenderName(); @@ -195,6 +200,7 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { magicData.writeToNBT(compound); tradeData.writeToNBT(compound); abilityData.writeToNBT(compound); + hotbarData.writeToNBT(compound); compound.setString("PlayerName", playername); compound.setString("UUID", uuid); diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 187ce583d..4834504b3 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -11,6 +11,7 @@ import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; import kamkeel.npcs.network.packets.data.ChatBubblePacket; import kamkeel.npcs.network.packets.data.QuestCompletionPacket; +import kamkeel.npcs.network.packets.data.RequestProperSpawnData; import kamkeel.npcs.network.packets.data.SoundManagementPacket; import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket; import kamkeel.npcs.network.packets.data.npc.WeaponNpcPacket; @@ -68,6 +69,7 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.ServerChatEvent; import noppes.npcs.CustomItems; @@ -229,6 +231,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti public FlyingMoveHelper flyMoveHelper = new FlyingMoveHelper(this); public PathNavigate flyNavigator = new PathNavigateFlying(this, worldObj); + @SideOnly(Side.CLIENT) + public int immediateSpawnDataFixAttempts = 0; + public EntityNPCInterface(World world) { super(world); try { @@ -1829,10 +1834,17 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti try { readSpawnData(ByteBufUtils.readNBT(buf)); } catch (IOException e) { + RequestProperSpawnData.reportMissingData(this); } } public void readSpawnData(NBTTagCompound compound) { + if ((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))) { + RequestProperSpawnData.reportMissingData(this); + return; + } + + immediateSpawnDataFixAttempts = 0; stats.maxHealth = compound.getDouble("MaxHealth"); ais.setWalkingSpeed(compound.getInteger("Speed")); stats.hideKilledBody = compound.getBoolean("DeadBody"); diff --git a/src/main/java/noppes/npcs/mixin/MixinItemStack.java b/src/main/java/noppes/npcs/mixin/MixinItemStack.java index 8615573c0..4e82147f1 100644 --- a/src/main/java/noppes/npcs/mixin/MixinItemStack.java +++ b/src/main/java/noppes/npcs/mixin/MixinItemStack.java @@ -1,9 +1,11 @@ package noppes.npcs.mixin; import kamkeel.npcs.util.AttributeItemUtil; +import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.client.gui.player.GuiAuctionInterface; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -28,9 +30,14 @@ public abstract class MixinItemStack { @Inject(method = "getTooltip", at = @At("TAIL"), cancellable = true) public void getAttributeTooltip(EntityPlayer player, boolean advanced, CallbackInfoReturnable> cir) { + boolean override = false; + if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface) { + override = true; + } + List tooltip = cir.getReturnValue(); if (hasTagCompound() && getTagCompound().hasKey(TAG_RPGCORE)) { - cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound())); + cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound(), override)); } } } diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index aebc9321d..8cb554c3e 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -9,9 +9,13 @@ import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityDome; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityAbilitySweeper; import kamkeel.npcs.entity.EntityEnergyProjectile; +import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.block.Block; import net.minecraft.command.CommandHandler; import net.minecraft.entity.Entity; @@ -126,9 +130,13 @@ import noppes.npcs.scripted.entity.ScriptArrow; import noppes.npcs.scripted.entity.ScriptDBCPlayer; import noppes.npcs.scripted.entity.ScriptEnergyBeam; import noppes.npcs.scripted.entity.ScriptEnergyDisc; +import noppes.npcs.scripted.entity.ScriptEnergyDome; import noppes.npcs.scripted.entity.ScriptEnergyLaser; import noppes.npcs.scripted.entity.ScriptEnergyOrb; +import noppes.npcs.scripted.entity.ScriptEnergyPanel; import noppes.npcs.scripted.entity.ScriptEnergyProjectile; +import noppes.npcs.scripted.entity.ScriptEnergySlicer; +import noppes.npcs.scripted.entity.ScriptEnergySweeper; import noppes.npcs.scripted.entity.ScriptEntity; import noppes.npcs.scripted.entity.ScriptEntityItem; import noppes.npcs.scripted.entity.ScriptFishHook; @@ -472,16 +480,16 @@ public class NpcAPI extends AbstractNpcAPI { data = new ScriptEntityData(new ScriptEnergyDisc<>((EntityAbilityDisc) entity)); else if (entity instanceof EntityAbilityLaser) data = new ScriptEntityData(new ScriptEnergyLaser<>((EntityAbilityLaser) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityEnergySlicer) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergySlicer<>((kamkeel.npcs.entity.EntityEnergySlicer) entity)); + else if (entity instanceof EntityEnergySlicer) + data = new ScriptEntityData(new ScriptEnergySlicer<>((EntityEnergySlicer) entity)); else if (entity instanceof EntityEnergyProjectile) data = new ScriptEntityData(new ScriptEnergyProjectile((EntityEnergyProjectile) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityEnergyDome) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergyDome<>((kamkeel.npcs.entity.EntityEnergyDome) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityEnergyPanel) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergyPanel<>((kamkeel.npcs.entity.EntityEnergyPanel) entity)); - else if (entity instanceof kamkeel.npcs.entity.EntityAbilitySweeper) - data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergySweeper<>((kamkeel.npcs.entity.EntityAbilitySweeper) entity)); + else if (entity instanceof EntityAbilityDome) + data = new ScriptEntityData(new ScriptEnergyDome<>((EntityAbilityDome) entity)); + else if (entity instanceof EntityAbilityPanel) + data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityAbilityPanel) entity)); + else if (entity instanceof EntityAbilitySweeper) + data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityAbilitySweeper) entity)); else data = new ScriptEntityData(new ScriptEntity<>(entity)); entity.registerExtendedProperties("ScriptedObject", data); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java index 29f330ff7..a015a06ad 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java @@ -1,15 +1,15 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityEnergyBarrier; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityAbilityDome; import noppes.npcs.api.entity.IEnergyBarrier; import noppes.npcs.scripted.constants.EntityType; /** * Base script wrapper for energy barrier entities (Dome, Panel). - * All shared methods delegate directly to EntityEnergyBarrier base. + * All shared methods delegate directly to EntityAbilityBarrier base. */ -public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { +public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { public ScriptEnergyBarrier(T entity) { super(entity); @@ -89,6 +89,14 @@ public class ScriptEnergyBarrier extends ScriptEn entity.getBarrierData().defaultMultiplier = multiplier; } + public boolean isSolid() { + return entity.getBarrierData().solid; + } + + public void setSolid(boolean solid) { + entity.getBarrierData().solid = solid; + } + public boolean isKnockbackEnabled() { return entity.getBarrierData().knockbackEnabled; } @@ -105,15 +113,15 @@ public class ScriptEnergyBarrier extends ScriptEn entity.getBarrierData().knockbackStrength = strength; } - public int getKnockbackTarget() { - return entity.getBarrierData().knockbackTarget; + public boolean isAbsorbing() { + return entity.getBarrierData().absorbing; } - public void setKnockbackTarget(int target) { - entity.getBarrierData().knockbackTarget = target; + public void setAbsorbing(boolean absorbing) { + entity.getBarrierData().absorbing = absorbing; } public int getBarrierType() { - return entity instanceof EntityEnergyDome ? 0 : 1; + return entity instanceof EntityAbilityDome ? 0 : 1; } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java index e022118f7..9bcceefbc 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java @@ -1,10 +1,10 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityAbilityDome; import noppes.npcs.api.entity.IEnergyDome; import noppes.npcs.scripted.constants.EntityType; -public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { +public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { public ScriptEnergyDome(T entity) { super(entity); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java index 04c730fad..fa929b4a8 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java @@ -1,10 +1,10 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityAbilityPanel; import noppes.npcs.api.entity.IEnergyPanel; import noppes.npcs.scripted.constants.EntityType; -public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { +public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { public ScriptEnergyPanel(T entity) { super(entity); @@ -52,6 +52,6 @@ public class ScriptEnergyPanel extends ScriptEnergy } public boolean isLaunched() { - return entity.getMode() == EntityEnergyPanel.PanelMode.LAUNCHED; + return entity.getMode() == EntityAbilityPanel.PanelMode.LAUNCHED; } } diff --git a/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java b/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java index e52742812..8c3fcde4c 100644 --- a/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java +++ b/src/main/java/tconstruct/client/tabs/InventoryTabCustomNpc.java @@ -4,6 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import noppes.npcs.CustomItems; +import noppes.npcs.client.gui.player.inventory.GuiAbilities; import noppes.npcs.client.gui.player.inventory.GuiCNPCInventory; import noppes.npcs.client.gui.player.inventory.GuiFaction; import noppes.npcs.client.gui.player.inventory.GuiParty; @@ -58,5 +59,8 @@ public class InventoryTabCustomNpc extends AbstractTab { if (tab == -104) { mc.displayGuiScreen(new GuiProfiles()); } + if (tab == -105) { + mc.displayGuiScreen(new GuiAbilities()); + } } } diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json index 0a0ba828c..e34dd5d21 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json @@ -1,196 +1,196 @@ { - "Loop": 1, + "Loop": 2, "Speed": 1.0f, "Frames": [ - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": -7.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": -31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -6.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "LEFT_ARM", - "Rotation1": -25.0f, - "Rotation0": -90.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": -25.0f - } - ], - "Smooth": 0b, - "Duration": 2 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": -7.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": -31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": -1.0f, - "Part": "RIGHT_ARM", - "Rotation1": 25.0f, - "Rotation0": -90.0f, - "Pivot0": 1.0f, - "Pivot1": 1.0f, - "Rotation2": 25.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -6.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -7.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 5 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 3.0f, - "FrameParts": [ - { - "Pivot2": -7.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": -31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 18.0f - }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": 31.0f, - "Rotation0": 6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -6.0f, - "Part": "BODY", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "LEFT_ARM", - "Rotation1": -25.0f, - "Rotation0": -90.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": -25.0f - } - ], - "Smooth": 0b, - "Duration": 5 - } + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 25.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 25.0f + }, + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } ], "CurrentFrameTime": 0, "CurrentFrame": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json index 58a305e78..c632afc9c 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json @@ -1,5 +1,5 @@ { - "Loop": 3, + "Loop": -1, "Speed": 1.0f, "Frames": [ { @@ -252,7 +252,7 @@ } ], "Smooth": 0b, - "Duration": 3 + "Duration": 20 } ], "CurrentFrameTime": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json index 994e2190c..cb8973971 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_Orb_Active.json @@ -1,11 +1,11 @@ { - "Loop": 0, + "Loop": -1, "Speed": 1.0f, "Frames": [ { "ColorMarker": 16777215, "Comment": "", - "Speed": 0.5f, + "Speed": 1.0f, "FrameParts": [ { "Pivot2": 0.0f, @@ -63,7 +63,7 @@ } ], "Smooth": 0b, - "Duration": 30 + "Duration": 20 } ], "CurrentFrameTime": 0, diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index b963e5d34..dbe0442cd 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -2,6 +2,7 @@ customnpcs.defaultTextColor=404040 key.categories.customnpc=CustomNPC+ key.customnpcs.special=Special Key +key.customnpcs.abilityHudKey=HUD Key key.npcInventory=NPC Inventory entity.CustomNpc.name=Custom Npc @@ -167,6 +168,12 @@ gui.apply=Apply gui.cancel=Cancel gui.continue=Continue gui.yes=Yes +gui.abilities=Abilities +gui.toggles=Toggles +gui.toggle=Toggle +gui.toggle.active=Active +gui.toggle.inactive=Inactive +gui.abilityHotbar=Ability Hotbar gui.lineColor1=Upper line color gui.lineColor2=Middle line color @@ -1555,6 +1562,7 @@ ability.sweep.spin=Spin # Dash Mode ability.dash.aggressive=Aggressive ability.dash.defensive=Defensive +ability.dash.directional=Directional # Counter Type ability.counter.flat=Flat @@ -1665,6 +1673,9 @@ ability.cnpc.sweeper=Sweeper ability.weight=Weight ability.windUpTicks=Wind Up ability.cooldownTicks=Cooldown +ability.perAbilityCooldown=Per-Ability +ability.freeOnCast=Free on Cast +ability.hover.freeOnCast=Ability enters cooldown immediately after entities are spawned, allowing the caster to use other abilities while summoned entities remain active ability.lockMovement=Lock Movement ability.rotationMode=Rotation ability.rotationPhase=Phase @@ -1987,7 +1998,7 @@ ability.hover.speed=Movement speed of projectile ability.hover.lifetime=Maximum ticks before despawning ability.hover.knockback=Push force applied to targets ability.hover.boomerang=Projectile returns to caster after reaching max distance -ability.hover.dashMode=Aggressive dashes toward target, Defensive dashes away +ability.hover.dashMode=Aggressive dashes toward target, Defensive dashes away, Directional dashes in looking direction ability.hover.aoe=Affects all valid targets in range instead of just one ability.hover.dmgOnPull=Deal damage continuously while pulling targets ability.hover.lineOfSight=Requires clear line of sight to the target @@ -2011,7 +2022,7 @@ ability.cnpc.shield=Shield ability.cnpc.slicer=Slicer ability.section.barrier=Barrier -ability.section.knockback=Knockback +ability.section.properties=Properties ability.section.panel=Panel ability.section.launch=Launch ability.section.slicer=Slicer @@ -2024,17 +2035,17 @@ ability.defaultMultiplier=Default Multiplier ability.innerAlpha=Inner Alpha ability.heightOffset=Height Offset +ability.solid=Solid ability.knockbackEnabled=Knockback ability.knockbackStrength=Knockback Strength -ability.knockbackTarget=Target - -ability.section.melee=Melee -ability.meleeEnabled=Melee Attackable +ability.absorbing=Absorbing +ability.meleeEnabled=Allows Melee ability.meleeDamageMultiplier=Melee Multiplier ability.followCaster=Follow Caster ability.hover.followCaster=Dome stays centered on the caster as they move + ability.variant.small=Small ability.variant.large=Large ability.variant.static=Static @@ -2055,19 +2066,56 @@ ability.userType.PLAYER_ONLY=Players ability.userType.BOTH=Both ability.dieOnImpact=Die on Impact +ability.icon.section.uv=UV Coordinates +ability.icon.x=Icon X +ability.icon.y=Icon Y + gui.both=Both gui.players=Players # Conditions condition.edit=Edit Condition -condition.hp_above=NPC HP Above -condition.hp_below=NPC HP Below -condition.target_hp_above=Target HP Above -condition.target_hp_below=Target HP Below +condition.filter=Filter Type +condition.filter.target=Target +condition.filter.caster=Caster +condition.filter.both=Both + +# Condition HP Threshold +condition.hp_threshold=HP Threshold +condition.hp_above=HP Above +condition.hp_below=HP Below +condition.hp_equal=HP Equal +condition.threshold=Threshold +condition.percent=Use Percent +condition.threshold_type=Threshold Type + +# Condition Hit Count condition.hit_count=Hit Count -condition.percent=Threshold -condition.hits=Required Hits -condition.within=Within (ticks) +condition.required_hits=Required Hits +condition.within_ticks=Within (ticks) + +# Condition Item +condition.item=Has Item +condition.usage_type=Usage Type +condition.armor_slot=Armor Slot +condition.full_armor=Full Armor +condition.item_count=Item Count +condition.item_name=Item Name + +# Condition Threshold +condition.above=Above +condition.below=Below +condition.equal=Equal +condition.threshold_flat=Threshold +condition.threshold_percent=Threshold % + +# Condition Quest Completed +condition.quest_completed=Quest Completed +condition.select_quest=Select Quest + +# Condition Has Effect +condition.has_effect=Has Effect +condition.select_effect=Select Effect # Condition Hover Tooltips condition.hover.type=Condition type that must be met for ability to activate diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png b/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png new file mode 100644 index 000000000..ad84e3327 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability_fallback.png differ