Merge branch 'dev' into syntax-highlighter-unified

This commit is contained in:
bigguy345 committed 2026-02-24 10:32:17 +02:00
commit fa38f93677
67 files changed
+642 -868

No files matched your search

+1 -1
View File
@@ -142,7 +142,7 @@ public class CmdNpc extends ChMcLogger {
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
@@ -59,12 +59,17 @@ public class RenderAbilityDisc extends RenderEnergyAbility {
double motionX = entity.motionX;
double motionY = entity.motionY;
double motionZ = entity.motionZ;
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
// Only apply motion-based facing when speed is meaningful.
// Near-zero motion makes atan2 unstable, producing jittery angles.
if (speedSq > 0.0001) {
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Apply Y-axis rotation for spin
GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
@@ -23,9 +23,6 @@ public class RenderAbilityLaser extends RenderEnergyAbility {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityLaser laser = (EntityAbilityLaser) entity;
setupRenderState();
@@ -46,12 +46,17 @@ public class RenderAbilityOrb extends RenderEnergyAbility {
double motionX = entity.motionX;
double motionY = entity.motionY;
double motionZ = entity.motionZ;
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
// Only apply motion-based facing when speed is meaningful.
// Near-zero motion makes atan2 unstable, producing jittery angles.
if (speedSq > 0.0001) {
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Use entity's interpolated rotation for smooth spinning
GL11.glRotatef(orb.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f);
@@ -200,7 +200,7 @@ public class NpcCommand extends CommandKamkeelBase {
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
@@ -410,7 +410,7 @@ public class AbilityController implements IAbilityHandler {
customAbilities.put(name, ability);
customAbilitiesById.put(uuid, ability);
customAbilityRevision++;
LogWriter.info("Saved custom ability: " + name + " [" + uuid + "]");
LogWriter.script("Saved custom ability: " + name + " [" + uuid + "]");
SyncController.syncAllCustomAbilities();
return true;
} catch (Exception e) {
@@ -464,7 +464,7 @@ public class AbilityController implements IAbilityHandler {
}
customAbilityRevision++;
LogWriter.info("Deleted custom ability: " + name);
LogWriter.script("Deleted custom ability: " + name);
SyncController.syncAllCustomAbilities();
return true;
}
@@ -640,7 +640,7 @@ public class AbilityController implements IAbilityHandler {
chainedAbilities.put(name, chain);
chainedAbilitiesById.put(uuid, chain);
chainedAbilityRevision++;
LogWriter.info("Saved chained ability: " + name + " [" + uuid + "]");
LogWriter.script("Saved chained ability: " + name + " [" + uuid + "]");
SyncController.syncAllChainedAbilities();
return true;
} catch (Exception e) {
@@ -692,7 +692,7 @@ public class AbilityController implements IAbilityHandler {
}
chainedAbilityRevision++;
LogWriter.info("Deleted chained ability: " + name);
LogWriter.script("Deleted chained ability: " + name);
SyncController.syncAllChainedAbilities();
return true;
}
@@ -1176,6 +1176,27 @@ public class AbilityController implements IAbilityHandler {
return false;
}
public Boolean fireCheckConditions(AbilityCondition condition, EntityLivingBase caster, EntityLivingBase target) {
for (IAbilityExtender ext : extenders) {
Boolean result = ext.onCheckCondition(condition, caster, target);
if (result != null) {
return result;
}
}
return null;
}
public Boolean fireCheckConditionsForPlayer(AbilityCondition condition, EntityLivingBase player) {
for (IAbilityExtender ext : extenders) {
Boolean result = ext.onCheckConditionForPlayer(condition, player);
if (result != null) {
return result;
}
}
return null;
}
// ═══════════════════════════════════════════════════════════════════════════
// IAbilityHandler
// ═══════════════════════════════════════════════════════════════════════════
@@ -1228,7 +1249,7 @@ public class AbilityController implements IAbilityHandler {
public boolean isAllowedByPlayer(String typeId) {
if (abilityTypes.containsKey(typeId)) {
Ability temp = abilityTypes.get(typeId).get();
return temp.getAllowedBy() == UserType.PLAYER_ONLY;
return temp.getAllowedBy().allowsPlayer();
}
return false;
@@ -1237,7 +1258,7 @@ public class AbilityController implements IAbilityHandler {
public boolean isAllowedByNPC(String typeId) {
if (abilityTypes.containsKey(typeId)) {
Ability temp = abilityTypes.get(typeId).get();
return temp.getAllowedBy() == UserType.NPC_ONLY;
return temp.getAllowedBy().allowsNpc();
}
return false;
@@ -12,6 +12,9 @@ import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSyncAction;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.packets.data.LoginPacket;
import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket;
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
import kamkeel.npcs.network.packets.data.large.SyncPacket;
import kamkeel.npcs.network.packets.request.party.PartyInfoPacket;
@@ -865,6 +868,32 @@ public class SyncController {
PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP);
}
/**
* Full sync of all player ability state to the client: unlocked abilities,
* selection, toggles, hotbar layout, and cooldowns.
* Used for entity reconstruction and other full-refresh scenarios.
*/
public static void syncAbilities(EntityPlayerMP playerMP) {
PlayerData playerData = PlayerData.get(playerMP);
if (playerData == null) return;
PlayerAbilitySyncPacket.sendToPlayer(playerMP);
AbilityHotbarSyncPacket.sendToPlayer(playerMP);
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
}
/**
* Lightweight sync of cooldown state only (global + per-ability).
* Called periodically (every 10 ticks) to keep the client's cooldown
* display accurate. Cooldowns are transient and not part of NBT sync.
*/
public static void syncAbilityCooldowns(EntityPlayerMP playerMP) {
PlayerData playerData = PlayerData.get(playerMP);
if (playerData == null) return;
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
}
@SideOnly(Side.CLIENT)
public static void clientSyncEffects(NBTTagCompound compound) {
PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
@@ -184,6 +184,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
// Burst execution state
protected transient int burstIndex = 0;
protected transient List<Entity> burstEntities = new ArrayList<>();
protected transient float damageMultiplier = 1.0f; // Ability-internal damage scaling (e.g., Slam height)
// ═══════════════════════════════════════════════════════════════════
// PREVIEW STATE (client-side only, not saved)
@@ -632,7 +633,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
defs.add(FieldDef.stringField("gui.displayName", this::getRawDisplayName, this::setDisplayName)
.tab("General"));
defs.add(FieldDef.labelField("ability.validFor", () ->
"\u00A7e" + StatCollector.translateToLocal("ability.userType." + getAllowedBy().name()))
"\u00A7e" + StatCollector.translateToLocal("ability.userType." + getAllowedBy().name()))
.tab("General"));
defs.add(FieldDef.row(
FieldDef.intField("ability.weight", this::getWeight, this::setWeight).range(1, 1000),
@@ -961,31 +962,46 @@ public abstract class Ability implements IAbility, IAbilityAction {
/**
* Find the ground level at a given position.
* Searches downward from the given Y to find a solid block.
* Uses default search range of 3 blocks — if no ground is found,
* returns slightly below the entity for airborne telegraph placement.
*
* @param world The world
* @param x X coordinate
* @param startY Starting Y coordinate (entity feet position)
* @param z Z coordinate
* @return The Y coordinate of the ground surface
* @return The Y coordinate of the ground surface, or startY - 0.5 if airborne
*/
public static double findGroundLevel(World world, double x, double startY, double z) {
if (world == null) return startY;
return findGroundLevel(world, x, startY, z, 3);
}
/**
* Find the ground level at a given position with configurable search range.
* Searches downward from the given Y to find a solid block.
*
* @param world The world
* @param x X coordinate
* @param startY Starting Y coordinate (entity feet position)
* @param z Z coordinate
* @param maxSearchDown Maximum blocks to search downward
* @return The Y coordinate of the ground surface, or startY - 0.5 if no ground found
*/
public static double findGroundLevel(World world, double x, double startY, double z, int maxSearchDown) {
if (world == null) return startY - 0.5;
int blockX = (int) Math.floor(x);
int blockZ = (int) Math.floor(z);
int startBlockY = (int) Math.floor(startY);
// Search downward for solid ground (max 10 blocks down)
for (int checkY = startBlockY; checkY >= startBlockY - 10 && checkY >= 0; checkY--) {
for (int checkY = startBlockY; checkY >= startBlockY - maxSearchDown && checkY >= 0; checkY--) {
Block block = world.getBlock(blockX, checkY, blockZ);
if (block != null && block.getMaterial().isSolid()) {
// Found solid block, telegraph goes on top of it
return checkY + 1;
}
}
// No ground found, use original position
return startY;
// No ground found within range — place slightly under entity
return startY - 0.5;
}
/**
@@ -1154,8 +1170,8 @@ public abstract class Ability implements IAbility, IAbilityAction {
public void interrupt() {
cleanupBurstEntities();
cleanup();
if (interruptible && (phase == AbilityPhase.WINDUP || phase == AbilityPhase.BURST_DELAY)) {
// Interrupted during windup or burst delay - go to dazed state
if (interruptible && phase == AbilityPhase.WINDUP) {
// Interrupted during windup - go to dazed state
phase = AbilityPhase.DAZED;
currentTick = 0;
} else {
@@ -1192,13 +1208,15 @@ public abstract class Ability implements IAbility, IAbilityAction {
/**
* Check if can be interrupted by this damage source.
* Only direct physical hits (not magic, fire, or other indirect damage) can interrupt.
* Interruption only occurs during WINDUP phase - if ability is already active, it completes.
* Interruption only occurs during WINDUP phase (including burst replay windups).
* BURST_DELAY is not interruptible - only the windup animation itself can be interrupted.
* For chained abilities, windUpAll controls whether subsequent entries even have a windup.
*
* @param source The damage source
* @return true if the ability should be interrupted
*/
public boolean canInterrupt(DamageSource source) {
if (!interruptible || (phase != AbilityPhase.WINDUP && phase != AbilityPhase.BURST_DELAY)) {
if (!interruptible || phase != AbilityPhase.WINDUP) {
return false;
}
if (isInvulnerableForCurrentPhase()) {
@@ -1324,6 +1342,13 @@ public abstract class Ability implements IAbility, IAbilityAction {
public boolean checkConditions(EntityLivingBase caster, EntityLivingBase target) {
for (AbilityCondition c : conditions) {
if (!c.getUserType().allowsNpc()) continue;
Boolean extendedCondition = AbilityController.Instance.fireCheckConditions(c, caster, target);
if (extendedCondition != null) {
if (!extendedCondition) return false;
continue;
}
if (!c.check(caster, target)) return false;
}
return true;
@@ -1336,6 +1361,13 @@ public abstract class Ability implements IAbility, IAbilityAction {
for (AbilityCondition c : conditions) {
if (!c.getUserType().allowsPlayer()) continue;
if (c.requiresTarget()) continue;
Boolean extendedCondition = AbilityController.Instance.fireCheckConditionsForPlayer(c, caster);
if (extendedCondition != null) {
if (!extendedCondition) return false;
continue;
}
if (!c.check(caster, null)) return false;
}
return true;
@@ -1448,8 +1480,8 @@ public abstract class Ability implements IAbility, IAbilityAction {
lockMovement = LockMode.fromOrdinal(nbt.getInteger("lockMovement"));
rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode"));
rotationPhase = LockMode.fromOrdinal(nbt.getInteger("rotationPhase"));
windUpColor = nbt.getInteger("windUpColor");
activeColor = nbt.getInteger("activeColor");
windUpColor = nbt.hasKey("windUpColor") ? nbt.getInteger("windUpColor") : 0x80FF4400;
activeColor = nbt.hasKey("activeColor") ? nbt.getInteger("activeColor") : 0xC0FF0000;
windUpSound = nbt.getString("windUpSound");
activeSound = nbt.getString("activeSound");
windUpAnimationId = nbt.getInteger("windUpAnimationId");
@@ -1465,7 +1497,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
telegraphType = TelegraphType.CIRCLE;
}
telegraphHeightOffset = nbt.getFloat("telegraphHeightOffset");
customData = nbt.getCompoundTag("customData");
customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy();
allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy"));
ignoreCooldown = nbt.getBoolean("ignoreCooldown");
perAbilityCooldown = nbt.getBoolean("perAbilityCooldown");
@@ -1489,7 +1521,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
burstEnabled = nbt.getBoolean("burstEnabled");
burstAmount = nbt.getInteger("burstAmount");
burstDelay = nbt.getInteger("burstDelay");
burstReplayAnimations = nbt.getBoolean("burstReplayAnimations");
burstReplayAnimations = nbt.hasKey("burstReplayAnimations") ? nbt.getBoolean("burstReplayAnimations") : true;
burstOverlap = nbt.getBoolean("burstOverlap");
// Conditions
@@ -2050,6 +2082,18 @@ public abstract class Ability implements IAbility, IAbilityAction {
return phase;
}
/**
* Get the damage multiplier applied by the ability itself (e.g. Slam height scaling).
* Extenders should apply this after their own damage calculation.
*/
public float getDamageMultiplier() {
return damageMultiplier;
}
public void setDamageMultiplier(float damageMultiplier) {
this.damageMultiplier = damageMultiplier;
}
/**
* Get the current execution phase as int (0=IDLE, 1=WINDUP, 2=ACTIVE, 3=DAZED).
* Required for IAbility interface.
@@ -1,313 +0,0 @@
package kamkeel.npcs.controllers.data.ability.conditions;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.entity.EntityNPCInterface;
/**
* Interface for ability usage conditions.
* Conditions determine when an ability is eligible to be used.
*/
public interface Condition {
/**
* Check if this condition is met.
*
* @param caster The entity that would use the ability (NPC or Player)
* @param target The current target (may be null for self-targeting abilities or players)
* @return true if the condition is satisfied
*/
boolean check(EntityLivingBase caster, EntityLivingBase target);
/**
* Whether this condition requires a target entity to evaluate.
* Conditions that return true here will be skipped for player ability checks.
*/
default boolean requiresTarget() {
return false;
}
/**
* Get the condition type ID for serialization.
*/
String getTypeId();
/**
* Write this condition to NBT.
*/
NBTTagCompound writeNBT();
/**
* Read this condition from NBT.
*/
void readNBT(NBTTagCompound nbt);
/**
* Create a Condition from NBT data.
* Uses the "type" field to determine which implementation to create.
*/
static Condition fromNBT(NBTTagCompound nbt) {
if (nbt == null || !nbt.hasKey("type")) {
return null;
}
String type = nbt.getString("type");
Condition condition = null;
switch (type) {
case "hp_above":
condition = new ConditionHPAbove();
break;
case "hp_below":
condition = new ConditionHPBelow();
break;
case "target_hp_above":
condition = new ConditionTargetHPAbove();
break;
case "target_hp_below":
condition = new ConditionTargetHPBelow();
break;
case "hit_count":
condition = new ConditionHitCount();
break;
default:
return null;
}
condition.readNBT(nbt);
return condition;
}
// ═══════════════════════════════════════════════════════════════════
// BUILT-IN CONDITION IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════════════
/**
* Condition: Caster HP is above a percentage threshold.
*/
class ConditionHPAbove implements Condition {
private float threshold = 0.5f; // 50%
public ConditionHPAbove() {
}
public ConditionHPAbove(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
return caster.getHealth() / caster.getMaxHealth() > threshold;
}
@Override
public String getTypeId() {
return "hp_above";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Caster HP is below a percentage threshold.
*/
class ConditionHPBelow implements Condition {
private float threshold = 0.5f;
public ConditionHPBelow() {
}
public ConditionHPBelow(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
return caster.getHealth() / caster.getMaxHealth() < threshold;
}
@Override
public String getTypeId() {
return "hp_below";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Target HP is above a percentage threshold.
* Requires a target - will be skipped for player ability checks.
*/
class ConditionTargetHPAbove implements Condition {
private float threshold = 0.5f;
public ConditionTargetHPAbove() {
}
public ConditionTargetHPAbove(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
if (target == null) return false;
return target.getHealth() / target.getMaxHealth() > threshold;
}
@Override
public boolean requiresTarget() {
return true;
}
@Override
public String getTypeId() {
return "target_hp_above";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Target HP is below a percentage threshold.
* Requires a target - will be skipped for player ability checks.
*/
class ConditionTargetHPBelow implements Condition {
private float threshold = 0.5f;
public ConditionTargetHPBelow() {
}
public ConditionTargetHPBelow(float threshold) {
this.threshold = threshold;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
if (target == null) return false;
return target.getHealth() / target.getMaxHealth() < threshold;
}
@Override
public boolean requiresTarget() {
return true;
}
@Override
public String getTypeId() {
return "target_hp_below";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setFloat("threshold", threshold);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
threshold = nbt.getFloat("threshold");
}
}
/**
* Condition: Caster has been hit X times within a time window.
* Useful for reactive abilities that trigger after receiving multiple hits.
* Currently only works for NPCs (requires DataAbilities hit tracking).
*/
class ConditionHitCount implements Condition {
private int requiredHits = 3;
private int withinTicks = 60;
public ConditionHitCount() {
}
public ConditionHitCount(int requiredHits, int withinTicks) {
this.requiredHits = requiredHits;
this.withinTicks = withinTicks;
}
@Override
public boolean check(EntityLivingBase caster, EntityLivingBase target) {
// Check NPC's recent hit count from DataAbilities
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;
}
@Override
public String getTypeId() {
return "hit_count";
}
@Override
public NBTTagCompound writeNBT() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("type", getTypeId());
nbt.setInteger("requiredHits", requiredHits);
nbt.setInteger("withinTicks", withinTicks);
return nbt;
}
@Override
public void readNBT(NBTTagCompound nbt) {
requiredHits = nbt.getInteger("requiredHits");
withinTicks = nbt.getInteger("withinTicks");
}
public int getRequiredHits() {
return requiredHits;
}
public void setRequiredHits(int hits) {
this.requiredHits = hits;
}
public int getWithinTicks() {
return withinTicks;
}
public void setWithinTicks(int ticks) {
this.withinTicks = ticks;
}
}
}
@@ -17,6 +17,7 @@ public class ConditionHitCount extends AbilityCondition {
public ConditionHitCount() {
this.typeId = "condition.cnpc.hit_count";
this.name = "condition.hit_count";
this.conditionFilter = ConditionFilter.CASTER;
}
@Override
@@ -64,8 +65,7 @@ public class ConditionHitCount extends AbilityCondition {
@SideOnly(Side.CLIENT)
@Override
public String getConditionSummary() {
String filterLabel = StatCollector.translateToLocal(getFilter().toString());
return "[" + filterLabel + "] Hit " + requiredHits + " times in " + withinTicks + " ticks";
return "[Caster] Hit " + requiredHits + " times in " + withinTicks + " ticks";
}
@Override
@@ -99,6 +99,7 @@ public class ConditionItem extends AbilityCondition {
private boolean checkOffhand(EntityLivingBase entity) {
// No offhand for players
if (entity instanceof EntityPlayer) return false;
if (!(entity instanceof EntityNPCInterface)) return false;
ItemStack item = ((EntityNPCInterface) entity).getOffHand();
return matchesItem(item);
@@ -31,7 +31,7 @@ public abstract class ConditionThreshold extends AbilityCondition {
EQUAL {
@Override
public boolean test(float value, float threshold) {
return value == threshold;
return Math.abs(value - threshold) < 0.001f;
}
};
@@ -190,7 +190,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
if (allAllowPlayer && allAllowNpc) return UserType.BOTH;
if (allAllowPlayer) return UserType.PLAYER_ONLY;
if (allAllowNpc) return UserType.NPC_ONLY;
return UserType.NPC_ONLY;
return UserType.NONE;
}
public List<AbilityCondition> getConditions() {
@@ -441,6 +441,6 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
}
// Custom data (for external mods)
customData = nbt.getCompoundTag("customData");
customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy();
}
}
@@ -1,291 +0,0 @@
package kamkeel.npcs.controllers.data.ability.data.energy;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants;
import noppes.npcs.api.IPos;
import noppes.npcs.api.ability.data.IEnergyTrajectoryData;
import noppes.npcs.scripted.NpcAPI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
public class EnergyTrajectoryData implements IEnergyTrajectoryData {
public int currentPath = 0;
private final List<Path> trajectory = new ArrayList<>();
public EnergyTrajectoryData() {
}
public EnergyTrajectoryData(int startingPath, Path... paths) {
trajectory.addAll(Arrays.asList(paths));
this.currentPath = startingPath < trajectory.size() && startingPath >= 0 ? startingPath : 0;
}
@Override
public int getCurrentPath() {
return currentPath;
}
@Override
public void setCurrentPath(int currentPath) {
this.currentPath = currentPath;
}
@Override
public int getDelay(int path) {
if (getPath(path) == null) return -1;
return getPath(path).getDelay();
}
@Override
public void setDelay(int path, int ticks) {
if (getPath(path) == null) return;
getPath(path).setDelay(ticks);
}
@Override
public IPos getPos(int path) {
IPath p = getPath(path);
return p == null ? null : p.getPos();
}
@Override
public void setPos(int path, IPos pos) {
IPath p = getPath(path);
if (p != null) p.setPos(pos);
}
@Override
public boolean isConcluded(int path) {
IPath p = getPath(path);
return p != null && p.isConcluded();
}
@Override
public void setConcluded(int path, boolean concluded) {
IPath p = getPath(path);
if (p != null) p.setConcluded(concluded);
}
@Override
public double getX(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getX();
}
@Override
public double getY(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getY();
}
@Override
public double getZ(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getZ();
}
@Override
public void setX(int path, double x) {
IPath p = getPath(path);
if (p != null) p.setX(x);
}
@Override
public void setY(int path, double y) {
IPath p = getPath(path);
if (p != null) p.setY(y);
}
@Override
public void setZ(int path, double z) {
IPath p = getPath(path);
if (p != null) p.setZ(z);
}
public IPath getPath(int path) {
if (path < 0 || path >= trajectory.size()) return null;
return trajectory.get(path);
}
@Override
public void setPath(int path, IPos pos) {
setPath(path, pos, 0);
}
@Override
public void setPath(int path, IPos pos, int delay) {
setPath(path, pos.getX(), pos.getY(), pos.getZ(), delay);
}
@Override
public void setPath(int path, double x, double y, double z) {
setPath(path, x, y, z, 0);
}
@Override
public void setPath(int path, double x, double y, double z, int delay) {
Path newPath = new Path(
NpcAPI.Instance().getIPos(x, y, z),
delay
);
while (trajectory.size() <= path) {
trajectory.add(null);
}
trajectory.set(path, newPath);
}
@Override
public IPath createPath(IPos pos) {
return new Path(pos, 0);
}
@Override
public IPath createPath(IPos pos, int delay) {
return new Path(pos, delay);
}
@Override
public IPath createPath(double x, double y, double z) {
return createPath(x, y, z, 0);
}
@Override
public IPath createPath(double x, double y, double z, int delay) {
return new Path(NpcAPI.Instance().getIPos(x, y, z), delay);
}
@Override
public void forEach(BiConsumer<Integer, IPath> lambda) {
for (int i = 0; i < trajectory.size(); i++) {
lambda.accept(i, trajectory.get(i));
}
}
public int size() {
return trajectory.size();
}
public boolean isEmpty() {
return trajectory.isEmpty();
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("currentPath", currentPath);
for (int i = 0; i < trajectory.size(); i++) {
Path path = trajectory.get(i);
NBTTagCompound pathNbt = new NBTTagCompound();
path.writeNBT(pathNbt);
nbt.setTag("Path_" + i, pathNbt);
}
}
public void readNBT(NBTTagCompound nbt) {
this.currentPath = nbt.getInteger("currentPath");
trajectory.clear();
int i = 0;
while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) {
NBTTagCompound pathNbt = nbt.getCompoundTag("Path_" + i);
Path path = (Path) createPath(0, 0, 0);
path.readNBT(pathNbt);
trajectory.add(path);
i++;
}
}
public static class Path implements IEnergyTrajectoryData.IPath {
public IPos pos;
public int delayTicks;
public boolean concluded;
public Path(IPos pos, int delayTicks) {
this.pos = pos;
this.delayTicks = delayTicks;
}
@Override
public IPos getPos() {
return pos;
}
@Override
public void setPos(IPos pos) {
this.pos = pos;
}
@Override
public int getDelay() {
return delayTicks;
}
@Override
public void setDelay(int delayTicks) {
this.delayTicks = delayTicks;
}
@Override
public boolean isConcluded() {
return concluded;
}
@Override
public void setConcluded(boolean concluded) {
this.concluded = concluded;
}
@Override
public double getX() {
return pos.getX();
}
@Override
public void setX(double x) {
this.pos = NpcAPI.Instance().getIPos(x, getY(), getZ());
}
@Override
public double getY() {
return pos.getY();
}
@Override
public void setY(double y) {
this.pos = NpcAPI.Instance().getIPos(getX(), y, getZ());
}
@Override
public double getZ() {
return pos.getZ();
}
@Override
public void setZ(double z) {
this.pos = NpcAPI.Instance().getIPos(pos.getX(), pos.getY(), z);
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("delay", delayTicks);
nbt.setBoolean("concluded", concluded);
nbt.setDouble("X", getX());
nbt.setDouble("Y", getY());
nbt.setDouble("Z", getZ());
}
public void readNBT(NBTTagCompound nbt) {
this.delayTicks = nbt.getInteger("delay");
this.concluded = nbt.getBoolean("concluded");
double x = nbt.getDouble("X");
double y = nbt.getDouble("Y");
double z = nbt.getDouble("Z");
this.pos = NpcAPI.Instance().getIPos(x, y, z);
}
}
}
@@ -6,7 +6,8 @@ package kamkeel.npcs.controllers.data.ability.enums;
public enum UserType {
NPC_ONLY,
PLAYER_ONLY,
BOTH;
BOTH,
NONE;
public boolean allowsNpc() {
return this == NPC_ONLY || this == BOTH;
@@ -1,5 +1,6 @@
package kamkeel.npcs.controllers.data.ability.extender;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.Ability;
import net.minecraft.entity.EntityLivingBase;
@@ -117,4 +118,12 @@ public interface IAbilityExtender {
default boolean onAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) {
return false;
}
default Boolean onCheckCondition(AbilityCondition condition, EntityLivingBase caster, EntityLivingBase target) {
return null;
}
default Boolean onCheckConditionForPlayer(AbilityCondition condition, EntityLivingBase player) {
return null;
}
}
@@ -60,6 +60,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
// ==================== NPC START POSITION ====================
private double npcStartX, npcStartY, npcStartZ;
private boolean hasStartPosition = false;
// ==================== PREVIEW CONTENT ====================
private TelegraphInstance previewTelegraph;
@@ -98,6 +99,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
this.hasStartPosition = true;
// Create invisible fake target NPC for targeting
createFakeTarget(npc);
@@ -127,6 +129,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
this.hasStartPosition = true;
// Resolve all entries to deep-copied abilities
chainAbilities = new ArrayList<>();
@@ -315,7 +318,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
previewEntities.clear();
// Reset NPC position to start position (undo movement from Slam/Charge/Dash)
if (previewNpc != null && npcStartX != 0 && npcStartY != 0 && npcStartZ != 0) {
if (previewNpc != null && hasStartPosition) {
previewNpc.posX = npcStartX;
previewNpc.posY = npcStartY;
previewNpc.posZ = npcStartZ;
@@ -97,6 +97,7 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
}
if (movementDirection == null) {
stopMomentum(caster);
signalCompletion();
return;
}
@@ -249,10 +250,10 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.chargeSpeed = nbt.getFloat("chargeSpeed");
this.damage = nbt.getFloat("damage");
this.knockback = nbt.getFloat("knockback");
this.hitWidth = nbt.getFloat("hitWidth");
this.chargeSpeed = nbt.hasKey("chargeSpeed") ? Math.max(0.01f, nbt.getFloat("chargeSpeed")) : 0.8f;
this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f;
this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 3.0f;
this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 1.5f;
}
// Getters & Setters
@@ -252,8 +252,8 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash {
} catch (Exception e) {
this.dashMode = DashMode.DEFENSIVE;
}
this.dashDistance = nbt.getFloat("dashDistance");
this.dashSpeed = nbt.getFloat("dashSpeed");
this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f;
this.dashSpeed = nbt.hasKey("dashSpeed") ? Math.max(0.01f, nbt.getFloat("dashSpeed")) : 0.5f;
}
// Getters & Setters
@@ -173,6 +173,19 @@ public class AbilityEffect extends Ability implements IAbilityEffect {
if (tick >= durationTicks) {
signalCompletion();
return;
}
// Early completion if all affected entities are dead
boolean allDead = true;
for (EntityLivingBase entity : getAffectedEntities()) {
if (!entity.isDead) {
allDead = false;
break;
}
}
if (!getAffectedEntities().isEmpty() && allDead) {
signalCompletion();
}
}
@@ -123,6 +123,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
if (tick >= durationTicks) {
signalCompletion();
return;
}
// Just enough to see the counter animation
@@ -194,7 +195,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
return AnimationController.Instance.get(counterAnimationId);
}
if (!counterAnimationName.isEmpty()) {
if (counterAnimationName != null && !counterAnimationName.isEmpty()) {
return AnimationController.Instance.get(counterAnimationName, true);
}
@@ -247,8 +248,8 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.durationTicks = nbt.getInteger("durationTicks");
this.damageReduction = nbt.getFloat("damageReduction");
this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60;
this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f;
this.canCounter = nbt.getBoolean("canCounter");
this.counterWindow = nbt.getInteger("counterWindow");
try {
@@ -353,7 +354,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
}
public void setCounterAnimationName(String name) {
this.counterAnimationName = name;
this.counterAnimationName = name != null ? name : "";
}
@SideOnly(Side.CLIENT)
@@ -66,6 +66,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
private transient boolean airSlam = false; // True when slam initiated while already in the air
private transient double airSlamStartY = 0; // Start height for air-slam damage scaling
private transient boolean wasFlying = false; // Restore player flight after air slam
private transient double peakY = 0; // Maximum Y position during arc (for height scaling)
public AbilitySlam() {
this.typeId = "ability.cnpc.slam";
@@ -140,6 +141,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
hasRisen = false;
airTicks = 0;
startY = caster.posY;
peakY = caster.posY;
caster.fallDistance = 0;
if (isPlayerCaster(caster)) {
@@ -177,8 +179,20 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
* Works regardless of flying state — position is forced downward each tick.
*/
private void executePlayerSlam(EntityLivingBase caster) {
if (!caster.onGround) {
// Air slam: player is already airborne (flying, falling, jumping)
// Determine if this qualifies as an air slam (at least 3 blocks above ground)
boolean isAirborne = !caster.onGround;
boolean highEnoughForAirSlam = false;
if (isAirborne) {
double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ, 64);
highEnoughForAirSlam = (caster.posY - groundY) >= 3.0;
System.out.println("[Slam] AIR CHECK: posY=" + caster.posY + " groundY=" + groundY + " dist=" + (caster.posY - groundY) + " highEnough=" + highEnoughForAirSlam);
}
System.out.println("[Slam] EXECUTE: onGround=" + caster.onGround + " isAirborne=" + isAirborne + " highEnough=" + highEnoughForAirSlam + " -> " + (isAirborne && highEnoughForAirSlam ? "AIR SLAM" : "GROUND SLAM"));
if (isAirborne && highEnoughForAirSlam) {
// Air slam: player is already airborne (flying, falling, jumping) and high enough
airSlam = true;
airSlamStartY = caster.posY;
targetX = caster.posX;
@@ -216,7 +230,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f);
}
} else {
// Ground slam: normal ballistic arc
// Ground slam: normal ballistic arc (also used when airborne but not high enough)
airSlam = false;
airSlamStartY = 0;
wasFlying = false;
@@ -382,6 +396,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
caster.fallDistance = 0;
}
// Track peak height for damage scaling
if (caster.posY > peakY) {
peakY = caster.posY;
}
// Air slam: accelerate descent smoothly via velocity; landing uses normal collision.
if (airSlam && !isPreview() && !hasLanded) {
if (forceHorizontalControl) {
@@ -467,9 +486,6 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
}
restoreFlightIfNeeded(caster);
// Signal that the ability has completed its active phase
signalCompletion();
// Stop horizontal momentum only when movement is controlled by the ability.
if (!isPlayerCaster(caster) || isMovementLockedDuringActive()) {
caster.motionX = 0;
@@ -488,17 +504,29 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
// Play slam impact sound on landing
world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f);
// Scale damage based on fall distance for air slams
// Scale damage based on height for both air and ground slams
float effectiveDamage = damage;
float heightMultiplier = 1.0f;
if (airSlam) {
double fallStartY = airSlamStartY > 0 ? airSlamStartY : startY;
double fallDistance = fallStartY - caster.posY;
// Air slam: scale based on total fall distance
double fallDistance = airSlamStartY - caster.posY;
if (fallDistance < 0) fallDistance = 0;
// Scale linearly: full damage at leapHeight distance, minimum 25% for tiny falls
float heightFactor = (float) Math.min(1.0, fallDistance / Math.max(1.0, leapHeight));
effectiveDamage = damage * Math.max(0.25f, heightFactor);
heightMultiplier = Math.max(0.25f, heightFactor);
effectiveDamage = damage * heightMultiplier;
} else {
// Ground slam: scale based on arc height reached
double arcHeight = peakY - startY;
if (arcHeight > 0) {
float heightFactor = (float) Math.min(1.0, arcHeight / Math.max(1.0, leapHeight));
heightMultiplier = Math.max(0.25f, heightFactor);
effectiveDamage = damage * heightMultiplier;
}
}
// Set multiplier so extenders (e.g. DBC Addon) can apply height scaling to their own damage calc
setDamageMultiplier(heightMultiplier);
// Find all entities in radius
@SuppressWarnings("unchecked")
List<Entity> entities = world.getEntitiesWithinAABBExcludingEntity(
@@ -522,8 +550,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
}
}
setDamageMultiplier(1.0f); // Reset after damage loop
// Spawn particles
spawnSlamParticles(world, caster.posX, caster.posY, caster.posZ);
// Signal completion AFTER damage — signalCompletion triggers onComplete which resets state
signalCompletion();
}
/**
@@ -574,6 +607,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
airTicks = 0;
airSlam = false;
airSlamStartY = 0;
peakY = 0;
wasFlying = false;
}
@@ -589,6 +623,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
airTicks = 0;
airSlam = false;
airSlamStartY = 0;
peakY = 0;
wasFlying = false;
}
@@ -601,6 +636,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
airTicks = 0;
airSlam = false;
airSlamStartY = 0;
peakY = 0;
wasFlying = false;
}
@@ -613,6 +649,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
airTicks = 0;
airSlam = false;
airSlamStartY = 0;
peakY = 0;
wasFlying = false;
}
@@ -659,8 +696,8 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
targetZ = caster.posZ;
}
// Create telegraph at the appropriate position
double groundY = findGroundLevel(caster.worldObj, targetX, targetY, targetZ);
// Create telegraph at the appropriate position — always project to actual ground for landing zone
double groundY = findGroundLevel(caster.worldObj, targetX, targetY, targetZ, 64);
Telegraph telegraph = Telegraph.circle(radius);
telegraph.setDurationTicks(windUpTicks);
@@ -668,6 +705,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
telegraph.setWarningColor(activeColor);
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
telegraph.setGroundSearchRange(64); // Slam always projects to actual ground (landing zone)
TelegraphInstance instance = new TelegraphInstance(telegraph, targetX, groundY, targetZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
@@ -4,8 +4,10 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
import kamkeel.npcs.controllers.data.ability.enums.TargetFilter;
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.block.Block;
@@ -389,6 +391,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
for (Entity entity : entities) {
if (!(entity instanceof EntityLivingBase)) continue;
if (entity == caster) continue;
if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue;
EntityLivingBase living = (EntityLivingBase) entity;
double dist = Math.sqrt(Math.pow(living.posX - x, 2) + Math.pow(living.posZ - z, 2));
@@ -435,8 +438,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
} catch (Exception e) {
this.mode = TeleportMode.BLINK;
}
this.blinkCount = nbt.getInteger("blinkCount");
this.blinkDelayTicks = nbt.getInteger("blinkDelayTicks");
this.blinkCount = nbt.hasKey("blinkCount") ? nbt.getInteger("blinkCount") : 3;
this.blinkDelayTicks = nbt.hasKey("blinkDelayTicks") ? nbt.getInteger("blinkDelayTicks") : 10;
this.blinkRadius = nbt.getFloat("blinkRadius");
this.behindDistance = nbt.getFloat("behindDistance");
this.requireLineOfSight = nbt.getBoolean("requireLineOfSight");
@@ -153,6 +153,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
boolean anyStillPulling = false;
ticksSincePullDamage++;
boolean shouldDealPullDamage = damageOnPull && pullDamage > 0 && ticksSincePullDamage >= 10;
if (shouldDealPullDamage) {
ticksSincePullDamage = 0;
}
for (UUID uuid : new HashSet<>(getPulledEntities())) {
EntityLivingBase entity = findEntity(caster, caster.worldObj, uuid);
@@ -193,8 +197,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
entity.motionZ = nextZ;
entity.velocityChanged = true;
if (damageOnPull && pullDamage > 0 && ticksSincePullDamage >= 10) {
ticksSincePullDamage = 0;
if (shouldDealPullDamage) {
entity.hurtResistantTime = 0;
applyAbilityDamage(caster, entity, pullDamage * 0.5f, 0);
}
@@ -66,7 +66,7 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
caster.worldObj, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
beamWidth, headSize,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData,
resolved, combatData, homingData, lightningData, lifespanData,
lockMovement.locksActive());
}
@@ -66,7 +66,7 @@ public class AbilityDisc extends AbilityEnergyProjectile<EntityAbilityDisc> impl
caster.worldObj, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
discRadius, discThickness,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData,
resolved, combatData, homingData, lightningData, lifespanData,
boomerang, boomerangDelay);
}
@@ -9,7 +9,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import kamkeel.npcs.controllers.data.ability.data.ProjectileData;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
@@ -44,9 +43,6 @@ public abstract class AbilityEnergyProjectile<E extends EntityEnergyProjectile>
protected int projectileCount = 1;
protected int fireDelay = 0;
// Trajectory data
protected EnergyTrajectoryData trajectoryData;
// Shared combat/movement data
protected final EnergyCombatData combatData;
protected final EnergyHomingData homingData;
@@ -74,7 +70,6 @@ public abstract class AbilityEnergyProjectile<E extends EntityEnergyProjectile>
this.combatData = combatData;
this.homingData = homingData;
this.lifespanData = lifespanData;
this.trajectoryData = new EnergyTrajectoryData();
this.burstOverlap = true;
initProjectiles(1);
}
@@ -538,7 +533,8 @@ public abstract class AbilityEnergyProjectile<E extends EntityEnergyProjectile>
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw);
double groundY = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ);
TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, groundY, target.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(target.getEntityId());
@@ -89,7 +89,8 @@ public class AbilityLaserShot extends AbilityEnergyProjectile<EntityAbilityLaser
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, caster.posY, caster.posZ, caster.rotationYaw);
double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ);
TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, groundY, caster.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(caster.getEntityId());
if (target != null) {
@@ -117,7 +118,7 @@ public class AbilityLaserShot extends AbilityEnergyProjectile<EntityAbilityLaser
caster.worldObj, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
laserWidth,
resolved, combatData, lightningData, lifespanData, trajectoryData,
resolved, combatData, lightningData, lifespanData,
expansionSpeed, lingerTicks);
return laser;
}
@@ -59,7 +59,7 @@ public class AbilityOrb extends AbilityEnergyProjectile<EntityAbilityOrb> implem
return new EntityAbilityOrb(
caster.worldObj, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData);
resolved, combatData, homingData, lightningData, lifespanData);
}
@Override
@@ -61,7 +61,7 @@ public class AbilitySlicer extends AbilityEnergyProjectile<EntityEnergySlicer> {
caster.worldObj, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
sliceWidth, sliceThickness,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData
resolved, combatData, homingData, lightningData, lifespanData
);
}
@@ -157,8 +157,9 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper {
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
// Position at caster, not target
TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, caster.posY, caster.posZ, caster.rotationYaw);
// Position at caster ground level, not target
double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ);
TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, groundY, caster.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(caster.getEntityId()); // Follow caster
@@ -27,7 +27,10 @@ public class AbilityTargetHelper {
* </ul>
*/
public static boolean isAlly(EntityLivingBase caster, Entity target) {
if (caster == null || target == null) return false;
if (target == caster) return true;
// Ally resolution relies on server-owned player/party/faction state.
if (caster.worldObj == null || caster.worldObj.isRemote) return false;
// NPC target checks
if (target instanceof EntityNPCInterface) {
@@ -44,7 +47,9 @@ public class AbilityTargetHelper {
// Player caster: friendly faction = ally
if (caster instanceof EntityPlayer) {
if (targetNpc.faction.isFriendlyToPlayer((EntityPlayer) caster)) return true;
EntityPlayer casterPlayer = (EntityPlayer) caster;
if (PlayerData.get(casterPlayer) == null) return false;
if (targetNpc.faction.isFriendlyToPlayer(casterPlayer)) return true;
}
return false;
@@ -54,7 +59,9 @@ public class AbilityTargetHelper {
if (target instanceof EntityPlayer && caster instanceof EntityNPCInterface) {
// NPC caster vs Player target: faction friendly to player = ally
EntityNPCInterface casterNpc = (EntityNPCInterface) caster;
return casterNpc.faction.isFriendlyToPlayer((EntityPlayer) target);
EntityPlayer targetPlayer = (EntityPlayer) target;
if (PlayerData.get(targetPlayer) == null) return false;
return casterNpc.faction.isFriendlyToPlayer(targetPlayer);
}
if (target instanceof EntityPlayer && caster instanceof EntityPlayer) {
@@ -63,6 +70,7 @@ public class AbilityTargetHelper {
EntityPlayer targetPlayer = (EntityPlayer) target;
PlayerData casterData = PlayerData.get(casterPlayer);
PlayerData targetData = PlayerData.get(targetPlayer);
if (casterData == null || targetData == null) return false;
if (casterData.partyUUID != null && casterData.partyUUID.equals(targetData.partyUUID)) {
Party party = PartyController.Instance().getParty(casterData.partyUUID);
if (party != null && !party.friendlyFire()) return true;
@@ -86,6 +94,8 @@ public class AbilityTargetHelper {
*/
public static boolean shouldAffect(EntityLivingBase caster, Entity target,
TargetFilter filter, boolean includeSelf) {
if (caster == null || target == null || filter == null) return false;
if (caster.worldObj == null || caster.worldObj.isRemote) return false;
if (target == caster) return includeSelf;
if (!(target instanceof EntityLivingBase)) return false;
if (!target.isEntityAlive()) return false;
@@ -28,6 +28,7 @@ public class Telegraph {
private int warningStartTick = 10;
private boolean animated = true;
private float heightOffset = 0.1f;
private int groundSearchRange = 3;
// Positioning
private boolean atTarget = true;
@@ -57,6 +58,7 @@ public class Telegraph {
this.warningStartTick = other.warningStartTick;
this.animated = other.animated;
this.heightOffset = other.heightOffset;
this.groundSearchRange = other.groundSearchRange;
this.atTarget = other.atTarget;
this.followsTarget = other.followsTarget;
this.followsCaster = other.followsCaster;
@@ -82,6 +84,7 @@ public class Telegraph {
nbt.setInteger("warningStartTick", warningStartTick);
nbt.setBoolean("animated", animated);
nbt.setFloat("heightOffset", heightOffset);
nbt.setInteger("groundSearchRange", groundSearchRange);
nbt.setBoolean("atTarget", atTarget);
nbt.setBoolean("followsTarget", followsTarget);
nbt.setBoolean("followsCaster", followsCaster);
@@ -109,6 +112,9 @@ public class Telegraph {
this.warningStartTick = nbt.getInteger("warningStartTick");
this.animated = nbt.getBoolean("animated");
this.heightOffset = nbt.getFloat("heightOffset");
if (nbt.hasKey("groundSearchRange")) {
this.groundSearchRange = nbt.getInteger("groundSearchRange");
}
this.atTarget = nbt.getBoolean("atTarget");
this.followsTarget = nbt.getBoolean("followsTarget");
this.followsCaster = nbt.getBoolean("followsCaster");
@@ -264,6 +270,14 @@ public class Telegraph {
this.heightOffset = heightOffset;
}
public int getGroundSearchRange() {
return groundSearchRange;
}
public void setGroundSearchRange(int groundSearchRange) {
this.groundSearchRange = groundSearchRange;
}
public boolean isAtTarget() {
return atTarget;
}
@@ -96,7 +96,8 @@ public class TelegraphInstance {
this.x = entity.posX;
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);
int searchRange = (telegraph != null) ? telegraph.getGroundSearchRange() : 3;
this.y = Ability.findGroundLevel(world, entity.posX, entity.posY, entity.posZ, searchRange);
// Track followed entity's yaw for directional telegraphs (player casters)
if (trackFollowedEntityYaw && targetEntityId < 0) {
@@ -4,10 +4,12 @@ import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper;
import kamkeel.npcs.controllers.data.ability.data.energy.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.CustomNpcs;
import noppes.npcs.EventHooks;
import noppes.npcs.entity.EntityNPCInterface;
@@ -439,16 +441,56 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility {
return this.dataWatcher.getWatchableObjectFloat(DW_HEALTH_PERCENT);
}
/**
* Client prediction only runs for the local player.
*/
protected EntityPlayer getClientPredictionPlayer() {
return worldObj != null && worldObj.isRemote ? CustomNpcs.proxy.getPlayer() : null;
}
/**
* Shared target filter used by Dome/Panel physics loops.
*/
protected boolean shouldSkipBarrierPhysicsTarget(EntityLivingBase entity, EntityPlayer clientPredictionPlayer) {
if (entity == null || !entity.isEntityAlive()) return true;
if (entity.getEntityId() == ownerEntityId) return true;
if (worldObj.isRemote && (clientPredictionPlayer == null || entity != clientPredictionPlayer)) return true;
return isAllyOfOwner(entity);
}
/**
* Check if an entity is an ally of this barrier's owner.
* Allies are not affected by barrier physics.
* Server uses full relationship logic; client uses a lightweight safe approximation.
*/
protected boolean isAllyOfOwner(EntityLivingBase entity) {
Entity owner = getOwnerEntity();
if (owner == null || !(owner instanceof EntityLivingBase)) return false;
if (worldObj != null && worldObj.isRemote) {
return isClientPredictedAlly((EntityLivingBase) owner, entity);
}
return AbilityTargetHelper.isAlly((EntityLivingBase) owner, entity);
}
/**
* Client-safe ally approximation used only for movement prediction.
* Avoids PlayerData/Party/Faction point lookups that are server-owned.
*/
protected boolean isClientPredictedAlly(EntityLivingBase owner, EntityLivingBase target) {
if (owner == null || target == null) return false;
if (owner == target) return true;
if (target instanceof EntityNPCInterface) {
EntityNPCInterface targetNpc = (EntityNPCInterface) target;
if (targetNpc.faction.isPassive) return true;
if (owner instanceof EntityNPCInterface) {
EntityNPCInterface ownerNpc = (EntityNPCInterface) owner;
return ownerNpc.faction.id == targetNpc.faction.id;
}
}
return false;
}
// ==================== CONTAINMENT & ABSORBING ====================
/**
@@ -8,7 +8,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
@@ -139,12 +138,12 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
float beamWidth, float headSize,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory,
EnergyLifespanData lifespan,
boolean anchoredMode) {
super(world);
// Initialize base properties via parent
initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan, trajectory);
initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan);
// Beam-specific properties from homing data
@@ -6,7 +6,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
@@ -39,6 +38,9 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
private int returnOwnerNullTicks = 0;
private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward)
// Cached travel direction for smooth rendering when motion is near zero
private float lastTravelYaw = 0.0f;
// Charging state (disc-specific target sizes)
private float targetDiscRadius = 1.0f; // Full radius to grow to during charging
private float targetDiscThickness = 0.2f; // Full thickness to grow to during charging
@@ -55,12 +57,12 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
float discRadius, float discThickness,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory,
EnergyLifespanData lifespan,
boolean boomerang, int boomerangDelay) {
super(world);
// Initialize base properties
initProjectile(owner, target, x, y, z, discRadius, display, combat, lightning, lifespan, trajectory);
initProjectile(owner, target, x, y, z, 1.0f, display, combat, lightning, lifespan);
this.homingData = homing;
@@ -316,7 +318,7 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
float progress = getChargeProgress();
this.discRadius = targetDiscRadius * progress;
this.discThickness = targetDiscThickness * progress;
this.size = this.discRadius; // Base size for interpolation
this.size = 1.0f; // Size acts as a scaling factor; discRadius handles actual dimensions
Entity owner = getOwnerEntity();
if (owner instanceof EntityLivingBase) {
@@ -382,14 +384,15 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
if (isCharging()) {
Entity owner = previewMode ? previewOwner : getOwnerEntity();
if (owner != null) {
return owner.rotationYaw;
lastTravelYaw = owner.rotationYaw;
return lastTravelYaw;
}
}
double speed = Math.sqrt(motionX * motionX + motionZ * motionZ);
if (speed > 0.001) {
return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI);
lastTravelYaw = (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI);
}
return 0.0f;
return lastTravelYaw;
}
// ==================== NBT ====================
@@ -406,6 +409,12 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
readChargingNBT(nbt);
this.targetDiscRadius = nbt.hasKey("TargetDiscRadius") ? nbt.getFloat("TargetDiscRadius") : this.discRadius;
this.targetDiscThickness = nbt.hasKey("TargetDiscThickness") ? nbt.getFloat("TargetDiscThickness") : this.discThickness;
// Normalize size to 1.0 (scaling factor) — discRadius handles actual dimensions.
// Old saves may have size = discRadius baked in from the quadratic scaling bug.
this.size = 1.0f;
this.renderCurrentSize = 1.0f;
this.prevRenderSize = 1.0f;
}
@Override
@@ -258,18 +258,11 @@ public class EntityAbilityDome extends EntityAbilityBarrier {
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;
EntityPlayer localPlayer = getClientPredictionPlayer();
List<EntityLivingBase> entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox);
for (EntityLivingBase ent : entities) {
if (ent.getEntityId() == ownerEntityId) continue;
// Client-side: only process local player for solid prediction
// Must be checked before isAllyOfOwner which uses server-only PlayerData
if (worldObj.isRemote && (localPlayer == null || ent != localPlayer)) continue;
if (isAllyOfOwner(ent)) continue;
if (shouldSkipBarrierPhysicsTarget(ent, localPlayer)) continue;
// Current position relative to dome center
double dx = ent.posX - posX;
@@ -5,7 +5,8 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
@@ -58,11 +59,11 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
float laserWidth,
EnergyDisplayData display, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan,
EnergyTrajectoryData trajectory, float expansionSpeed, int lingerTicks) {
float expansionSpeed, int lingerTicks) {
super(world);
// Initialize base properties (laser doesn't rotate)
initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan, trajectory);
initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan);
this.displayData.rotationSpeed = 0.0f;
// Laser-specific properties
@@ -88,12 +89,16 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
this.dirX = look.xCoord;
this.dirY = look.yCoord;
this.dirZ = look.zCoord;
} else {
} else if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
this.dirX = -Math.sin(yaw) * Math.cos(pitch);
this.dirY = -Math.sin(pitch);
this.dirZ = Math.cos(yaw) * Math.cos(pitch);
} else {
this.dirX = 1.0;
this.dirY = 0.0;
this.dirZ = 0.0;
}
}
@@ -103,6 +108,13 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
this.endZ = z;
}
@Override
@SideOnly(Side.CLIENT)
public boolean isInRangeToRenderDist(double distance) {
double range = Math.max(128.0D, currentLength * 2.0D + 64.0D);
return distance < range * range;
}
@Override
protected void updateRotation() {
// Laser doesn't rotate
@@ -179,7 +191,13 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
*/
private void updateLaserOriginAndDirection() {
Entity owner = getOwnerEntity();
if (owner == null || !(owner instanceof EntityLivingBase)) return;
if (owner == null || !(owner instanceof EntityLivingBase)) {
// On client, fall back to entity tracker interpolation when owner not loaded
if (worldObj != null && worldObj.isRemote) {
handleClientInterpolation();
}
return;
}
EntityLivingBase livingOwner = (EntityLivingBase) owner;
// Use owner look vector (head/eye aim) for direction updates so hit logic matches visuals.
@@ -6,7 +6,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
@@ -33,11 +32,11 @@ public class EntityAbilityOrb extends EntityEnergyProjectile {
double x, double y, double z, float orbSize,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory) {
EnergyLifespanData lifespan) {
super(world);
// Initialize base properties
initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan, trajectory);
initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan);
this.homingData = homing;
@@ -114,17 +113,13 @@ public class EntityAbilityOrb extends EntityEnergyProjectile {
}
private void updateMovement() {
if (!isTrajectoryConcluded()) {
updateTrajectory();
} else {
if (ticksExisted > HOMING_STARTUP_TICKS) {
int homingTicks = ticksExisted - HOMING_STARTUP_TICKS;
if (homingTicks >= HOMING_RAMP_TICKS) {
updateHoming();
} else {
float ramp = homingTicks / (float) HOMING_RAMP_TICKS;
updateHomingWithRamp(ramp);
}
if (ticksExisted > HOMING_STARTUP_TICKS) {
int homingTicks = ticksExisted - HOMING_STARTUP_TICKS;
if (homingTicks >= HOMING_RAMP_TICKS) {
updateHoming();
} else {
float ramp = homingTicks / (float) HOMING_RAMP_TICKS;
updateHomingWithRamp(ramp);
}
}
}
@@ -137,24 +132,6 @@ public class EntityAbilityOrb extends EntityEnergyProjectile {
homingData.homingStrength = originalStrength;
}
private void updateTrajectory() {
if (isTrajectoryConcluded()) return;
// i really fucking hate math
}
private boolean isTrajectoryConcluded() {
if (trajectoryData.isEmpty()) return true;
for (int i = 0; i < trajectoryData.size(); i++) {
if (!trajectoryData.getPath(i).isConcluded()) {
return false;
}
}
return true;
}
private void checkBlockCollision() {
handleBlockImpact(rayTraceBlocks(posX, posY, posZ, posX + motionX, posY + motionY, posZ + motionZ), true);
}
@@ -13,7 +13,6 @@ 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;
@@ -203,10 +202,8 @@ public class EntityAbilityPanel extends EntityAbilityBarrier {
Entity owner = getOwnerEntity();
for (EntityLivingBase target : entities) {
if (target == owner) continue;
if (owner instanceof EntityNPCInterface && target instanceof EntityNPCInterface) {
if (((EntityNPCInterface) owner).faction.id == ((EntityNPCInterface) target).faction.id) continue;
}
if (target.getEntityId() == ownerEntityId) continue;
if (isAllyOfOwner(target)) continue;
// Apply damage
if (panelData.launchDamage > 0) {
@@ -411,8 +408,7 @@ public class EntityAbilityPanel extends EntityAbilityBarrier {
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;
EntityPlayer localPlayer = getClientPredictionPlayer();
List<EntityLivingBase> entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox);
float yawRad = (float) Math.toRadians(panelYaw);
@@ -420,13 +416,7 @@ public class EntityAbilityPanel extends EntityAbilityBarrier {
float normalZ = (float) Math.cos(yawRad);
for (EntityLivingBase ent : entities) {
if (ent.getEntityId() == ownerEntityId) continue;
// Client-side: only process local player for solid prediction
// Must be checked before isAllyOfOwner which uses server-only PlayerData
if (worldObj.isRemote && (localPlayer == null || ent != localPlayer)) continue;
if (isAllyOfOwner(ent)) continue;
if (shouldSkipBarrierPhysicsTarget(ent, localPlayer)) continue;
// Current position relative to panel center
double dx = ent.posX - posX;
@@ -159,10 +159,9 @@ public class EntityAbilitySweeper extends EntityEnergyAbility {
// Update rotation
currentAngle += sweepSpeed;
if (currentAngle >= 360) {
while (currentAngle >= 360) {
currentAngle -= 360;
completedRotations++;
// Rotation completed
}
// Server handles damage
@@ -12,7 +12,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import kamkeel.npcs.network.packets.data.energyexplosion.EnergyExplosionSpawnPacket;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.block.Block;
@@ -114,8 +113,6 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
// ==================== HOMING PROPERTIES ====================
protected EnergyHomingData homingData = new EnergyHomingData();
// ==================== TRAJECTORY PROPERTIES ====================
protected EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
protected Map<Integer, Integer> pathDelays;
// ==================== TRACKING ====================
@@ -174,8 +171,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
protected void initProjectile(EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z, float size,
EnergyDisplayData display, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan,
EnergyTrajectoryData trajectory) {
EnergyLightningData lightning, EnergyLifespanData lifespan) {
this.setPosition(x, y, z);
this.startX = x;
this.startY = y;
@@ -191,7 +187,6 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
this.combatData = combat;
this.lifespanData = lifespan; // deathWorldTime will be set on first tick when world is available
this.lightningData = lightning;
this.trajectoryData = trajectory;
syncProjectileColorWatchers();
// Initialize render size
@@ -801,19 +796,21 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
/**
* Handle client-side position interpolation.
* Only moves position during active interpolation (interpSteps > 0).
* Does NOT predict/drift between server updates — the motion values are
* derived from correction deltas, not actual entity velocity, so applying
* them between updates causes entities to fly off in wrong directions.
* This matches vanilla Minecraft behavior for non-player entities.
*/
protected void handleClientInterpolation() {
if (this.interpSteps > 0) {
// For very slow / stationary projectiles, snap directly to avoid jitter
double dx = this.interpTargetX - this.posX;
double dy = this.interpTargetY - this.posY;
double dz = this.interpTargetZ - this.posZ;
double distSq = dx * dx + dy * dy + dz * dz;
if (distSq < 0.04) {
if (distSq < 0.0001) {
this.setPosition(this.interpTargetX, this.interpTargetY, this.interpTargetZ);
this.motionX = this.interpTargetMotionX;
this.motionY = this.interpTargetMotionY;
this.motionZ = this.interpTargetMotionZ;
this.interpSteps = 0;
return;
}
@@ -828,16 +825,6 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
this.setPosition(newX, newY, newZ);
this.interpSteps--;
} else {
// Skip motion application for nearly-stationary projectiles to prevent drift
double speedSq = this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ;
if (speedSq < 0.0001) {
return;
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
this.setPosition(this.posX, this.posY, this.posZ);
}
}
@@ -1542,9 +1529,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
protected void setChargeOrigin(Vec3 pos) {
if (pos == null) return;
this.setPosition(pos.xCoord, pos.yCoord, pos.zCoord);
this.prevPosX = pos.xCoord;
this.prevPosY = pos.yCoord;
this.prevPosZ = pos.zCoord;
syncPositionState(pos.xCoord, pos.yCoord, pos.zCoord, true);
this.startX = pos.xCoord;
this.startY = pos.yCoord;
this.startZ = pos.zCoord;
@@ -2213,7 +2198,6 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
combatData.readNBT(nbt);
homingData.readNBT(nbt);
lifespanData.readNBT(nbt);
trajectoryData.readNBT(nbt);
syncProjectileColorWatchers();
}
@@ -2248,7 +2232,6 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
combatData.writeNBT(nbt);
homingData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
trajectoryData.writeNBT(nbt);
}
/**
@@ -6,7 +6,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
@@ -24,6 +23,10 @@ public class EntityEnergySlicer extends EntityEnergyProjectile {
private float sliceWidth = 3.0f;
private float sliceThickness = 0.15f;
// Cached travel direction for smooth rendering when motion is near zero
private float lastTravelYaw = 0.0f;
private float lastTravelPitch = 0.0f;
public EntityEnergySlicer(World world) {
super(world);
}
@@ -36,10 +39,10 @@ public class EntityEnergySlicer extends EntityEnergyProjectile {
float sliceWidth, float sliceThickness,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory) {
EnergyLifespanData lifespan) {
super(world);
initProjectile(owner, target, x, y, z, sliceWidth, display, combat, lightning, lifespan, trajectory);
initProjectile(owner, target, x, y, z, sliceWidth, display, combat, lightning, lifespan);
this.homingData = homing;
this.sliceWidth = sliceWidth;
this.sliceThickness = sliceThickness;
@@ -166,13 +169,16 @@ public class EntityEnergySlicer extends EntityEnergyProjectile {
public float getTravelYaw() {
if (isCharging()) {
Entity owner = previewMode ? previewOwner : getOwnerEntity();
if (owner != null) return owner.rotationYaw;
if (owner != null) {
lastTravelYaw = owner.rotationYaw;
return lastTravelYaw;
}
}
double speed = Math.sqrt(motionX * motionX + motionZ * motionZ);
if (speed > 0.001) {
return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI);
lastTravelYaw = (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI);
}
return 0.0f;
return lastTravelYaw;
}
/**
@@ -181,9 +187,9 @@ public class EntityEnergySlicer extends EntityEnergyProjectile {
public float getTravelPitch() {
double horizSpeed = Math.sqrt(motionX * motionX + motionZ * motionZ);
if (horizSpeed > 0.001 || Math.abs(motionY) > 0.001) {
return (float) (-Math.atan2(motionY, horizSpeed) * 180.0 / Math.PI);
lastTravelPitch = (float) (-Math.atan2(motionY, horizSpeed) * 180.0 / Math.PI);
}
return 0.0f;
return lastTravelPitch;
}
// ==================== GETTERS ====================
@@ -55,5 +55,6 @@ public final class AbilityHotbarSelectPacket extends AbstractPacket {
data.abilityData.setSelectedIndex(index);
}
}
data.save();
}
}
@@ -52,6 +52,7 @@ public final class AbilityTogglePacket extends AbstractPacket {
PlayerData playerData = PlayerData.get(player);
if (playerData == null || playerData.abilityData == null) return;
if (!playerData.abilityData.hasUnlockedAbility(key)) return;
int newState = playerData.abilityData.toggleAbility(key);
@@ -6,6 +6,8 @@ import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -39,6 +41,8 @@ public class AbilitiesGetAllPacket extends AbstractPacket {
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP))
return;
if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player))
return;
NoppesUtilServer.sendAbilityTypesInfo((EntityPlayerMP) player);
}
@@ -64,6 +64,7 @@ public final class AbilitiesNpcSavePacket extends AbstractPacket {
return;
NBTTagCompound compound = ByteBufUtils.readNBT(in);
if (compound == null) return;
npc.abilities.readFromNBT(compound);
}
}
@@ -35,6 +35,13 @@ import java.util.Set;
*/
public abstract class AbstractDataAbilities {
/**
* Safety timeout (ticks) for abilities stuck in ACTIVE phase.
* If an ability stays in ACTIVE for longer than this without calling signalCompletion(),
* it is force-completed to prevent permanent stuck state. 30 seconds at 20 TPS.
*/
protected static final int MAX_ACTIVE_PHASE_TICKS = 600;
// ═══════════════════════════════════════════════════════════════════
// SHARED RUNTIME STATE (not saved to NBT)
// ═══════════════════════════════════════════════════════════════════
@@ -427,7 +434,7 @@ public abstract class AbstractDataAbilities {
EntityLivingBase entity = getEntity();
List<String> toRemove = null;
for (Map.Entry<String, AbilityToggleEntry> mapEntry : activeToggles.entrySet()) {
for (Map.Entry<String, AbilityToggleEntry> mapEntry : new ArrayList<>(activeToggles.entrySet())) {
AbilityToggleEntry entry = mapEntry.getValue();
entry.incrementTick();
@@ -864,6 +871,16 @@ public abstract class AbstractDataAbilities {
if (positionLocked) releaseLockedPosition();
onBurstDelayReleaseLocks();
}
// Safety timeout: force-complete if stuck in ACTIVE too long.
// Individual ability types should have their own timeouts well below this;
// this is a last-resort failsafe to prevent permanent stuck state.
if (currentAbility != null && currentAbility.getPhase() == AbilityPhase.ACTIVE
&& currentAbility.getCurrentTick() > MAX_ACTIVE_PHASE_TICKS) {
currentAbility.cancel();
handleAbilityCompletion(target);
return;
}
break;
case BURST_DELAY:
+1 -1
View File
@@ -1109,7 +1109,7 @@ public class DataAbilities extends AbstractDataAbilities {
}
public void readFromNBT(NBTTagCompound compound) {
enabled = compound.getBoolean("AbilitiesEnabled");
enabled = compound.hasKey("AbilitiesEnabled") ? compound.getBoolean("AbilitiesEnabled") : true;
minCooldown = compound.getInteger("AbilityMinCooldown");
maxCooldown = compound.getInteger("AbilityMaxCooldown");
@@ -10,6 +10,7 @@ import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.util.AttributeAttackUtil;
import net.minecraft.entity.Entity;
@@ -142,8 +143,16 @@ public class ScriptPlayerEventHandler {
playerData.timers.update();
}
if (player.ticksExisted % 10 == 0)
SyncController.syncEffects((EntityPlayerMP) player);
if (player.ticksExisted % 10 == 0) {
EntityPlayerMP mp = (EntityPlayerMP) player;
SyncController.syncEffects(mp);
SyncController.syncAbilityCooldowns(mp);
if (playerData.abilityData.needsSync) {
PlayerAbilitySyncPacket.sendToPlayer(mp);
playerData.abilityData.needsSync = false;
}
playerData.abilityData.ensureLockStateClear();
}
if (player.ticksExisted % 10 == 0)
CustomEffectController.Instance.runEffects(player);
@@ -50,6 +50,9 @@ public class ServerTickHandler {
SyncController.syncEffects(player);
ScriptController.Instance.syncClientScripts(player);
// Sync clean ability state to the new client (after beginLogin initializes sync state)
SyncController.syncAbilities(player);
// Send auction notifications on login
if (AuctionController.Instance != null) {
AuctionController.Instance.onPlayerLogin(player);
@@ -212,7 +212,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
if (allAllowPlayer && allAllowNpc) return UserType.BOTH;
if (allAllowPlayer) return UserType.PLAYER_ONLY;
if (allAllowNpc) return UserType.NPC_ONLY;
return UserType.NPC_ONLY;
return UserType.NONE;
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -750,7 +750,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
} else {
entries.add(ChainedAbilityEntry.reference(consumed.getReferenceId(), 0));
}
consumedSlotIndices.add(slotIndex);
if (!consumedSlotIndices.contains(slotIndex)) {
consumedSlotIndices.add(slotIndex);
}
}
}
}
@@ -119,8 +119,7 @@ public class AbilityHotbarSlotRenderer extends Gui {
if (iconNaturalSize <= 0) iconNaturalSize = 16f;
float iconScale = targetSize / iconNaturalSize;
GL11.glScalef(iconScale, iconScale, 1);
GL11.glColor4f(1, 1, 1, slotAlpha);
icon.draw(getToggleState());
icon.draw(getToggleState(), slotAlpha);
GL11.glColor4f(1, 1, 1, 1);
GL11.glPopMatrix();
}
@@ -60,6 +60,10 @@ public class AbilityIcon extends Gui {
}
public void draw(int state) {
draw(state, 1.0f);
}
public void draw(int state, float alpha) {
TextureManager renderEngine = Minecraft.getMinecraft().renderEngine;
ImageData imageData = null;
@@ -68,7 +72,7 @@ public class AbilityIcon extends Gui {
}
GL11.glPushMatrix();
GL11.glColor4f(1, 1, 1, 1);
GL11.glColor4f(1, 1, 1, alpha);
Tessellator t;
@@ -126,7 +126,7 @@ public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiLis
private void openBidSubGui() {
if (listing == null) return;
long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement());
setSubGui(new SubGuiAuctionBid(listing.id, minBid, playerBalance));
setSubGui(new SubGuiAuctionBid(listing.id, minBid, listing.buyoutPrice, playerBalance));
}
private void openBuyNowSubGui() {
@@ -23,14 +23,16 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
private final String listingId;
private final long minimumBid;
private final long buyoutPrice;
private final long playerBalance;
private long bidAmount;
private boolean successful = false;
private String errorMessage = null;
public SubGuiAuctionBid(String listingId, long minimumBid, long playerBalance) {
public SubGuiAuctionBid(String listingId, long minimumBid, long buyoutPrice, long playerBalance) {
this.listingId = listingId;
this.minimumBid = minimumBid;
this.buyoutPrice = buyoutPrice;
this.playerBalance = playerBalance;
this.bidAmount = minimumBid;
@@ -129,6 +131,12 @@ public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListe
return;
}
if (buyoutPrice > 0 && bidAmount >= buyoutPrice) {
errorMessage = StatCollector.translateToLocal("auction.error.bidExceedsBuyout");
updateErrorLabel();
return;
}
// Send bid packet
AuctionActionPacket.placeBid(listingId, bidAmount);
successful = true;
@@ -15,16 +15,19 @@ import noppes.npcs.controllers.data.AbilityHotbarData;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* SubGui for selecting an ability to assign to a hotbar slot.
* Uses ability keys internally to avoid duplicate display name collisions.
*/
public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
private HashMap<String, String> displayToKey = new HashMap<>();
private LinkedHashMap<String, String> keyToDisplay = new LinkedHashMap<>();
private List<String> scrollKeys = new ArrayList<>();
private GuiCustomScroll scrollAbilities;
private String selected = null;
private int selectedIndex = -1;
private String search = "";
public boolean confirmed = false;
@@ -36,7 +39,6 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
this.slotIndex = slotIndex;
this.closeOnEsc = true;
this.drawDefaultBackground = true;
guiLeft -= 10;
xSize = 256 + 10;
this.setBackground("menubg.png");
}
@@ -44,7 +46,7 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
@Override
public void initGui() {
super.initGui();
guiTop += 10;
guiTop = (this.height - ySize) / 2 + 10;
if (scrollAbilities == null) {
scrollAbilities = new GuiCustomScroll(this, 0, 0);
@@ -66,7 +68,7 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
}
private void loadAbilities() {
displayToKey.clear();
keyToDisplay.clear();
PlayerData playerData = ClientCacheHandler.playerData;
if (playerData == null || playerData.abilityData == null) {
return;
@@ -85,7 +87,7 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
AbilityController.Instance.resolveAbility(key) : null;
displayName = ability != null ? ability.getDisplayName() : key;
}
displayToKey.put(displayName, key);
keyToDisplay.put(key, displayName);
}
}
@@ -93,9 +95,9 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
public void actionPerformed(GuiButton button) {
int id = button.id;
if (id == 0 && selected != null) {
if (id == 0 && selectedIndex >= 0 && selectedIndex < scrollKeys.size()) {
confirmed = true;
selectedAbilityKey = displayToKey.get(selected);
selectedAbilityKey = scrollKeys.get(selectedIndex);
this.close();
}
if (id == 1) {
@@ -109,15 +111,16 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
@Override
public void customScrollClicked(int i, int i1, int i2, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll == scrollAbilities)
selected = scrollAbilities.getSelected();
if (guiCustomScroll == scrollAbilities) {
selectedIndex = scrollAbilities.selected;
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll == scrollAbilities && selection != null) {
if (guiCustomScroll == scrollAbilities && selectedIndex >= 0 && selectedIndex < scrollKeys.size()) {
confirmed = true;
selectedAbilityKey = displayToKey.get(selection);
selectedAbilityKey = scrollKeys.get(selectedIndex);
this.close();
}
}
@@ -135,21 +138,23 @@ public class SubGuiSelectAbilityForSlot extends SubGuiInterface implements ICust
return;
search = getTextField(55).getText().toLowerCase();
scrollAbilities.resetScroll();
selectedIndex = -1;
scrollAbilities.setList(getSearchList());
}
}
}
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(displayToKey.keySet());
}
scrollKeys.clear();
List<String> displayNames = new ArrayList<>();
List<String> list = new ArrayList<>();
for (String name : displayToKey.keySet()) {
if (name.toLowerCase().contains(search))
list.add(name);
for (Map.Entry<String, String> entry : keyToDisplay.entrySet()) {
String displayName = entry.getValue();
if (search.isEmpty() || displayName.toLowerCase().contains(search)) {
scrollKeys.add(entry.getKey());
displayNames.add(displayName);
}
}
return list;
return displayNames;
}
}
@@ -585,6 +585,11 @@ public class AuctionController implements IAuctionHandler {
return "Bid must be at least " + minBid + " " + ConfigMarket.CurrencyName + ".";
}
// Prevent bidding at or above buyout price
if (listing.hasBuyout() && bidAmount >= listing.buyoutPrice) {
return "Your bid meets or exceeds the buyout price. Use Buy Now instead.";
}
// Check currency
PlayerData playerData = PlayerData.get(player);
if (playerData == null) {
@@ -1,6 +1,7 @@
package noppes.npcs.controllers.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
@@ -90,6 +91,14 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
*/
private transient byte lastSyncedFlags = 0;
/**
* Dirty flag: set when ability data changes (unlock/lock/select/toggle).
* Checked by the periodic 10-tick sync handler, which sends an ability
* data packet and clears the flag. Avoids scattering sync calls across
* every mutation method.
*/
public transient boolean needsSync = false;
/**
* World time when the last ability was activated (for double-press cancel detection).
*/
@@ -251,7 +260,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
cooldownEndTime = endTime;
globalCooldownDuration = duration;
}
syncCooldownToClient();
}
@Override
@@ -259,7 +267,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
int duration = chain.getCooldownTicks();
cooldownEndTime = getWorldTime() + duration;
globalCooldownDuration = duration;
syncCooldownToClient();
}
@Override
@@ -278,6 +285,13 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
@Override
protected void onInterruptComplete() {
// Player clears state immediately (unlike NPC which ticks through DAZED)
// Roll cooldown before clearing state — NPC rolls during handleAbilityCompletion
// after ticking through DAZED, but the player skips DAZED entirely.
if (!interruptCooldownRolled && currentAbility != null) {
rollCooldown(currentAbility);
}
interruptCooldownRolled = false;
// Stop the dazed animation that was started in interruptCurrentAbility()
stopAbilityAnimation();
currentAbility = null;
@@ -450,6 +464,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
playAbilityAnimation(ability.getWindUpAnimation());
}
// Immediate sync on ability use
syncToClient();
return true;
}
@@ -458,31 +474,30 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
// ═══════════════════════════════════════════════════════════════════
/**
* Sync ability data to the client.
* Called when abilities change (unlock/lock/select) and on login.
* Full sync of all ability state to the client.
* Delegates to {@link SyncController#syncAbilities(EntityPlayerMP)}.
*/
public void syncToClient() {
EntityPlayer player = playerData.player;
if (player instanceof EntityPlayerMP) {
PlayerAbilitySyncPacket.sendToPlayer((EntityPlayerMP) player);
syncCooldownToClient();
SyncController.syncAbilities((EntityPlayerMP) player);
}
}
/**
* Sync cooldown state (global + per-ability) to the client.
* Sent as a lightweight packet separate from full ability sync.
* Lightweight sync of cooldown state only to the client.
* Delegates to {@link SyncController#syncAbilityCooldowns(EntityPlayerMP)}.
*/
public void syncCooldownToClient() {
EntityPlayer player = playerData.player;
if (player instanceof EntityPlayerMP) {
AbilityCooldownSyncPacket.sendToPlayer((EntityPlayerMP) player);
SyncController.syncAbilityCooldowns((EntityPlayerMP) player);
}
}
@Override
protected void onToggleStateChanged(String key, boolean active, int state) {
syncToClient();
needsSync = true;
}
@Override
@@ -519,20 +534,20 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
public void setSelectedIndex(int index) {
if (index == -1 || (index >= 0 && index < unlockedAbilities.size())) {
this.selectedIndex = index;
syncToClient();
needsSync = true;
}
}
public void selectNext() {
if (unlockedAbilities.isEmpty()) return;
selectedIndex = (selectedIndex + 1) % unlockedAbilities.size();
syncToClient();
needsSync = true;
}
public void selectPrevious() {
if (unlockedAbilities.isEmpty()) return;
selectedIndex = (selectedIndex - 1 + unlockedAbilities.size()) % unlockedAbilities.size();
syncToClient();
needsSync = true;
}
public String getSelectedAbilityKey() {
@@ -561,13 +576,13 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (selectedIndex >= unlockedAbilities.size()) {
selectedIndex = Math.max(0, unlockedAbilities.size() - 1);
}
syncToClient();
needsSync = true;
}
public void unlockAbility(String key) {
if (key != null && !key.isEmpty() && !unlockedAbilities.contains(key)) {
unlockedAbilities.add(key);
syncToClient();
needsSync = true;
}
}
@@ -576,7 +591,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (selectedIndex >= unlockedAbilities.size()) {
selectedIndex = Math.max(0, unlockedAbilities.size() - 1);
}
syncToClient();
needsSync = true;
}
public boolean hasUnlockedAbility(String key) {
@@ -620,7 +635,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
public void resetCooldown(String key) {
resetPerAbilityCooldown(key);
cooldownEndTime = 0;
syncCooldownToClient();
}
/**
@@ -629,7 +643,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
public void resetAllCooldowns() {
cooldownEndTime = 0;
resetAllPerAbilityCooldowns();
syncCooldownToClient();
}
// ═══════════════════════════════════════════════════════════════════
@@ -664,7 +677,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
public void resetCooldown() {
cooldownEndTime = 0;
resetAllPerAbilityCooldowns();
syncCooldownToClient();
}
// ═══════════════════════════════════════════════════════════════════
@@ -729,7 +741,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
// Clean up any executing ability silently (no script events — already fired on old entity)
if (currentAbility != null && currentAbility.isExecuting()) {
removeTelegraph(currentAbility);
currentAbility.cleanup();
currentAbility.interrupt();
stopAbilityAnimation();
releaseRotationControl();
@@ -782,13 +793,69 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
/**
* Reset ability state after death/respawn.
* Preserves cooldowns (interrupt on death already rolled them) but clears
* active toggles (death should end ongoing effects).
* Preserves cooldowns (the death handler interrupted the ability which rolled cooldown
* via onInterruptComplete) but clears active toggles (death should end ongoing effects).
*/
public void resetOnRespawn() {
onEntityReconstructed(false, true);
}
/**
* Reset ability state on login. Clears all transient execution state (current ability,
* locks, chains, cooldowns) that may have leaked from a previous session via the
* PlayerData cache. Toggles are NOT cleared — they are restored from NBT by readFromNBT.
* <p>
* Does NOT send packets — called before the client's sync state is initialized.
* The caller must trigger a full ability sync afterwards (e.g. via syncToClient).
*/
public void resetOnLogin() {
// Silently clean up any stale executing ability
if (currentAbility != null && currentAbility.isExecuting()) {
removeTelegraph(currentAbility);
currentAbility.interrupt();
stopAbilityAnimation();
releaseRotationControl();
releaseLockedPosition();
}
// Clear chain and concurrent state
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
interruptConcurrentSlots();
// Clear all transient state
currentAbility = null;
currentAbilityKey = null;
currentTarget = null;
lastAbilityActivationTime = -1;
// Clear cooldowns (fresh start after relog)
cooldownEndTime = 0;
resetAllPerAbilityCooldowns();
interruptCooldownRolled = false;
// Reset sync tracking so next sync sends fresh state
lastSyncedFlags = 0;
needsSync = true;
}
/**
* Clean up ability state on disconnect. Interrupts any executing ability (fires events,
* rolls cooldown) before the player entity goes away, then clears all transient state.
* This ensures scripts receive proper interrupt/complete events and prevents stale state
* from leaking into the next session via the PlayerData cache.
*/
public void resetOnDisconnect() {
// Interrupt with events so scripts know the ability ended
if (currentAbility != null && currentAbility.isExecuting()) {
interruptCurrentAbility(null, 0);
}
// Clear any remaining transient state (cooldowns, chains, locks)
// Don't clear toggles — they were already saved to NBT by this point
onEntityReconstructed(true, false);
}
// ═══════════════════════════════════════════════════════════════════
// DAMAGE HANDLING
// ═══════════════════════════════════════════════════════════════════
@@ -931,7 +998,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (rotationLocked && currentAbility.isRotationLockedForCurrentPhase()) {
flags |= PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED;
}
if (currentAbility.hasAbilityMovement() && currentAbility.getPhase() == AbilityPhase.ACTIVE) {
if (currentAbility.hasAbilityMovement()
&& (currentAbility.getPhase() == AbilityPhase.ACTIVE || currentAbility.getPhase() == AbilityPhase.WINDUP)) {
flags |= PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT;
}
if (positionLocked) {
@@ -969,6 +1037,20 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
}
/**
* Periodic safety check: if no ability is executing but the client may have
* stale lock flags, send a clear. Prevents stuck clients from missed packets.
*/
public void ensureLockStateClear() {
if (isExecutingAbility() || isExecutingChain()) return;
EntityPlayer player = playerData.player;
if (!(player instanceof EntityPlayerMP)) return;
if (lastSyncedFlags != 0) {
lastSyncedFlags = 0;
PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0);
}
}
// ═══════════════════════════════════════════════════════════════════
// SCRIPT EVENTS (Player-specific: start event only, others via abstract)
// ═══════════════════════════════════════════════════════════════════
@@ -1051,6 +1133,10 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
*/
private void validateUnlockedAbilities() {
if (AbilityController.Instance == null) return;
// Only validate on the server - the client trusts server-sent data.
// Custom ability definitions may not have been synced to the client yet,
// which would cause valid abilities to be incorrectly pruned.
if (playerData == null || !(playerData.player instanceof EntityPlayerMP)) return;
Iterator<String> it = unlockedAbilities.iterator();
while (it.hasNext()) {
@@ -1,5 +1,6 @@
package noppes.npcs.controllers.data;
import cpw.mods.fml.common.FMLCommonHandler;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
@@ -54,6 +55,8 @@ public class PlayerAbilityHotbarData {
public void validateSlots() {
if (AbilityController.Instance == null) return;
// Only validate on the server - the client trusts server-sent data.
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return;
for (AbilityHotbarData slot : slots) {
if (slot.isEmpty()) continue;
boolean valid;
@@ -75,6 +78,10 @@ public class PlayerAbilityHotbarData {
}
}
/**
* Sync hotbar data only to the client.
* Used after server confirms a client hotbar edit.
*/
public void syncToClient(EntityPlayer player) {
if (player instanceof EntityPlayerMP) {
AbilityHotbarSyncPacket.sendToPlayer((EntityPlayerMP) player);
@@ -94,6 +94,10 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
private boolean specialKeyDown = false;
public void onLogin() {
// Clear any stale transient ability state that leaked via the PlayerData cache.
// Must happen before the animation check since it may clear ability animation state.
abilityData.resetOnLogin();
// Handle animation state from previous session
AnimationData animationData = this.animationData;
if (animationData != null && animationData.isClientAnimating()) {
@@ -117,17 +121,12 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
if (!controller.playerEffects.containsKey(playerID)) {
controller.playerEffects.put(playerID, effectData.getEffects());
}
// Sync player ability data to client
abilityData.syncToClient();
// Sync hotbar data to client
hotbarData.syncToClient(player);
}
public void onLogout() {
// Cancel any executing ability and release all locks
abilityData.interruptCurrentAbility();
// Interrupt executing ability (fires events, rolls cooldown), then clear
// all transient state so nothing leaks via the PlayerData cache.
abilityData.resetOnDisconnect();
this.partyInvites.clear();
this.actionManager.clear();
}
@@ -254,6 +253,8 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
factionData.saveNBTData(compound);
mailData.saveNBTData(compound);
tradeData.writeToNBT(compound);
abilityData.writeToNBT(compound);
hotbarData.writeToNBT(compound);
compound.setString("PlayerName", playername);
compound.setString("UUID", uuid);
DBCAddon.instance.writeToNBT(this, compound);
@@ -268,6 +269,8 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
factionData.loadNBTData(data);
mailData.loadNBTData(data);
tradeData.readFromNBT(data);
abilityData.readFromNBT(data);
hotbarData.readFromNBT(data);
if (player != null) {
playername = player.getCommandSenderName();
uuid = player.getPersistentID().toString();
@@ -48,7 +48,7 @@ public class ItemNpcWand extends Item {
EntityCustomNpc npc = new EntityCustomNpc(par3World);
npc.ais.startPos = new int[]{par4, par5, par6};
npc.setLocationAndAngles((float) par4 + 0.5F, npc.getStartYPos(), (float) par6 + 0.5F, player.rotationYaw, player.rotationPitch);
npc.setLocationAndAngles((float) par4 + 0.5F, npc.getStartYPos(), (float) par6 + 0.5F, player.rotationYaw, 0);
par3World.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
@@ -7,7 +7,6 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import kamkeel.npcs.entity.EntityAbilityOrb;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
@@ -117,8 +116,6 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback {
EnergyLightningData lightning = new EnergyLightningData();
EnergyLifespanData lifespan = new EnergyLifespanData(100, 72000);
EnergyHomingData homing = new EnergyHomingData();
EnergyTrajectoryData trajectory = new EnergyTrajectoryData();
homing.speed = 0.5f;
homing.homingStrength = 0.35f;
homing.homingRange = 20f;
@@ -126,7 +123,7 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback {
EntityAbilityOrb orb = new EntityAbilityOrb(
player.worldObj, player, null,
player.posX, player.posY + player.getEyeHeight(), player.posZ,
1.0f, colorData, combat, homing, lightning, lifespan, trajectory
1.0f, colorData, combat, homing, lightning, lifespan
);
orb.setupCharging(
@@ -86,6 +86,9 @@ public abstract class MixinModelRenderer {
float prevAngleX = this.rotateAngleX;
float prevAngleY = this.rotateAngleY;
float prevAngleZ = this.rotateAngleZ;
float prevOffsetX = this.offsetX;
float prevOffsetY = this.offsetY;
float prevOffsetZ = this.offsetZ;
boolean changedAngles = false;
try {
@@ -149,6 +152,11 @@ public abstract class MixinModelRenderer {
GL11.glPopMatrix();
}
// Mirror vanilla ModelRenderer behavior: always undo offset translation.
// Without this, models that animate via offsetX/Y/Z (e.g. witch nose while drinking)
// leak transforms into subsequent renders.
GL11.glTranslatef(-this.offsetX, -this.offsetY, -this.offsetZ);
if (changedAngles) {
this.rotationPointX = prevPointX;
this.rotationPointY = prevPointY;
@@ -156,6 +164,9 @@ public abstract class MixinModelRenderer {
this.rotateAngleX = prevAngleX;
this.rotateAngleY = prevAngleY;
this.rotateAngleZ = prevAngleZ;
this.offsetX = prevOffsetX;
this.offsetY = prevOffsetY;
this.offsetZ = prevOffsetZ;
}
}
}