diff --git a/src/api b/src/api index aac5f98be..b28a7a5c4 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit aac5f98be85b2004f61733c1c97bdae26329a714 +Subproject commit b28a7a5c4d025ec3d5207cd8d4714f14c3a5de72 diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyAbility.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java similarity index 99% rename from src/main/java/kamkeel/npcs/client/renderer/RenderEnergyAbility.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java index e87e24d51..ce5d59669 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyAbility.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java @@ -20,12 +20,12 @@ import org.lwjgl.opengl.GL12; * Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public abstract class RenderEnergyAbility extends Render { +public abstract class RenderEnergy extends Render { protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png"); protected static final int HIDE_INITIAL_ACTIVE_TICKS = 1; - public RenderEnergyAbility() { + public RenderEnergy() { this.shadowSize = 0.0f; } diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java index 676440035..846c167ea 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java @@ -2,20 +2,20 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityEnergyBarrier; /** * Intermediate renderer base for energy barrier entities (Dome, Panel). * Provides shared hit flash alpha computation. */ @SideOnly(Side.CLIENT) -public abstract class RenderEnergyBarrier extends RenderEnergyAbility { +public abstract class RenderEnergyBarrier extends RenderEnergy { /** * Compute the alpha boost from a hit flash effect. * Flash value decays from 4 to 0, producing alpha from 0.3 to 0. */ - protected float computeFlashAlpha(EntityAbilityBarrier barrier) { + protected float computeFlashAlpha(EntityEnergyBarrier barrier) { byte flash = barrier.getHitFlash(); if (flash <= 0) return 0.0f; return flash / 4.0f * 0.3f; diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java similarity index 99% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java index e9868854a..c5335d2ab 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java @@ -23,7 +23,7 @@ import java.util.List; * Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public class RenderAbilityBeam extends RenderEnergyAbility { +public class RenderEnergyBeam extends RenderEnergy { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java similarity index 99% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java index 3e3bcb025..e71e17a02 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java @@ -15,7 +15,7 @@ import org.lwjgl.opengl.GL11; * Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public class RenderAbilityDisc extends RenderEnergyAbility { +public class RenderEnergyDisc extends RenderEnergy { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java similarity index 86% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java index dcf3e5c06..34465635c 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDome.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyDome; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; @@ -10,17 +10,16 @@ import org.lwjgl.opengl.GL11; /** * Renders the Dome entity as a translucent sphere. * Inner layer solid, outer layer translucent glow. - * Optional skybox texture rendered on the interior surface. */ @SideOnly(Side.CLIENT) -public class RenderAbilityDome extends RenderEnergyBarrier { +public class RenderEnergyDome extends RenderEnergyBarrier { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { if (shouldSkipInitialActiveRender(entity)) { return; } - EntityAbilityDome dome = (EntityAbilityDome) entity; + EntityEnergyDome dome = (EntityEnergyDome) entity; float radius = dome.getDomeRadius(); float healthPercent = dome.getHealthPercent(); @@ -44,14 +43,9 @@ public class RenderAbilityDome extends RenderEnergyBarrier { float outerScale = 1.0f + dome.getOuterColorWidth() * 0.1f; float outerAlpha = dome.getOuterColorAlpha() * healthPercent; GL11.glDepthMask(false); - renderSphere(dome.getOuterColor(), outerAlpha + flashAlpha, radius * outerScale, 8); + renderSphere(dome.getOuterColor(), outerAlpha + (dome.getOuterColorAlpha() > 0 ? flashAlpha : 0), radius * outerScale, 8); } - // TODO: Skybox Feature - // if (dome.isSkyboxEnabled() && !dome.getSkyboxTexture().isEmpty()) { - // renderSkyboxSphere(dome.getSkyboxTexture(), radius, radius * 0.94f, 32, x, y, z); - // } - GL11.glDepthMask(true); // Render inner dome (depth write enabled so inner sphere properly occludes) renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8); @@ -114,5 +108,4 @@ public class RenderAbilityDome extends RenderEnergyBarrier { tess.draw(); } - // TODO: Skybox Feature — renderSkyboxSphere method removed } diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java index 850d857a4..02388621a 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java @@ -12,7 +12,7 @@ import org.lwjgl.opengl.GL11; * Draws expanding cubic shells with a short fade-out. */ @SideOnly(Side.CLIENT) -public class RenderEnergyExplosion extends RenderEnergyAbility { +public class RenderEnergyExplosion extends RenderEnergy { private static final float MAX_OUTER_ALPHA = 0.85f; private static final float MAX_INNER_ALPHA = 1.0f; diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java similarity index 99% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java index c2b2216df..1befc0dcc 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java @@ -17,7 +17,7 @@ import java.util.Map; * Design inspired by LouisXIV's energy rendering system. */ @SideOnly(Side.CLIENT) -public class RenderAbilityLaser extends RenderEnergyAbility { +public class RenderEnergyLaser extends RenderEnergy { private final Map tipLightningStates = new HashMap<>(); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java similarity index 98% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java index d5a44a245..08f77a522 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java @@ -13,7 +13,7 @@ import org.lwjgl.opengl.GL11; * Minecraft-style blocky appearance using Tessellator. */ @SideOnly(Side.CLIENT) -public class RenderAbilityOrb extends RenderEnergyAbility { +public class RenderEnergyOrb extends RenderEnergy { private static final int LIGHTNING_FADE_TICKS = 6; diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java similarity index 94% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java index d341082b5..5cb9a7abc 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityPanel.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityEnergyPanel; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; @@ -13,14 +13,14 @@ import org.lwjgl.opengl.GL11; * Voxel-blocky style with inner/outer layers. */ @SideOnly(Side.CLIENT) -public class RenderAbilityPanel extends RenderEnergyBarrier { +public class RenderEnergyPanel extends RenderEnergyBarrier { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { if (shouldSkipInitialActiveRender(entity)) { return; } - EntityAbilityPanel panel = (EntityAbilityPanel) entity; + EntityEnergyPanel panel = (EntityEnergyPanel) entity; float width = panel.getPanelData().panelWidth; float height = panel.getPanelData().panelHeight; @@ -67,7 +67,7 @@ public class RenderAbilityPanel extends RenderEnergyBarrier { float outerScale = 1.0f + panel.getOuterColorWidth() * 0.15f; float outerAlpha = panel.getOuterColorAlpha() * healthPercent; GL11.glDepthMask(false); - renderPanel(panel.getOuterColor(), outerAlpha + flashAlpha, + renderPanel(panel.getOuterColor(), outerAlpha + (panel.getOuterColorAlpha() > 0 ? flashAlpha : 0), width * 0.5f * outerScale, height * 0.5f * outerScale, panelThickness * 1.5f); GL11.glDepthMask(true); } diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java index be0d75748..f661442c1 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java @@ -13,7 +13,7 @@ import org.lwjgl.opengl.GL11; * Inner solid core with outer translucent glow. */ @SideOnly(Side.CLIENT) -public class RenderEnergySlicer extends RenderEnergyAbility { +public class RenderEnergySlicer extends RenderEnergy { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java similarity index 97% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java index fc7bc33c7..01ec9b429 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java @@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergySweeper; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; @@ -15,11 +15,11 @@ import org.lwjgl.opengl.GL11; * Uses similar rendering style to the Beam trail for visual consistency. */ @SideOnly(Side.CLIENT) -public class RenderAbilitySweeper extends Render { +public class RenderSweeper extends Render { @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { - EntityAbilitySweeper sweeper = (EntityAbilitySweeper) entity; + EntityEnergySweeper sweeper = (EntityEnergySweeper) entity; setupRenderState(); @@ -114,7 +114,7 @@ public class RenderAbilitySweeper extends Render { /** * Render a beam segment as a 3D rectangular prism with independent width and height. - * Uses the same approach as RenderAbilityBeam.renderBeamRectangle. + * Uses the same approach as RenderEnergyBeam.renderBeamRectangle. */ private void renderBeamSegment(double x1, double y1, double z1, double x2, double y2, double z2, diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java similarity index 99% rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java rename to src/main/java/kamkeel/npcs/client/renderer/RenderZone.java index 20d31c56d..1d3d92d85 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java @@ -23,7 +23,7 @@ import java.util.Map; import java.util.Random; @SideOnly(Side.CLIENT) -public class RenderAbilityZone extends Render { +public class RenderZone extends Render { private static final int CIRCLE_SEGMENTS = 32; private static final int ACCENT_LINE_COUNT = 12; diff --git a/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java b/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java index f33d3626b..27eb0efb8 100644 --- a/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java +++ b/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java @@ -99,7 +99,9 @@ public class QuestCategoryCommand extends CommandKamkeelBase { playerdata.questData.finishedQuests.put(quest.id, completeTime); } - if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) + if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime); ; diff --git a/src/main/java/kamkeel/npcs/command/QuestCommand.java b/src/main/java/kamkeel/npcs/command/QuestCommand.java index 0a6cb5edf..5ccbe5319 100644 --- a/src/main/java/kamkeel/npcs/command/QuestCommand.java +++ b/src/main/java/kamkeel/npcs/command/QuestCommand.java @@ -115,7 +115,9 @@ public class QuestCommand extends CommandKamkeelBase { playerdata.questData.finishedQuests.put(quest.id, completeTime); } - if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) + if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime); playerdata.save(); diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java index e2d8451f5..7acfc96a9 100644 --- a/src/main/java/kamkeel/npcs/controllers/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java @@ -17,9 +17,12 @@ import kamkeel.npcs.controllers.data.ability.enums.UserType; import kamkeel.npcs.controllers.data.ability.extender.IAbilityExtender; import kamkeel.npcs.controllers.data.ability.gui.IAbilityFieldProvider; import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider; +import kamkeel.npcs.controllers.data.ability.CustomAbility; import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; import kamkeel.npcs.controllers.data.ability.type.AbilityDash; +import kamkeel.npcs.controllers.data.ability.type.AbilityCounter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDodge; import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.ability.type.AbilityHazard; import kamkeel.npcs.controllers.data.ability.type.AbilityEffect; @@ -37,11 +40,15 @@ import kamkeel.npcs.controllers.data.ability.type.energy.AbilityOrb; import kamkeel.npcs.controllers.data.ability.type.energy.AbilityShield; import kamkeel.npcs.controllers.data.ability.type.energy.AbilitySweeper; import kamkeel.npcs.controllers.data.ability.type.energy.AbilityWall; +import net.minecraftforge.common.util.Constants; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; import noppes.npcs.LogWriter; +import noppes.npcs.api.ability.IChainedAbility; import noppes.npcs.api.handler.IAbilityHandler; import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.controllers.data.PlayerData; @@ -52,7 +59,6 @@ import java.io.File; import java.util.*; import java.util.function.Predicate; import java.util.function.Supplier; -import java.util.regex.Pattern; public class AbilityController implements IAbilityHandler { @@ -64,6 +70,10 @@ public class AbilityController implements IAbilityHandler { private final Map customAbilities = new LinkedHashMap<>(); // name → Ability private final Map customAbilitiesById = new LinkedHashMap<>(); // UUID → Ability + // ── Script Handlers ──────────────────────────────────────────────────── + public final HashMap abilityScriptHandlers = new HashMap<>(); + public final HashMap chainedAbilityScriptHandlers = new HashMap<>(); + // ── Extension Points ───────────────────────────────────────────────────── private final Map> externalVariants = new LinkedHashMap<>(); private final List fieldProviders = new ArrayList<>(); @@ -72,11 +82,6 @@ public class AbilityController implements IAbilityHandler { private final Map> conditionTypes = new HashMap<>(); private final List> flightCheckers = new ArrayList<>(); - // ── Legacy Migration ───────────────────────────────────────────────────── - private static final Pattern UUID_PATTERN = - Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", - Pattern.CASE_INSENSITIVE); - // ── Chained Abilities ────────────────────────────────────────────────── private final Map chainedAbilities = new LinkedHashMap<>(); // name → ChainedAbility private final Map chainedAbilitiesById = new LinkedHashMap<>(); // UUID → ChainedAbility @@ -97,7 +102,7 @@ public class AbilityController implements IAbilityHandler { // TYPE REGISTRATION // ═══════════════════════════════════════════════════════════════════════════ - public void registerType(String factoryKey, Supplier factory) { + public void registerType(Supplier factory) { Ability temp = factory.get(); String typeId = temp.getTypeId(); if (abilityTypes.containsKey(typeId)) { @@ -132,36 +137,37 @@ public class AbilityController implements IAbilityHandler { } private void registerBuiltinTypes() { - registerType("cnpc:slam", AbilitySlam::new); - registerType("cnpc:charge", AbilityCharge::new); + registerType(CustomAbility::new); - registerType("cnpc:heavy_hit", AbilityHeavyHit::new); - registerType("cnpc:cutter", AbilityCutter::new); + registerType(AbilitySlam::new); + registerType(AbilityCharge::new); - // registerType("cnpc:projectile", AbilityProjectile::new); + registerType(AbilityHeavyHit::new); + registerType(AbilityCutter::new); - registerType("cnpc:sweeper", AbilitySweeper::new); - registerType("cnpc:orb", AbilityOrb::new); - registerType("cnpc:disc", AbilityDisc::new); - registerType("cnpc:laser_shot", AbilityLaser::new); - registerType("cnpc:beam", AbilityBeam::new); - // registerType("cnpc:slicer", AbilitySlicer::new); + registerType(AbilitySweeper::new); + registerType(AbilityOrb::new); + registerType(AbilityDisc::new); + registerType(AbilityLaser::new); + registerType(AbilityBeam::new); - registerType("cnpc:dash", AbilityDash::new); - registerType("cnpc:teleport", AbilityTeleport::new); + registerType(AbilityDash::new); + registerType(AbilityTeleport::new); - registerType("cnpc:vortex", AbilityVortex::new); - registerType("cnpc:shockwave", AbilityShockwave::new); + registerType(AbilityVortex::new); + registerType(AbilityShockwave::new); - registerType("cnpc:guard", AbilityGuard::new); - registerType("cnpc:effect", AbilityEffect::new); + registerType(AbilityGuard::new); + registerType(AbilityCounter::new); + registerType(AbilityDodge::new); + registerType(AbilityEffect::new); - registerType("cnpc:hazard", AbilityHazard::new); - registerType("cnpc:trap", AbilityTrap::new); + registerType(AbilityHazard::new); + registerType(AbilityTrap::new); - registerType("cnpc:dome", AbilityDome::new); - registerType("cnpc:wall", AbilityWall::new); - registerType("cnpc:shield", AbilityShield::new); + registerType(AbilityDome::new); + registerType(AbilityWall::new); + registerType(AbilityShield::new); } private void registerBuiltinConditionTypes() { @@ -193,7 +199,7 @@ public class AbilityController implements IAbilityHandler { public Ability getAbilityByDisplayName(String displayName) { for (Ability ability : builtAbilities.values()) { - if (ability.getName().equals(displayName)) { + if (ability.getDisplayName().equals(displayName)) { return ability; } } @@ -214,8 +220,6 @@ public class AbilityController implements IAbilityHandler { public void load() { customAbilities.clear(); customAbilitiesById.clear(); - int migrated = 0; - Map migratedAbilityNames = new HashMap(); File dir = getDir(); File[] files = dir.exists() ? dir.listFiles() : null; @@ -230,59 +234,29 @@ public class AbilityController implements IAbilityHandler { Ability ability = fromNBT(nbt); if (ability == null) continue; - // Skip built-in abilities that were erroneously saved as custom files - if (ability.isBuiltIn()) { - file.delete(); - LogWriter.info("Removed stale built-in ability file: " + filename); - continue; - } - - String storedName = ability.getName(); - String preferredName; - if (UUID_PATTERN.matcher(fileKey).matches()) { - preferredName = (storedName != null && !storedName.isEmpty()) ? storedName : fileKey; - } else { - preferredName = fileKey; - } - String name = FileNameHelper.sanitizeName(preferredName, "Ability"); + String name = FileNameHelper.sanitizeName(fileKey, "Ability"); name = makeUniqueNameForLoad(customAbilities, dir, file, name, fileKey); boolean dirty = false; if (!name.equals(fileKey)) { File renamedFile = new File(dir, name + ".json"); if (file.renameTo(renamedFile)) { - LogWriter.info("Migrated ability file: " + fileKey + ".json -> " + name + ".json"); file = renamedFile; - migrated++; dirty = true; - } else { - LogWriter.error("Failed to rename ability file: " + fileKey + ".json -> " + name + ".json"); } } ability.setName(name); - if (storedName != null && !storedName.equals(name)) { - dirty = true; - if (!storedName.isEmpty()) { - migratedAbilityNames.put(storedName, name); - } - } - if (!fileKey.equals(name)) { - migratedAbilityNames.put(fileKey, name); - } - // Ensure ability has a UUID; generate one for legacy abilities String uuid = ability.getId(); - if (uuid == null || uuid.isEmpty() || uuid.equals(fileKey) || uuid.equals(name)) { - // Legacy: id was the name or empty — generate a real UUID + if (uuid == null || uuid.isEmpty()) { uuid = UUID.randomUUID().toString(); ability.setId(uuid); - migrated++; dirty = true; } if (dirty) { - NBTJsonUtil.SaveFile(file, ability.writeNBT()); + NBTJsonUtil.SaveFile(file, ability.writeNBT(true)); } customAbilities.put(name, ability); @@ -294,12 +268,9 @@ public class AbilityController implements IAbilityHandler { } customAbilityRevision++; - if (migrated > 0) { - LogWriter.info("Migrated " + migrated + " abilities (filename normalization / UUID repair)"); - } LogWriter.info("Loaded " + customAbilities.size() + " custom abilities"); - loadChainedAbilities(migratedAbilityNames); + loadChainedAbilities(); } private boolean nameFileExists(File dir, String name, File ignoredFile) { @@ -325,32 +296,6 @@ public class AbilityController implements IAbilityHandler { return candidate; } - private boolean remapChainEntryReferences(ChainedAbility chain, Map migratedAbilityNames) { - if (chain == null || migratedAbilityNames == null || migratedAbilityNames.isEmpty()) return false; - boolean changed = false; - for (ChainedAbilityEntry entry : chain.getEntries()) { - if (entry == null || !entry.isReference()) continue; - String ref = entry.getAbilityReference(); - if (ref == null || ref.isEmpty()) continue; - - String mapped = migratedAbilityNames.get(ref); - if (mapped == null) { - for (Map.Entry e : migratedAbilityNames.entrySet()) { - if (e.getKey().equalsIgnoreCase(ref)) { - mapped = e.getValue(); - break; - } - } - } - - if (mapped != null && !mapped.equals(ref)) { - entry.setAbilityReference(mapped); - changed = true; - } - } - return changed; - } - public boolean saveCustomAbility(Ability ability) { if (ability == null) return false; if (ability.isBuiltIn()) return false; @@ -396,7 +341,8 @@ public class AbilityController implements IAbilityHandler { File fileCurrent = new File(dir, name + ".json"); try { - NBTTagCompound nbt = ability.writeNBT(); + NBTTagCompound nbt = ability.writeNBT(true); + NBTJsonUtil.SaveFile(fileNew, nbt); if (fileCurrent.exists()) { @@ -434,10 +380,11 @@ public class AbilityController implements IAbilityHandler { } if (removed == null) return false; - // Also remove from UUID index + // Also remove from UUID index and script handler String uuid = removed.getId(); if (uuid != null && !uuid.isEmpty()) { customAbilitiesById.remove(uuid); + abilityScriptHandlers.remove(uuid); } File dir = getDir(); @@ -459,6 +406,9 @@ public class AbilityController implements IAbilityHandler { pData.abilityData.lockAbility(name); changed = true; } + if (changed) { + pData.save(); + } } } } @@ -516,10 +466,9 @@ public class AbilityController implements IAbilityHandler { // CHAINED ABILITIES // ═══════════════════════════════════════════════════════════════════════════ - private void loadChainedAbilities(Map migratedAbilityNames) { + private void loadChainedAbilities() { chainedAbilities.clear(); chainedAbilitiesById.clear(); - int migrated = 0; File dir = getChainedDir(); File[] files = dir.exists() ? dir.listFiles() : null; @@ -534,7 +483,6 @@ public class AbilityController implements IAbilityHandler { ChainedAbility chain = new ChainedAbility(); chain.readNBT(nbt); - String storedName = chain.getName(); String name = FileNameHelper.sanitizeName(fileKey, "Chain"); name = makeUniqueNameForLoad(chainedAbilities, dir, file, name, fileKey); @@ -542,33 +490,22 @@ public class AbilityController implements IAbilityHandler { if (!name.equals(fileKey)) { File renamedFile = new File(dir, name + ".json"); if (file.renameTo(renamedFile)) { - LogWriter.info("Migrated chained ability file: " + fileKey + ".json -> " + name + ".json"); file = renamedFile; dirty = true; - } else { - LogWriter.error("Failed to rename chained ability file: " + fileKey + ".json -> " + name + ".json"); } } chain.setName(name); - if (storedName != null && !storedName.equals(name)) { - dirty = true; - } - - if (remapChainEntryReferences(chain, migratedAbilityNames)) { - dirty = true; - } String uuid = chain.getId(); - if (uuid == null || uuid.isEmpty() || uuid.equals(fileKey) || uuid.equals(name)) { + if (uuid == null || uuid.isEmpty()) { uuid = UUID.randomUUID().toString(); chain.setId(uuid); dirty = true; } if (dirty) { - NBTJsonUtil.SaveFile(file, chain.writeNBT()); - migrated++; + NBTJsonUtil.SaveFile(file, chain.writeNBT(true)); } chainedAbilities.put(name, chain); @@ -580,9 +517,6 @@ public class AbilityController implements IAbilityHandler { } chainedAbilityRevision++; - if (migrated > 0) { - LogWriter.info("Migrated " + migrated + " chained abilities"); - } LogWriter.info("Loaded " + chainedAbilities.size() + " chained abilities"); } @@ -626,7 +560,8 @@ public class AbilityController implements IAbilityHandler { File fileCurrent = new File(dir, name + ".json"); try { - NBTTagCompound nbt = chain.writeNBT(); + NBTTagCompound nbt = chain.writeNBT(true); + NBTJsonUtil.SaveFile(fileNew, nbt); if (fileCurrent.exists()) { @@ -667,6 +602,7 @@ public class AbilityController implements IAbilityHandler { String uuid = removed.getId(); if (uuid != null && !uuid.isEmpty()) { chainedAbilitiesById.remove(uuid); + chainedAbilityScriptHandlers.remove(uuid); } File dir = getChainedDir(); @@ -775,7 +711,7 @@ public class AbilityController implements IAbilityHandler { } @Override - public boolean saveChainedAbility(noppes.npcs.api.ability.IChainedAbility chain) { + public boolean saveChainedAbility(IChainedAbility chain) { if (chain instanceof ChainedAbility) { return saveChainedAbility((ChainedAbility) chain); } @@ -818,48 +754,36 @@ public class AbilityController implements IAbilityHandler { Ability byUuid = customAbilitiesById.get(key); if (byUuid != null) return byUuid.deepCopy(); - // Built-in: exact name + // Built-in: exact key Ability builtIn = builtAbilities.get(key); if (builtIn != null) return builtIn.deepCopy(); - // Built-in: case-insensitive map key + // Built-in: case-insensitive key + String lowerKey = key.toLowerCase(); for (Map.Entry entry : builtAbilities.entrySet()) { - if (entry.getKey().equalsIgnoreCase(key)) { + if (entry.getKey().equalsIgnoreCase(lowerKey)) { return entry.getValue().deepCopy(); } } - // Built-in: by ability name (name may differ from map key, e.g. "Ki Fist" vs "ki_fist") + // Built-in: by ID (case-insensitive) for (Ability ability : builtAbilities.values()) { - if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { + if (key.equalsIgnoreCase(ability.getId())) { return ability.deepCopy(); } } - // Built-in: registry key / ID - for (Ability ability : builtAbilities.values()) { - if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) { - return ability.deepCopy(); - } - } - - // Custom: exact name (fallback for legacy references) + // Custom: exact name Ability custom = customAbilities.get(key); if (custom != null) return custom.deepCopy(); // Custom: case-insensitive name - for (Ability ability : customAbilities.values()) { - if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { - return ability.deepCopy(); + for (Map.Entry entry : customAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue().deepCopy(); } } - String sanitizedKey = FileNameHelper.sanitizeTextInput(key); - if (!sanitizedKey.equals(key)) { - Ability sanitized = customAbilities.get(sanitizedKey); - if (sanitized != null) return sanitized.deepCopy(); - } - return null; } @@ -904,14 +828,8 @@ public class AbilityController implements IAbilityHandler { } public boolean hasAbility(String key) { - if (builtAbilities.containsKey(key) || customAbilities.containsKey(key) - || customAbilitiesById.containsKey(key)) { - return true; - } - String sanitized = FileNameHelper.sanitizeTextInput(key); - return !sanitized.equals(key) - && (builtAbilities.containsKey(sanitized) || customAbilities.containsKey(sanitized) - || customAbilitiesById.containsKey(sanitized)); + return builtAbilities.containsKey(key) || customAbilities.containsKey(key) + || customAbilitiesById.containsKey(key); } public Ability getCustomAbilityByUUID(String uuid) { @@ -919,12 +837,30 @@ public class AbilityController implements IAbilityHandler { } public Ability getCustomAbilityByName(String name) { - Ability ability = customAbilities.get(name); - if (ability != null) return ability; - String sanitized = FileNameHelper.sanitizeTextInput(name); - if (!sanitized.equals(name)) { - return customAbilities.get(sanitized); + return customAbilities.get(name); + } + + /** + * Resolve an ability by key and return the live (non-copied) reference. + * For validation/permission checks only — do NOT expose or modify the returned ability. + * Uses the same lookup chain as {@link #resolveAbility(String)}. + */ + public Ability peekAbility(String key) { + if (key == null || key.isEmpty()) return null; + + Ability byUuid = customAbilitiesById.get(key); + if (byUuid != null) return byUuid; + + Ability builtIn = builtAbilities.get(key); + if (builtIn != null) return builtIn; + + for (Ability ability : builtAbilities.values()) { + if (key.equals(ability.getId())) return ability; } + + Ability custom = customAbilities.get(key); + if (custom != null) return custom; + return null; } @@ -935,33 +871,20 @@ public class AbilityController implements IAbilityHandler { public boolean canResolveAbility(String key) { if (key == null || key.isEmpty()) return false; - // Custom: UUID lookup (most common for persistent references) + // Custom: UUID lookup if (customAbilitiesById.containsKey(key)) return true; - // Built-in: exact name + // Built-in: exact key if (builtAbilities.containsKey(key)) return true; - // Built-in: case-insensitive name - for (String name : builtAbilities.keySet()) { - if (name.equalsIgnoreCase(key)) return true; - } - - // Built-in: registry key / ID + // Built-in: by ID for (Ability ability : builtAbilities.values()) { - if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) return true; + if (key.equals(ability.getId())) return true; } - // Custom: exact name (fallback for legacy references) + // Custom: exact name if (customAbilities.containsKey(key)) return true; - // Custom: case-insensitive name - for (Ability ability : customAbilities.values()) { - if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) return true; - } - - String sanitizedKey = FileNameHelper.sanitizeTextInput(key); - if (!sanitizedKey.equals(key) && customAbilities.containsKey(sanitizedKey)) return true; - return false; } diff --git a/src/main/java/kamkeel/npcs/controllers/ProfileController.java b/src/main/java/kamkeel/npcs/controllers/ProfileController.java index f7ac06bb1..fcb3436af 100644 --- a/src/main/java/kamkeel/npcs/controllers/ProfileController.java +++ b/src/main/java/kamkeel/npcs/controllers/ProfileController.java @@ -523,6 +523,7 @@ public class ProfileController implements IProfileHandler { // overwrite the destination slot with stale data. saveSlotData(profile.player, profile, prevSlot); loadSlotData(profile.player, profile, newSlotId); + syncSharedQuestsToPlayer(profile.player); EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true); } else { @@ -860,6 +861,9 @@ public class ProfileController implements IProfileHandler { } } + // Update the profile cache + profile.sharedQuestTimestamps = universalFinished; + // Push the universal shared completion times into every slot. for (ISlot slot : profile.getSlots().values()) { IPlayerData data = getSlotPlayerData(player, slot.getId()); @@ -872,21 +876,29 @@ public class ProfileController implements IProfileHandler { } } + public void syncSharedQuestsToPlayer(EntityPlayer player) { + Profile profile = getProfile(player); + if (profile == null || profile.sharedQuestTimestamps.isEmpty()) { + return; + } + PlayerQuestData questData = PlayerData.get(player).questData; + for (Map.Entry entry : profile.sharedQuestTimestamps.entrySet()) { + Long existing = questData.finishedQuests.get(entry.getKey()); + if (existing == null || entry.getValue() > existing) { + questData.finishedQuests.put(entry.getKey(), entry.getValue()); + } + } + } + public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) { Profile profile = getProfile(player); if (profile == null) { return; } - for (ISlot slot : profile.getSlots().values()) { - IPlayerData playerData = getSlotPlayerData(player, slot.getId()); - if (playerData != null) { - PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData(); - Long existing = questData.finishedQuests.get(questId); - if (existing == null || completeTime > existing) { - questData.finishedQuests.put(questId, completeTime); - } - playerData.save(); - } + + Long existing = profile.sharedQuestTimestamps.get(questId); + if (existing == null || completeTime > existing) { + profile.sharedQuestTimestamps.put(questId, completeTime); } save(player, profile); } diff --git a/src/main/java/kamkeel/npcs/controllers/SyncController.java b/src/main/java/kamkeel/npcs/controllers/SyncController.java index 2d6384c27..6403a2c1b 100644 --- a/src/main/java/kamkeel/npcs/controllers/SyncController.java +++ b/src/main/java/kamkeel/npcs/controllers/SyncController.java @@ -337,7 +337,7 @@ public class SyncController { NBTTagList list = new NBTTagList(); NBTTagCompound compound = new NBTTagCompound(); for (Map.Entry entry : AbilityController.Instance.getCustomAbilities().entrySet()) { - NBTTagCompound abilityNBT = entry.getValue().writeNBT(); + NBTTagCompound abilityNBT = entry.getValue().writeNBT(false); abilityNBT.setString("CustomAbilityId", entry.getKey()); list.appendTag(abilityNBT); } @@ -358,7 +358,7 @@ public class SyncController { NBTTagList list = new NBTTagList(); NBTTagCompound compound = new NBTTagCompound(); for (Map.Entry entry : AbilityController.Instance.getChainedAbilities().entrySet()) { - NBTTagCompound chainNBT = entry.getValue().writeNBT(); + NBTTagCompound chainNBT = entry.getValue().writeNBT(false); chainNBT.setString("ChainedAbilityId", entry.getKey()); list.appendTag(chainNBT); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 1b3b290fe..0b78a5b2f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -19,9 +19,9 @@ import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.telegraph.Telegraph; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBarrier; -import kamkeel.npcs.entity.EntityAbilityDome; -import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityEnergyPanel; import kamkeel.npcs.util.FileNameHelper; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -36,23 +36,20 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.DataAbilities; import noppes.npcs.NpcDamageSource; import noppes.npcs.api.INbt; import noppes.npcs.api.ability.IAbility; -import noppes.npcs.api.entity.IPlayer; import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.Frame; -import noppes.npcs.controllers.data.PlayerDataScript; +import noppes.npcs.controllers.data.AbilityScript; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.EventHooks; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AbilityEvent; -import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import java.util.ArrayList; import java.util.Collections; @@ -139,6 +136,48 @@ public abstract class Ability implements IAbility, IAbilityAction { protected transient boolean builtIn = false; protected transient String registryKey; + // Default icon layers (set in subclass constructors, NOT persisted) + protected transient DefaultIconLayer[] defaultIconLayers = null; + protected transient int defaultIconWidth = 48; + protected transient int defaultIconHeight = 48; + + /** + * A single layer of a default ability icon. Each layer has a texture, + * an optional dynamic color source, and optional per-state texture variants. + */ + public static class DefaultIconLayer { + public final String texture; + public final String[] stateTextures; + public final java.util.function.IntSupplier colorSource; + + public DefaultIconLayer(String texture, String[] stateTextures, java.util.function.IntSupplier colorSource) { + this.texture = texture; + this.stateTextures = stateTextures; + this.colorSource = colorSource; + } + + public DefaultIconLayer(String texture, java.util.function.IntSupplier colorSource) { + this(texture, null, colorSource); + } + + /** Layer with no color tinting (renders as white). */ + public DefaultIconLayer(String texture) { + this(texture, null, null); + } + + /** Resolve texture for a given toggle state. Falls back to base texture. */ + public String getTextureForState(int state) { + if (state > 0 && stateTextures != null && state - 1 < stateTextures.length) { + return stateTextures[state - 1]; + } + return texture; + } + + public int getColor() { + return colorSource != null ? colorSource.getAsInt() : 0xFFFFFF; + } + } + // ═══════════════════════════════════════════════════════════════════ // TOGGLE CONFIGURATION (saved to NBT for custom abilities) // ═══════════════════════════════════════════════════════════════════ @@ -295,28 +334,14 @@ public abstract class Ability implements IAbility, IAbilityAction { // ═══════════════════════════════════════════════════════════════════ /** - * Called when this toggle ability is first activated (state goes from 0 to any active state). - * Override to apply effects (e.g., set a DBC flag, apply a buff). - */ - public void onToggleOn(EntityLivingBase caster) { - } - - /** - * Called when this toggle ability is fully deactivated (state goes to 0). - * Override to remove effects (e.g., clear a DBC flag, remove a buff). - */ - public void onToggleOff(EntityLivingBase caster) { - } - - /** - * Called whenever the toggle state changes (including on/off transitions and mid-cycling). - * For multi-state toggles, this fires on every state transition. + * Called whenever the toggle state changes (activation, deactivation, or mid-cycling). + * Override to apply/remove effects based on state transitions. * * @param caster The entity * @param oldState Previous state (0 = was off) * @param newState New state (0 = now off, 1+ = active state) */ - public void onToggleStateChanged(EntityLivingBase caster, int oldState, int newState) { + public void onToggle(EntityLivingBase caster, int oldState, int newState) { } /** @@ -365,11 +390,7 @@ public abstract class Ability implements IAbility, IAbilityAction { * Unlike {@link #cleanup()}, this does NOT kill spawned entities (they may * still be in flight for overlap mode). */ - public void resetForBurst() { - } - - public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) { - } + public void resetForBurst() {} /** * Apply damage to an entity with ability hit event support. @@ -432,39 +453,15 @@ public abstract class Ability implements IAbility, IAbilityAction { private boolean applyAbilityDamageInternal(EntityLivingBase caster, EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp, double knockbackDirX, double knockbackDirZ) { - // Fire hit event for NPC casters (NPC event system) - if (caster instanceof EntityNPCInterface) { - EntityNPCInterface npc = (EntityNPCInterface) caster; - DataAbilities dataAbilities = npc.abilities; - AbilityEvent.HitEvent event = dataAbilities.fireHitEvent( - this, currentTarget, hitEntity, damage, knockback, knockbackUp); - - if (event == null) { - return false; // Cancelled - } - - damage = event.getDamage(); - knockback = event.getKnockback(); - knockbackUp = event.getKnockbackUp(); - } - // Fire hit event for Player casters (Player event system) - else if (caster instanceof EntityPlayer && ScriptController.Instance != null) { - EntityPlayer player = (EntityPlayer) caster; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler != null) { - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.HitEvent event = new PlayerAbilityEvent.HitEvent( - iPlayer, this, currentTarget, hitEntity, damage, knockback, knockbackUp); - - if (noppes.npcs.EventHooks.onPlayerAbilityHit(handler, event)) { - return false; // Cancelled - } - - damage = event.getDamage(); - knockback = event.getKnockback(); - knockbackUp = event.getKnockbackUp(); - } + // Fire hit event (unified — works for both NPC and Player casters) + AbilityEvent.HitEvent hitEvent = new AbilityEvent.HitEvent( + caster, this, currentTarget, hitEntity, damage, knockback, knockbackUp); + if (EventHooks.onAbilityHit(this, hitEvent)) { + return false; // Cancelled } + damage = hitEvent.getDamage(); + knockback = hitEvent.getKnockback(); + knockbackUp = hitEvent.getKnockbackUp(); // Save velocity before damage to cancel vanilla knockback when ability knockback is zero double prevMotionX = hitEntity.motionX; @@ -809,23 +806,35 @@ public abstract class Ability implements IAbility, IAbilityAction { } } - // ── Icon tab (native) ───────────────────────────────────── + // ── Icon section (Effects tab) ─────────────────────────── if (!isNpcInlineEdit()) { AbilityIconData icon = AbilityIconData.fromAbility(this); - defs.add(FieldDef.stringField("gui.texture", icon::getTexture, icon::setTexture) - .tab("Icon")); - defs.add(FieldDef.section("ability.icon.section.uv").tab("Icon")); - defs.add(FieldDef.intField("ability.icon.x", icon::getIconX, icon::setIconX) - .tab("Icon").range(0, 4096)); - defs.add(FieldDef.intField("ability.icon.y", icon::getIconY, icon::setIconY) - .tab("Icon").range(0, 4096)); - defs.add(FieldDef.section("gui.size").tab("Icon")); - defs.add(FieldDef.intField("gui.width", icon::getWidth, icon::setWidth) - .tab("Icon").range(1, 256)); - defs.add(FieldDef.intField("gui.height", icon::getHeight, icon::setHeight) - .tab("Icon").range(1, 256)); + java.util.function.BooleanSupplier isCustom = icon::isEnabled; + + defs.add(FieldDef.section("ability.section.icon").tab("Effects")); + defs.add(FieldDef.boolField("ability.hasIcon", icon::isEnabled, icon::setEnabled) + .tab("Effects")); + defs.add(FieldDef.row( + FieldDef.intField("gui.width", icon::getWidth, icon::setWidth).range(1, 256), + FieldDef.intField("gui.height", icon::getHeight, icon::setHeight).range(1, 256) + ).tab("Effects").visibleWhen(isCustom)); defs.add(FieldDef.floatField("gui.scale", icon::getScale, icon::setScale) - .tab("Icon").range(0.1f, 10.0f)); + .tab("Effects").range(0.1f, 10.0f).visibleWhen(isCustom)); + defs.add(FieldDef.intField("ability.icon.layers", icon::getLayerCount, icon::setLayerCount) + .tab("Effects").range(1, AbilityIconData.MAX_LAYERS).visibleWhen(isCustom)); + + addIconLayerFields(defs, icon, 0, isCustom); + addIconLayerFields(defs, icon, 1, () -> isCustom.getAsBoolean() && icon.getLayerCount() >= 2); + addIconLayerFields(defs, icon, 2, () -> isCustom.getAsBoolean() && icon.getLayerCount() >= 3); + + // Animation + defs.add(FieldDef.section("Animation").tab("Effects").visibleWhen(isCustom)); + defs.add(FieldDef.boolField("gui.animated", icon::isAnimated, icon::setAnimated) + .tab("Effects").visibleWhen(isCustom).hover("gui.animated.hover")); + defs.add(FieldDef.intField("gui.frameCount", icon::getFrameCount, icon::setFrameCount) + .tab("Effects").range(1, 256).visibleWhen(() -> isCustom.getAsBoolean() && icon.isAnimated())); + defs.add(FieldDef.intField("gui.frameTime", icon::getFrameTime, icon::setFrameTime) + .tab("Effects").range(1, 100).visibleWhen(() -> isCustom.getAsBoolean() && icon.isAnimated())); } // External field providers (e.g., DBC Addon injecting a "DBC" tab) @@ -836,6 +845,28 @@ public abstract class Ability implements IAbility, IAbilityAction { return defs; } + private void addIconLayerFields(List defs, AbilityIconData icon, int layerIndex, + java.util.function.BooleanSupplier visible) { + String sectionLabel = StatCollector.translateToLocal("ability.icon.layer") + " " + (layerIndex + 1); + defs.add(FieldDef.section(sectionLabel).tab("Effects").visibleWhen(visible)); + defs.add(FieldDef.stringField("gui.texture", + () -> icon.getLayer(layerIndex).texture, + t -> icon.setLayerTexture(layerIndex, t)) + .tab("Effects").visibleWhen(visible)); + defs.add(FieldDef.row( + FieldDef.intField("ability.icon.x", + () -> icon.getLayer(layerIndex).iconX, + x -> icon.setLayerIconX(layerIndex, x)).range(0, 4096), + FieldDef.intField("ability.icon.y", + () -> icon.getLayer(layerIndex).iconY, + y -> icon.setLayerIconY(layerIndex, y)).range(0, 4096) + ).tab("Effects").visibleWhen(visible)); + defs.add(FieldDef.colorSubGui("ability.icon.tint", + () -> icon.getLayer(layerIndex).tintColor, + c -> icon.setLayerTintColor(layerIndex, c)) + .tab("Effects").visibleWhen(visible)); + } + /** * Creates the GUI for configuring this ability. * Override this method to provide a custom GUI subclass for type-specific settings. @@ -1378,7 +1409,7 @@ public abstract class Ability implements IAbility, IAbilityAction { // NBT (config only, execution state is transient) // ═══════════════════════════════════════════════════════════════════ - public NBTTagCompound writeNBT() { + public NBTTagCompound writeNBT(boolean saveScripts) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setString("id", id); nbt.setString("name", name); @@ -1405,9 +1436,10 @@ public abstract class Ability implements IAbility, IAbilityAction { nbt.setInteger("windUpAnimationId", windUpAnimationId); nbt.setInteger("activeAnimationId", activeAnimationId); nbt.setInteger("dazedAnimationId", dazedAnimationId); - nbt.setString("windUpAnimationName", windUpAnimationName); - nbt.setString("activeAnimationName", activeAnimationName); - nbt.setString("dazedAnimationName", dazedAnimationName); + // Resolve current animation names from controller before writing + nbt.setString("windUpAnimationName", resolveAnimationName(windUpAnimationId, windUpAnimationName)); + nbt.setString("activeAnimationName", resolveAnimationName(activeAnimationId, activeAnimationName)); + nbt.setString("dazedAnimationName", resolveAnimationName(dazedAnimationId, dazedAnimationName)); nbt.setBoolean("showTelegraph", showTelegraph); nbt.setString("telegraphType", telegraphType.name()); nbt.setFloat("telegraphHeightOffset", telegraphHeightOffset); @@ -1452,6 +1484,16 @@ public abstract class Ability implements IAbility, IAbilityAction { writeTypeNBT(typeNBT); nbt.setTag("typeData", typeNBT); + // Script handler data (matching CustomEffect.writeToNBT pattern) + if (saveScripts) { + AbilityScript handler = getScriptHandler(); + if (handler != null) { + NBTTagCompound scriptData = new NBTTagCompound(); + handler.writeToNBT(scriptData); + nbt.setTag("ScriptData", scriptData); + } + } + return nbt; } @@ -1548,6 +1590,13 @@ public abstract class Ability implements IAbility, IAbilityAction { if (nbt.hasKey("typeData")) { readTypeNBT(nbt.getCompoundTag("typeData")); } + + // Script handler data (matching CustomEffect.readFromNBT pattern) + if (nbt.hasKey("ScriptData", 10)) { + AbilityScript handler = new AbilityScript(this.id); + handler.readFromNBT(nbt.getCompoundTag("ScriptData")); + setScriptHandler(handler); + } } // ═══════════════════════════════════════════════════════════════════ @@ -1627,8 +1676,29 @@ public abstract class Ability implements IAbility, IAbilityAction { this.typeId = "ability." + registryKey.replace(':', '.'); } + // ═══════════════════════════════════════════════════════════════════ + // DEFAULT ICON + // ═══════════════════════════════════════════════════════════════════ + + public DefaultIconLayer[] getDefaultIconLayers() { + return defaultIconLayers; + } + + public int getDefaultIconWidth() { + return defaultIconWidth; + } + + public int getDefaultIconHeight() { + return defaultIconHeight; + } + + public boolean hasDefaultIcon() { + return defaultIconLayers != null && defaultIconLayers.length > 0 + && defaultIconLayers[0].texture != null && !defaultIconLayers[0].texture.isEmpty(); + } + public Ability deepCopy() { - return AbilityController.Instance.fromNBT(this.writeNBT()); + return AbilityController.Instance.fromNBT(this.writeNBT(true)); } @Override @@ -1964,17 +2034,32 @@ public abstract class Ability implements IAbility, IAbilityAction { this.activeSound = activeSound; } + /** + * Resolves the current animation name for a custom animation ID. + * If the ID refers to a custom animation, looks up the current name from the controller. + * For built-in animations (id == -1), returns the stored name as-is. + */ + protected String resolveAnimationName(int animId, String storedName) { + if (animId >= 0 && AnimationController.Instance != null) { + Animation anim = (Animation) AnimationController.Instance.get(animId); + if (anim != null && anim.name != null && !anim.name.isEmpty()) { + return anim.name; + } + } + return storedName; + } + public Animation getWindUpAnimation() { if (AnimationController.Instance == null) return null; - // Built-in animation by name takes priority - if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(windUpAnimationName, true); - } - // Fall back to user animation by ID + // Custom animation by ID (most reliable, survives renames) if (windUpAnimationId >= 0) { return (Animation) AnimationController.Instance.get(windUpAnimationId); } + // Built-in animation by name + if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(windUpAnimationName, true); + } return null; } @@ -1997,14 +2082,14 @@ public abstract class Ability implements IAbility, IAbilityAction { public Animation getActiveAnimation() { if (AnimationController.Instance == null) return null; - // Built-in animation by name takes priority - if (activeAnimationName != null && !activeAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(activeAnimationName, true); - } - // Fall back to user animation by ID + // Custom animation by ID (most reliable, survives renames) if (activeAnimationId >= 0) { return (Animation) AnimationController.Instance.get(activeAnimationId); } + // Built-in animation by name + if (activeAnimationName != null && !activeAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(activeAnimationName, true); + } return null; } @@ -2027,14 +2112,14 @@ public abstract class Ability implements IAbility, IAbilityAction { public Animation getDazedAnimation() { if (AnimationController.Instance == null) return null; - // Built-in animation by name takes priority - if (dazedAnimationName != null && !dazedAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(dazedAnimationName, true); - } - // Fall back to user animation by ID + // Custom animation by ID (most reliable, survives renames) if (dazedAnimationId >= 0) { return (Animation) AnimationController.Instance.get(dazedAnimationId); } + // Built-in animation by name + if (dazedAnimationName != null && !dazedAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(dazedAnimationName, true); + } return null; } @@ -2284,14 +2369,14 @@ public abstract class Ability implements IAbility, IAbilityAction { } Animation animation = null; - // Check for built-in animation (by name) first - if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { - animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true); - } - // Fall back to user animation (by ID) - else if (windUpAnimationId >= 0) { + // Custom animation by ID (most reliable, survives renames) + if (windUpAnimationId >= 0) { animation = (Animation) AnimationController.Instance.get(windUpAnimationId); } + // Built-in animation by name + else if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { + animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true); + } if (animation == null || animation.frames.isEmpty()) { return this.windUpTicks; @@ -2390,9 +2475,9 @@ public abstract class Ability implements IAbility, IAbilityAction { double maxZ = Math.max(caster.posZ, target.posZ) + searchRange; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - List barriers = world.getEntitiesWithinAABB(EntityAbilityBarrier.class, searchBox); + List barriers = world.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox); - for (EntityAbilityBarrier barrier : barriers) { + for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead) continue; if (barrier.isCharging()) continue; @@ -2403,10 +2488,10 @@ public abstract class Ability implements IAbility, IAbilityAction { if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue; } - if (barrier instanceof EntityAbilityDome) { - if (isDomeBlocking((EntityAbilityDome) barrier, caster, target)) return true; - } else if (barrier instanceof EntityAbilityPanel) { - if (isPanelBlocking((EntityAbilityPanel) barrier, caster, target)) return true; + if (barrier instanceof EntityEnergyDome) { + if (isDomeBlocking((EntityEnergyDome) barrier, caster, target)) return true; + } else if (barrier instanceof EntityEnergyPanel) { + if (isPanelBlocking((EntityEnergyPanel) barrier, caster, target)) return true; } } @@ -2417,7 +2502,7 @@ public abstract class Ability implements IAbility, IAbilityAction { * Check if a dome blocks an attack from caster to target. * Blocks when caster is outside and target is inside the dome. */ - private static boolean isDomeBlocking(EntityAbilityDome dome, EntityLivingBase caster, EntityLivingBase target) { + private static boolean isDomeBlocking(EntityEnergyDome dome, EntityLivingBase caster, EntityLivingBase target) { float radius = dome.getDomeRadius(); double cdx = caster.posX - dome.posX; @@ -2438,7 +2523,7 @@ public abstract class Ability implements IAbility, IAbilityAction { * Check if a panel blocks an attack from caster to target. * Checks if the line from caster to target crosses through the panel bounds. */ - private static boolean isPanelBlocking(EntityAbilityPanel panel, EntityLivingBase caster, EntityLivingBase target) { + private static boolean isPanelBlocking(EntityEnergyPanel panel, EntityLivingBase caster, EntityLivingBase target) { float halfW = panel.getPanelData().panelWidth * 0.5f; float halfH = panel.getPanelData().panelHeight * 0.5f; @@ -2497,11 +2582,35 @@ public abstract class Ability implements IAbility, IAbilityAction { @Override public INbt getNbt() { - return NpcAPI.Instance().getINbt(writeNBT()); + return NpcAPI.Instance().getINbt(writeNBT(false)); } @Override public void setNbt(INbt nbt) { readNBT(nbt.getMCNBT()); } + + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT HANDLER + // ═══════════════════════════════════════════════════════════════════ + + public AbilityScript getScriptHandler() { + if (this.id == null || this.id.isEmpty()) return null; + return AbilityController.Instance.abilityScriptHandlers.get(this.id); + } + + public void setScriptHandler(AbilityScript handler) { + if (this.id == null || this.id.isEmpty()) return; + AbilityController.Instance.abilityScriptHandlers.put(this.id, handler); + } + + public AbilityScript getOrCreateScriptHandler() { + if (this.id == null || this.id.isEmpty()) return null; + AbilityScript handler = getScriptHandler(); + if (handler == null) { + handler = new AbilityScript(this.id); + AbilityController.Instance.abilityScriptHandlers.put(this.id, handler); + } + return handler; + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java index aadca44a3..571b2fd35 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityAction.java @@ -218,7 +218,7 @@ public class AbilityAction { Ability resolved = getAbility(); if (resolved == null) return false; - inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT()); + inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT(true)); slotType = SlotType.INLINE_ABILITY; referenceId = null; cachedAction = null; @@ -245,12 +245,12 @@ public class AbilityAction { // NBT // ═══════════════════════════════════════════════════════════════════ - public NBTTagCompound writeNBT() { + public NBTTagCompound writeNBT(boolean saveScripts) { switch (slotType) { case INLINE_CHAIN: { NBTTagCompound nbt = new NBTTagCompound(); if (inlineChain != null) { - nbt.setTag("InlineChain", inlineChain.writeNBT()); + nbt.setTag("InlineChain", inlineChain.writeNBT(saveScripts)); } return nbt; } @@ -275,7 +275,7 @@ public class AbilityAction { case INLINE_ABILITY: default: - return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound(); + return inlineAbility != null ? inlineAbility.writeNBT(saveScripts) : new NBTTagCompound(); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/CustomAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/CustomAbility.java new file mode 100644 index 000000000..c59eb9765 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/CustomAbility.java @@ -0,0 +1,165 @@ +package kamkeel.npcs.controllers.data.ability; + +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.ICustomAbility; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * A blank-slate ability that does nothing by itself. + * All behavior is driven by script event hooks (abilityStart, abilityTick, abilityComplete, + * abilityToggle, abilityToggleTick). + *

+ * Supports two modes based on toggle configuration: + *

    + *
  • Instant mode (toggleStates = 0): Uses standard execution lifecycle with + * configurable duration. Script hooks: abilityStart, abilityTick, abilityComplete.
  • + *
  • Toggle mode (toggleStates >= 1): Uses toggle lifecycle. + * Script hooks: abilityToggle, abilityToggleTick.
  • + *
+ */ +public class CustomAbility extends Ability implements ICustomAbility { + + private int durationTicks = 20; + + public CustomAbility() { + this.typeId = "ability.cnpc.custom"; + this.name = "Custom"; + this.targetingMode = TargetingMode.SELF; + this.lockMovement = LockMode.NO; + this.cooldownTicks = 0; + this.windUpTicks = 0; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + } + + // ==================== EXECUTION ==================== + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (durationTicks <= 0) { + signalCompletion(); + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (durationTicks > 0 && tick >= durationTicks) { + signalCompletion(); + } + } + + // ==================== PROPERTIES ==================== + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean isConcurrentCapable() { + return true; + } + + @Override + public boolean isTargetingModeLocked() { + return false; + } + + @Override + public boolean allowFreeOnCast() { + return true; + } + + // ==================== FIELDS ==================== + + @Override + public int getDurationTicks() { + return durationTicks; + } + + @Override + public void setDurationTicks(int ticks) { + this.durationTicks = Math.max(0, ticks); + } + + // ==================== ICustomAbility ==================== + + @Override + public int getTelegraphShapeType() { + return getTelegraphType().ordinal(); + } + + @Override + public void setTelegraphShapeType(int type) { + TelegraphType[] values = TelegraphType.values(); + if (type >= 0 && type < values.length) { + setTelegraphType(values[type]); + } + } + + @Override + public int getTargetingModeType() { + return getTargetingMode().ordinal(); + } + + @Override + public void setTargetingModeType(int type) { + TargetingMode[] values = TargetingMode.values(); + if (type >= 0 && type < values.length) { + setTargetingMode(values[type]); + } + } + + // ==================== NBT ==================== + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + this.durationTicks = nbt.getInteger("durationTicks"); + } + + // ==================== GUI ==================== + + @Override + public void getAbilityDefinitions(List defs) { + // User Type (NPC / Player / Both) + defs.add(FieldDef.enumField("ability.allowedBy", UserType.class, + this::getAllowedBy, this::setAllowedBy)); + + // Targeting Mode + defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, + this::getTargetingMode, this::setTargetingMode)); + + // Telegraph Shape + defs.add(FieldDef.enumField("ability.telegraphShape", TelegraphType.class, + this::getTelegraphType, this::setTelegraphType)); + + // Toggle section + defs.add(FieldDef.section("ability.section.toggle")); + defs.add(FieldDef.boolField("ability.toggleEnabled", + this::isToggleable, enabled -> setToggleStates(enabled ? Math.max(1, getToggleStates()) : 0))); + defs.add(FieldDef.intField("ability.toggleStates", this::getToggleStates, this::setToggleStates) + .range(1, 10) + .visibleWhen(this::isToggleable)); + defs.add(FieldDef.boolField("ability.hasActiveToggle", this::hasActiveToggle, this::setHasActiveToggle) + .visibleWhen(this::isToggleable)); + + // Duration (instant mode only) + defs.add(FieldDef.section("ability.section.execution") + .visibleWhen(() -> !this.isToggleable())); + defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) + .range(0, 6000) + .visibleWhen(() -> !this.isToggleable())); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java index df6d01e04..552bb5de9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/conditions/ConditionItem.java @@ -137,21 +137,19 @@ public class ConditionItem extends AbilityCondition { this::getUsageType, this::setUsageType)); defs.add(FieldDef.stringField("condition.item_name", - this::getItemName, this::setItemName)); -// .hover("condition.hover.item_name")); - - + this::getItemName, this::setItemName) + .hover("condition.hover.item_name")); defs.add(FieldDef.enumField("condition.armor_slot", ArmorSlot.class, this::getArmorSlot, this::setArmorSlot) - .visibleWhen(() -> usageType == UsageType.ARMOR)); -// .hover("condition.hover.armor_slots")); + .visibleWhen(() -> usageType == UsageType.ARMOR) + .hover("condition.hover.armor_slots")); defs.add(FieldDef.intField("condition.item_count", this::getRequiredCount, this::setRequiredCount) .range(1, 64) - .visibleWhen(() -> usageType == UsageType.AMMO && userType.allowsPlayer())); -// .hover("condition.hover.required_count")); + .visibleWhen(() -> usageType == UsageType.AMMO && userType.allowsPlayer()) + .hover("condition.hover.required_count")); } @SideOnly(Side.CLIENT) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java index 77dd746ea..8efb25791 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/AbilityIconData.java @@ -6,24 +6,72 @@ import net.minecraft.nbt.NBTTagList; /** * Icon data for abilities, stored in the ability's customData NBT under "AbilityIcon". - * Used to render ability icons in the Ability Hotbar, Wheel, and Abilities Tab. + * Supports up to 3 layers, each with its own texture, UV coordinates, and tint color. + * Width, height, and scale are shared across all layers. */ public class AbilityIconData { public static final String NBT_KEY = "AbilityIcon"; + public static final int MAX_LAYERS = 3; private final NBTTagCompound customData; - // Icon properties - public String texture = ""; - public int iconX = 0; - public int iconY = 0; + // Shared across all layers public int width = 32; public int height = 32; public float scale = 1.0f; - /** Per-state icon UV overrides (0-indexed, maps to toggle states 1, 2, ...). */ + /** Whether a custom icon override is active. Default false = use type's default icon. */ + private boolean enabled = false; + + /** Number of active layers (1-3). */ + private int layerCount = 1; + + /** Layer data (always 3 slots allocated). */ + private Layer[] layers = { new Layer(), new Layer(), new Layer() }; + + /** Per-state icon UV overrides for layer 0 (0-indexed, maps to toggle states 1, 2, ...). */ private int[][] stateIcons = null; + // Animation + private boolean animated = false; + private int frameCount = 1; + private int frametime = 2; + + // ═══════════════════════════════════════════════════════════════════ + // LAYER INNER CLASS + // ═══════════════════════════════════════════════════════════════════ + + public static class Layer { + public String texture = ""; + public int iconX = 0; + public int iconY = 0; + public int tintColor = 0xFFFFFF; + + public Layer() {} + + public boolean hasTexture() { + return texture != null && !texture.isEmpty(); + } + + public void writeToNBT(NBTTagCompound nbt) { + nbt.setString("Texture", texture); + nbt.setInteger("IconX", iconX); + nbt.setInteger("IconY", iconY); + nbt.setInteger("TintColor", tintColor); + } + + public void readFromNBT(NBTTagCompound nbt) { + texture = nbt.getString("Texture"); + iconX = nbt.getInteger("IconX"); + iconY = nbt.getInteger("IconY"); + tintColor = nbt.hasKey("TintColor") ? nbt.getInteger("TintColor") : 0xFFFFFF; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // CONSTRUCTION + // ═══════════════════════════════════════════════════════════════════ + private AbilityIconData(NBTTagCompound customData) { this.customData = customData; } @@ -54,6 +102,10 @@ public class AbilityIconData { return fromCustomData(chain.getCustomData()); } + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + /** * Write current state back to the customData NBT. */ @@ -64,12 +116,24 @@ public class AbilityIconData { } public void writeToNBT(NBTTagCompound nbt) { - nbt.setString("Texture", texture); - nbt.setInteger("IconX", iconX); - nbt.setInteger("IconY", iconY); + nbt.setBoolean("Enabled", enabled); nbt.setInteger("Width", width); nbt.setInteger("Height", height); nbt.setFloat("Scale", scale); + nbt.setInteger("LayerCount", layerCount); + + NBTTagList layerList = new NBTTagList(); + for (int i = 0; i < MAX_LAYERS; i++) { + NBTTagCompound layerNBT = new NBTTagCompound(); + layers[i].writeToNBT(layerNBT); + layerList.appendTag(layerNBT); + } + nbt.setTag("Layers", layerList); + + nbt.setBoolean("Animated", animated); + nbt.setInteger("FrameCount", frameCount); + nbt.setInteger("FrameTime", frametime); + if (stateIcons != null && stateIcons.length > 0) { NBTTagList list = new NBTTagList(); for (int[] pair : stateIcons) { @@ -83,15 +147,35 @@ public class AbilityIconData { } public void readFromNBT(NBTTagCompound nbt) { - texture = nbt.getString("Texture"); - iconX = nbt.getInteger("IconX"); - iconY = nbt.getInteger("IconY"); + enabled = nbt.getBoolean("Enabled"); width = nbt.getInteger("Width"); if (width <= 0) width = 32; height = nbt.getInteger("Height"); if (height <= 0) height = 32; scale = nbt.getFloat("Scale"); if (scale <= 0) scale = 1.0f; + + layerCount = nbt.getInteger("LayerCount"); + if (layerCount < 1) layerCount = 1; + if (layerCount > MAX_LAYERS) layerCount = MAX_LAYERS; + + if (nbt.hasKey("Animated")) + animated = nbt.getBoolean("Animated"); + if (nbt.hasKey("FrameCount")) + frameCount = Math.max(1, nbt.getInteger("FrameCount")); + if (nbt.hasKey("FrameTime")) + frametime = Math.max(1, nbt.getInteger("FrameTime")); + + if (nbt.hasKey("Layers")) { + NBTTagList layerList = nbt.getTagList("Layers", 10); + for (int i = 0; i < MAX_LAYERS; i++) { + layers[i] = new Layer(); + if (i < layerList.tagCount()) { + layers[i].readFromNBT(layerList.getCompoundTagAt(i)); + } + } + } + if (nbt.hasKey("StateIcons")) { NBTTagList list = nbt.getTagList("StateIcons", 10); stateIcons = new int[list.tagCount()][2]; @@ -103,41 +187,61 @@ public class AbilityIconData { } } - /** - * Check if this icon has a valid texture configured. - */ - public boolean hasTexture() { - return texture != null && !texture.isEmpty(); - } - // ═══════════════════════════════════════════════════════════════════ - // GETTERS AND SETTERS (with auto-save) + // LAYER API // ═══════════════════════════════════════════════════════════════════ - public String getTexture() { - return texture; + public int getLayerCount() { + return layerCount; } - public void setTexture(String texture) { - this.texture = texture != null ? texture : ""; + public void setLayerCount(int count) { + this.layerCount = Math.max(1, Math.min(MAX_LAYERS, count)); save(); } - public int getIconX() { - return iconX; + public Layer getLayer(int index) { + return (index >= 0 && index < MAX_LAYERS) ? layers[index] : layers[0]; } - public void setIconX(int iconX) { - this.iconX = Math.max(0, iconX); - save(); + public void setLayerTexture(int index, String tex) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].texture = tex != null ? tex : ""; + save(); + } } - public int getIconY() { - return iconY; + public void setLayerIconX(int index, int x) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].iconX = Math.max(0, x); + save(); + } } - public void setIconY(int iconY) { - this.iconY = Math.max(0, iconY); + public void setLayerIconY(int index, int y) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].iconY = Math.max(0, y); + save(); + } + } + + public void setLayerTintColor(int index, int color) { + if (index >= 0 && index < MAX_LAYERS) { + layers[index].tintColor = color & 0xFFFFFF; + save(); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // SHARED PROPERTY GETTERS/SETTERS (with auto-save) + // ═══════════════════════════════════════════════════════════════════ + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; save(); } @@ -169,7 +273,38 @@ public class AbilityIconData { } // ═══════════════════════════════════════════════════════════════════ - // PER-STATE ICON OVERRIDES + // ANIMATION + // ═══════════════════════════════════════════════════════════════════ + + public boolean isAnimated() { + return animated; + } + + public void setAnimated(boolean animated) { + this.animated = animated; + save(); + } + + public int getFrameCount() { + return frameCount; + } + + public void setFrameCount(int frameCount) { + this.frameCount = Math.max(1, frameCount); + save(); + } + + public int getFrameTime() { + return frametime; + } + + public void setFrameTime(int frametime) { + this.frametime = Math.max(1, frametime); + save(); + } + + // ═══════════════════════════════════════════════════════════════════ + // PER-STATE ICON OVERRIDES (applies to layer 0) // ═══════════════════════════════════════════════════════════════════ public void setStateIcons(int[][] stateIcons) { @@ -178,26 +313,26 @@ public class AbilityIconData { } /** - * Get iconX for a specific toggle state. - * Falls back to default iconX if no state override exists. + * Get iconX for a specific toggle state (layer 0). + * Falls back to layer 0 iconX if no state override exists. * @param state 1-indexed toggle state (0 = off/default) */ public int getIconXForState(int state) { if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { return stateIcons[state - 1][0]; } - return iconX; + return layers[0].iconX; } /** - * Get iconY for a specific toggle state. - * Falls back to default iconY if no state override exists. + * Get iconY for a specific toggle state (layer 0). + * Falls back to layer 0 iconY if no state override exists. * @param state 1-indexed toggle state (0 = off/default) */ public int getIconYForState(int state) { if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) { return stateIcons[state - 1][1]; } - return iconY; + return layers[0].iconY; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java index 5390e0c1a..e3aa63346 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ChainedAbility.java @@ -2,6 +2,7 @@ package kamkeel.npcs.controllers.data.ability.data; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; +import noppes.npcs.controllers.data.ChainedAbilityScript; import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; import kamkeel.npcs.controllers.data.ability.enums.UserType; import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; @@ -358,7 +359,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { */ public ChainedAbility deepCopy() { ChainedAbility copy = new ChainedAbility(); - copy.readNBT(this.writeNBT()); + copy.readNBT(this.writeNBT(true)); return copy; } @@ -376,7 +377,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { // NBT SERIALIZATION // ═══════════════════════════════════════════════════════════════════ - public NBTTagCompound writeNBT() { + public NBTTagCompound writeNBT(boolean saveScripts) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setString("Id", id); nbt.setString("Name", name); @@ -398,13 +399,23 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { // Entries NBTTagList entryList = new NBTTagList(); for (ChainedAbilityEntry entry : entries) { - entryList.appendTag(entry.writeNBT()); + entryList.appendTag(entry.writeNBT(saveScripts)); } nbt.setTag("Entries", entryList); // Custom data (for external mods) nbt.setTag("customData", (NBTTagCompound) customData.copy()); + // Script handler data (matching CustomEffect.writeToNBT pattern) + if (saveScripts) { + ChainedAbilityScript handler = getScriptHandler(); + if (handler != null) { + NBTTagCompound scriptData = new NBTTagCompound(); + handler.writeToNBT(scriptData); + nbt.setTag("ScriptData", scriptData); + } + } + return nbt; } @@ -418,7 +429,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { cooldownTicks = nbt.hasKey("CooldownTicks") ? nbt.getInteger("CooldownTicks") : 100; minRange = nbt.getFloat("MinRange"); maxRange = nbt.hasKey("MaxRange") ? nbt.getFloat("MaxRange") : 20; - // AllowedBy is computed from child abilities — old NBT data silently ignored + // AllowedBy is computed from child abilities // Conditions conditions.clear(); @@ -442,5 +453,33 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction { // Custom data (for external mods) customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy(); + + // Script handler data (matching CustomEffect.readFromNBT pattern) + if (nbt.hasKey("ScriptData", 10)) { + ChainedAbilityScript handler = new ChainedAbilityScript(this.id); + handler.readFromNBT(nbt.getCompoundTag("ScriptData")); + setScriptHandler(handler); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT HANDLER + // ═══════════════════════════════════════════════════════════════════ + + public ChainedAbilityScript getScriptHandler() { + return AbilityController.Instance.chainedAbilityScriptHandlers.get(this.id); + } + + public void setScriptHandler(ChainedAbilityScript handler) { + AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler); + } + + public ChainedAbilityScript getOrCreateScriptHandler() { + ChainedAbilityScript handler = getScriptHandler(); + if (handler == null) { + handler = new ChainedAbilityScript(this.id); + AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler); + } + return handler; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java index 59a296f7b..341fdd061 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/IAbilityAction.java @@ -50,5 +50,5 @@ public interface IAbilityAction { */ IAbilityAction deepCopyAction(); - NBTTagCompound writeNBT(); + NBTTagCompound writeNBT(boolean saveScripts); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java index 1217c85d5..bfd48a3b3 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyBarrierData.java @@ -40,6 +40,7 @@ public class EnergyBarrierData { // Reflection: rebound projectiles that fail to break the barrier public boolean reflect = false; public float reflectStrengthPct = 25.0f; + public boolean targetOwner = false; /** * Per-projectile-type damage multipliers. @@ -139,6 +140,14 @@ public class EnergyBarrierData { this.reflectStrengthPct = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct)); } + public boolean isTargetOwner() { + return targetOwner; + } + + public void setTargetOwner(boolean targetOwner) { + this.targetOwner = targetOwner; + } + // ==================== NBT ==================== public void writeNBT(NBTTagCompound nbt) { @@ -155,6 +164,7 @@ public class EnergyBarrierData { nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier); nbt.setBoolean("barrierReflect", reflect); nbt.setFloat("barrierReflectStrPct", reflectStrengthPct); + nbt.setBoolean("barrierTargetOwner", targetOwner); NBTTagCompound multNbt = new NBTTagCompound(); for (Map.Entry entry : damageMultipliers.entrySet()) { @@ -177,6 +187,7 @@ public class EnergyBarrierData { meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f; reflect = nbt.hasKey("barrierReflect") && nbt.getBoolean("barrierReflect"); setReflectStrengthPct(nbt.hasKey("barrierReflectStrPct") ? nbt.getFloat("barrierReflectStrPct") : 25.0f); + targetOwner = nbt.hasKey("barrierTargetOwner") && nbt.getBoolean("barrierTargetOwner"); damageMultipliers.clear(); if (nbt.hasKey("barrierMultipliers")) { @@ -200,6 +211,7 @@ public class EnergyBarrierData { copy.meleeDamageMultiplier = meleeDamageMultiplier; copy.reflect = reflect; copy.reflectStrengthPct = reflectStrengthPct; + copy.targetOwner = targetOwner; copy.damageMultipliers = new HashMap<>(damageMultipliers); return copy; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java index f15f31b6d..72bcffbb8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyDisplayData.java @@ -16,10 +16,6 @@ public class EnergyDisplayData implements IEnergyDisplayData { public float innerAlpha = 1.0f; public float rotationSpeed = 4.0f; - // TODO: Skybox Feature - // public boolean skyboxEnabled = false; - // public String skyboxTexture = ""; - public EnergyDisplayData() { } @@ -122,9 +118,6 @@ public class EnergyDisplayData implements IEnergyDisplayData { nbt.setFloat("outerColorAlpha", outerColorAlpha); nbt.setFloat("innerAlpha", innerAlpha); nbt.setFloat("rotationSpeed", rotationSpeed); - // TODO: Skybox Feature - // nbt.setBoolean("skyboxEnabled", skyboxEnabled); - // nbt.setString("skyboxTexture", skyboxTexture); } public void readNBT(NBTTagCompound nbt) { @@ -135,16 +128,10 @@ public class EnergyDisplayData implements IEnergyDisplayData { outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; innerAlpha = nbt.hasKey("innerAlpha") ? nbt.getFloat("innerAlpha") : 1.0f; rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; - // TODO: Skybox Feature - // skyboxEnabled = nbt.hasKey("skyboxEnabled") && nbt.getBoolean("skyboxEnabled"); - // skyboxTexture = nbt.hasKey("skyboxTexture") ? nbt.getString("skyboxTexture") : ""; } public EnergyDisplayData copy() { EnergyDisplayData copy = new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, innerAlpha, rotationSpeed); - // TODO: Skybox Feature - // copy.skyboxEnabled = skyboxEnabled; - // copy.skyboxTexture = skyboxTexture; return copy; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java index c57e0bbf5..aaef76cf6 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/energy/EnergyPanelData.java @@ -10,6 +10,8 @@ public class EnergyPanelData { public float panelWidth = 3.0f; public float panelHeight = 3.0f; public float heightOffset = 0.0f; + public float offsetX = 0.0f; + public float offsetZ = 0.0f; // Launch properties (Wall only) public boolean launching = false; @@ -90,6 +92,8 @@ public class EnergyPanelData { nbt.setFloat("panelWidth", panelWidth); nbt.setFloat("panelHeight", panelHeight); nbt.setFloat("panelHeightOffset", heightOffset); + nbt.setFloat("panelOffsetX", offsetX); + nbt.setFloat("panelOffsetZ", offsetZ); nbt.setBoolean("panelLaunching", launching); nbt.setFloat("panelLaunchSpeed", launchSpeed); nbt.setFloat("panelLaunchDamage", launchDamage); @@ -100,6 +104,8 @@ public class EnergyPanelData { panelWidth = nbt.hasKey("panelWidth") ? nbt.getFloat("panelWidth") : 3.0f; panelHeight = nbt.hasKey("panelHeight") ? nbt.getFloat("panelHeight") : 3.0f; heightOffset = nbt.hasKey("panelHeightOffset") ? nbt.getFloat("panelHeightOffset") : 0.0f; + offsetX = nbt.hasKey("panelOffsetX") ? nbt.getFloat("panelOffsetX") : 0.0f; + offsetZ = nbt.hasKey("panelOffsetZ") ? nbt.getFloat("panelOffsetZ") : 0.0f; launching = nbt.hasKey("panelLaunching") && nbt.getBoolean("panelLaunching"); launchSpeed = nbt.hasKey("panelLaunchSpeed") ? nbt.getFloat("panelLaunchSpeed") : 0.5f; launchDamage = nbt.hasKey("panelLaunchDamage") ? nbt.getFloat("panelLaunchDamage") : 8.0f; @@ -108,6 +114,8 @@ public class EnergyPanelData { public EnergyPanelData copy() { EnergyPanelData copy = new EnergyPanelData(panelWidth, panelHeight, heightOffset); + copy.offsetX = offsetX; + copy.offsetZ = offsetZ; copy.launching = launching; copy.launchSpeed = launchSpeed; copy.launchDamage = launchDamage; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java index 85fa819ff..0e7b4bf97 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/entry/ChainedAbilityEntry.java @@ -155,7 +155,7 @@ public class ChainedAbilityEntry { Ability resolved = ctrl.resolveAbility(abilityReference); if (resolved == null) return false; - inlineAbility = ctrl.fromNBT(resolved.writeNBT()); + inlineAbility = ctrl.fromNBT(resolved.writeNBT(true)); entryType = EntryType.INLINE; abilityReference = ""; return true; @@ -175,22 +175,22 @@ public class ChainedAbilityEntry { copy.delayTicks = this.delayTicks; copy.concurrentEnabled = this.concurrentEnabled; if (this.inlineAbility != null) { - copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT()); + copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT(true)); } return copy; } // ═══════════════════════════════════════════════════════════════════ - // NBT (backwards compatible) + // NBT // ═══════════════════════════════════════════════════════════════════ - public NBTTagCompound writeNBT() { + public NBTTagCompound writeNBT(boolean saveScripts) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("Delay", delayTicks); nbt.setBoolean("Concurrent", concurrentEnabled); if (entryType == EntryType.INLINE && inlineAbility != null) { - nbt.setTag("InlineAbility", inlineAbility.writeNBT()); + nbt.setTag("InlineAbility", inlineAbility.writeNBT(saveScripts)); } else { nbt.setString("Reference", abilityReference); } @@ -204,14 +204,12 @@ public class ChainedAbilityEntry { entry.delayTicks = Math.max(0, nbt.getInteger("Delay")); entry.concurrentEnabled = nbt.hasKey("Concurrent") ? nbt.getBoolean("Concurrent") : true; - // Inline entry (new format) if (nbt.hasKey("InlineAbility")) { NBTTagCompound abilityNBT = nbt.getCompoundTag("InlineAbility"); entry.entryType = EntryType.INLINE; entry.inlineAbility = AbilityController.Instance != null ? AbilityController.Instance.fromNBT(abilityNBT) : null; } else { - // Reference entry (old + new format) entry.entryType = EntryType.REFERENCE; entry.abilityReference = nbt.getString("Reference"); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java index 93c8f1b73..aa2f5492f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/preview/AbilityPreviewExecutor.java @@ -137,7 +137,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler { for (ChainedAbilityEntry entry : chain.getEntries()) { Ability resolved = entry.resolve(); if (resolved != null && AbilityController.Instance != null) { - Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT()); + Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT(true)); if (copy != null) { chainAbilities.add(copy); chainDelays.add(entry.getDelayTicks()); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index da7e60344..4ad6811d5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -53,6 +53,9 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge { this.activeSound = "mob.zombie.attack"; this.windUpAnimationName = "Ability_Charge_Windup"; this.activeAnimationName = "Ability_Charge_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/charge.png") + }; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java new file mode 100644 index 000000000..f0d5ab4b6 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCounter.java @@ -0,0 +1,215 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.addon.DBCAddon; +import noppes.npcs.controllers.AnimationController; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import noppes.npcs.NpcDamageSource; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.api.ability.type.IAbilityCounter; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.Arrays; +import java.util.List; + +/** + * Counter ability: Absorbs incoming damage and counter-attacks the attacker. + */ +public class AbilityCounter extends AbilityDefend implements IAbilityCounter { + + private CounterType counterType = CounterType.FLAT; + private float counterValue = 6.0f; + private int counterAnimationId = -1; + private String counterAnimationName = "Ability_Guard_Counter"; + + public AbilityCounter() { + this.typeId = "ability.cnpc.counter"; + this.name = "Counter"; + this.cooldownTicks = 0; + this.windUpTicks = 20; + this.allowedBy = UserType.BOTH; + this.activeSound = "random.anvil_land"; + + this.activeAnimationName = "Ability_Guard_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png") + }; + } + + public enum CounterType { + FLAT, + PERCENT; + + @Override + public String toString() { + switch (this) { + case FLAT: + return "ability.counter.flat"; + case PERCENT: + return "ability.counter.percent"; + default: + return name(); + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOKS + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected float performDefend(EntityLivingBase attacker, float amount) { + // Calculate counter damage + float damage; + if (counterType == CounterType.FLAT) { + damage = counterValue; + } else { + damage = amount * (counterValue / 100.0f); + } + + // Hit back + if (caster != null && attacker.isEntityAlive()) { + if (caster instanceof EntityNPCInterface && DBCAddon.instance.canDBCAttack((EntityNPCInterface) caster, damage, attacker)) { + // NPC with DBC: dummy hit for events/knockback, then apply DBC damage with NPC's stats + attacker.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), 0.001f); + DBCAddon.instance.doDBCDamage((EntityNPCInterface) caster, damage, attacker); + } else { + // Player or non-DBC NPC: normal damage + DamageSource counterSource = caster instanceof EntityPlayer + ? DamageSource.causePlayerDamage((EntityPlayer) caster) + : DamageSource.causeMobDamage(caster); + attacker.attackEntityFrom(counterSource, damage); + } + } + + return 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean hasDamage() { + return true; + } + + @Override + protected Animation getDefendAnimation() { + return getCounterAnimation(); + } + + public Animation getCounterAnimation() { + if (AnimationController.Instance == null) return null; + if (counterAnimationId >= 0) { + return (Animation) AnimationController.Instance.get(counterAnimationId); + } + if (counterAnimationName != null && !counterAnimationName.isEmpty()) { + return (Animation) AnimationController.Instance.get(counterAnimationName, true); + } + return null; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void writeSubTypeNBT(NBTTagCompound nbt) { + nbt.setString("counterType", counterType.name()); + nbt.setFloat("counterValue", counterValue); + nbt.setInteger("counterAnimationId", counterAnimationId); + nbt.setString("counterAnimationName", resolveAnimationName(counterAnimationId, counterAnimationName)); + } + + @Override + protected void readSubTypeNBT(NBTTagCompound nbt) { + try { + this.counterType = CounterType.valueOf(nbt.getString("counterType")); + } catch (Exception e) { + this.counterType = CounterType.FLAT; + } + this.counterValue = nbt.getFloat("counterValue"); + this.counterAnimationId = nbt.getInteger("counterAnimationId"); + this.counterAnimationName = nbt.getString("counterAnimationName"); + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + protected void getTypeDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.enumField("gui.type", CounterType.class, this::getCounterTypeEnum, this::setCounterTypeEnum) + .hover("ability.hover.counterType"), + FieldDef.floatField("gui.value", this::getCounterValue, this::setCounterValue), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + + FieldDef.insertAfter(defs, "ability.dazedAnimation", + FieldDef.animSubGui("ability.counterAnimation", + this::getCounterAnimationId, this::setCounterAnimationId, + this::getCounterAnimationName, this::setCounterAnimationName) + .tab("Effects")); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public CounterType getCounterTypeEnum() { + return counterType; + } + + public void setCounterTypeEnum(CounterType counterType) { + this.counterType = counterType; + } + + @Override + public int getCounterType() { + return counterType.ordinal(); + } + + @Override + public void setCounterType(int type) { + CounterType[] values = CounterType.values(); + this.counterType = type >= 0 && type < values.length ? values[type] : CounterType.FLAT; + } + + @Override + public float getCounterValue() { + return counterValue; + } + + @Override + public void setCounterValue(float counterValue) { + this.counterValue = counterValue; + } + + @Override + public int getCounterAnimationId() { + return counterAnimationId; + } + + @Override + public void setCounterAnimationId(int counterAnimationId) { + this.counterAnimationId = counterAnimationId; + } + + public String getCounterAnimationName() { + return counterAnimationName; + } + + public void setCounterAnimationName(String name) { + this.counterAnimationName = name != null ? name : ""; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index c7b88961e..2fdc8fd48 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -79,6 +79,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter { this.activeSound = "random.break"; this.windUpAnimationName = "Ability_Cutter_Windup"; this.activeAnimationName = "Ability_Cutter_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/cutter.png", + this::getActiveColor) + }; } @Override @@ -294,12 +298,6 @@ public class AbilityCutter extends Ability implements IAbilityCutter { return entityRelative >= minAngle && entityRelative <= maxAngle; } - private boolean isInArc(double dx, double dz, float casterYaw, float arcWidth) { - double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); - double angleDiff = normalizeAngle(angleToEntity - casterYaw); - return Math.abs(angleDiff) <= arcWidth / 2.0; - } - private double normalizeAngle(double angle) { while (angle > 180) angle -= 360; while (angle < -180) angle += 360; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java index 2757bbf18..88c520c21 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -144,6 +144,9 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { this.telegraphType = TelegraphType.NONE; this.showTelegraph = false; this.windUpSound = "mob.bat.takeoff"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/dash.png") + }; } @Override @@ -302,7 +305,7 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; this.dashSpeed = nbt.hasKey("dashSpeed") ? Math.max(0.01f, nbt.getFloat("dashSpeed")) : 0.5f; - this.dashAngle = nbt.hasKey("dashAngle") ? Math.max(0.01f, nbt.getFloat("dashAngle")) : 0.0f; + this.dashAngle = nbt.hasKey("dashAngle") ? nbt.getFloat("dashAngle") : 0.0f; } // Getters & Setters @@ -394,7 +397,7 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash { FieldDef.row( FieldDef.enumField("ability.dashDirection", DashDirection.class, this::getDashDirectionEnum, this::setDashDirectionEnum), FieldDef.floatField("ability.dashAngle", this::getDashAngle, this::setDashAngle) - .visibleWhen(() -> getDashDirectionEnum() == DashDirection.CUSTOM) + .min(Float.NEGATIVE_INFINITY).visibleWhen(() -> getDashDirectionEnum() == DashDirection.CUSTOM) ).visibleWhen(() -> this.getDashModeEnum() == DashMode.DIRECTIONAL) )); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java new file mode 100644 index 000000000..c9f6e1e0a --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDefend.java @@ -0,0 +1,299 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.enums.LockMode; +import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.ability.type.IAbilityDefend; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.controllers.data.Animation; + +import java.util.List; + +/** + * Abstract base class for defensive abilities (Guard, Counter, Dodge). + *

+ * {@link #onDefend} handles shared checks (physical melee only) then delegates + * to {@link #performDefend(EntityLivingBase, float)} which subclasses override for their specific behavior. + */ +public abstract class AbilityDefend extends Ability implements IAbilityDefend { + + // ═══════════════════════════════════════════════════════════════════ + // SHARED PERSIST STATE + // ═══════════════════════════════════════════════════════════════════ + + protected int durationTicks = 60; + protected int maxHitAmount = 3; + + // ═══════════════════════════════════════════════════════════════════ + // TRANSIENT RUNTIME STATE + // ═══════════════════════════════════════════════════════════════════ + + protected transient EntityLivingBase caster; + protected transient int hitCount; + protected transient EntityLivingBase lastAttacker; + protected transient float lastDamageTaken; + protected transient Animation pendingDefendAnimation; + protected transient int defendAnimEndTick = -1; + + // ═══════════════════════════════════════════════════════════════════ + // CONSTRUCTOR DEFAULTS + // ═══════════════════════════════════════════════════════════════════ + + protected AbilityDefend() { + this.targetingMode = TargetingMode.SELF; + this.lockMovement = LockMode.ACTIVE; + this.interruptible = false; + this.telegraphType = TelegraphType.NONE; + this.showTelegraph = false; + this.windUpTicks = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // LIFECYCLE + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + this.caster = caster; + hitCount = 0; + lastAttacker = null; + lastDamageTaken = 0.0f; + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (tick >= durationTicks) { + signalCompletion(); + } + } + + @Override + public void reset() { + super.reset(); + caster = null; + hitCount = 0; + lastAttacker = null; + lastDamageTaken = 0.0f; + pendingDefendAnimation = null; + defendAnimEndTick = -1; + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOK + // ═══════════════════════════════════════════════════════════════════ + + /** + * Called when the caster is hit while defending. + * Checks for physical melee damage only, then delegates to {@link #performDefend(float)}. + * + * @param attacker The entity that hit the caster + * @param source The damage source + * @param amount The original incoming damage + * @return The modified damage to apply (unchanged if not physical melee) + */ + public final float onDefend(EntityLivingBase attacker, DamageSource source, float amount) { + if (!isDefending()) + return amount; + if (attacker == null || source == null) + return amount; + + // Only react to physical melee damage + if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion() || source.isProjectile()) + return amount; + + lastAttacker = attacker; + lastDamageTaken = amount; + hitCount++; + + float result = performDefend(attacker, amount); + + // Queue defend reaction animation (played on next tick by AbstractDataAbilities) + pendingDefendAnimation = getDefendAnimation(); + + // Auto-complete after max hits + if (maxHitAmount > 0 && hitCount >= maxHitAmount) { + signalCompletion(); + } + + return result; + } + + /** + * Subclass-specific defend behavior. Called only for physical melee hits while defending. + * + * @param attacker The entity that hit the caster + * @param amount The incoming damage + * @return The modified damage the caster should take + */ + protected abstract float performDefend(EntityLivingBase attacker, float amount); + + // ═══════════════════════════════════════════════════════════════════ + // SUBCLASS HOOKS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Subclass-specific NBT persistence. + */ + protected abstract void writeSubTypeNBT(NBTTagCompound nbt); + protected abstract void readSubTypeNBT(NBTTagCompound nbt); + + @SideOnly(Side.CLIENT) + protected abstract void getTypeDefinitions(List defs); + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND ANIMATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Returns the animation to play when this defend ability reacts to a hit. + * Subclasses override to provide their specific animation (counter strike, dodge roll, etc). + * Guard returns null (no reaction animation). + */ + protected Animation getDefendAnimation() { + return null; + } + + /** + * Consume and return the pending defend animation (set during onDefend). + * Called by AbstractDataAbilities to play the animation on the next tick. + */ + public Animation consumeDefendAnimation() { + Animation anim = pendingDefendAnimation; + pendingDefendAnimation = null; + return anim; + } + + /** + * Schedule return to active animation after the defend animation finishes. + */ + public void scheduleReturnToActive(int currentTick, Animation defendAnim) { + if (defendAnim != null) { + defendAnimEndTick = currentTick + (int) defendAnim.getTotalTime(); + } + } + + /** + * Check if the defend animation has finished and we should return to the active animation. + */ + public boolean shouldReturnToActiveAnimation(int currentTick) { + if (defendAnimEndTick >= 0 && currentTick >= defendAnimEndTick) { + defendAnimEndTick = -1; + return true; + } + return false; + } + + // ═══════════════════════════════════════════════════════════════════ + // STATE QUERIES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean isDefending() { + return isExecuting() && getPhase() == AbilityPhase.ACTIVE; + } + + // ═══════════════════════════════════════════════════════════════════ + // OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean hasDamage() { + return false; + } + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.SELF}; + } + + @Override + public float getTelegraphRadius() { + return 0; + } + + /** + * Suppresses the auto-play of activeSound on ACTIVE phase entry. + * Defend abilities play their sound on hit reaction, not on phase start. + */ + @Override + public boolean keepTelegraphDuringActive() { + return true; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + public final void writeTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setInteger("maxHitAmount", maxHitAmount); + writeSubTypeNBT(nbt); + } + + @Override + public final void readTypeNBT(NBTTagCompound nbt) { + this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; + this.maxHitAmount = nbt.hasKey("maxHitAmount") ? nbt.getInteger("maxHitAmount") : 3; + readSubTypeNBT(nbt); + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + public final void getAbilityDefinitions(List defs) { + defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 6000)); + defs.add(FieldDef.intField("ability.maxHitAmount", this::getMaxHitAmount, this::setMaxHitAmount).range(0, 100) + .hover("ability.hover.maxHitAmount")); + + getTypeDefinitions(defs); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + @Override + public int getDurationTicks() { + return durationTicks; + } + + @Override + public void setDurationTicks(int ticks) { + this.durationTicks = Math.max(1, ticks); + } + + @Override + public int getMaxHitAmount() { + return maxHitAmount; + } + + @Override + public void setMaxHitAmount(int amount) { + this.maxHitAmount = Math.max(0, amount); + } + + public int getHitCount() { + return hitCount; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDodge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDodge.java new file mode 100644 index 000000000..3c8ef4718 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDodge.java @@ -0,0 +1,195 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import noppes.npcs.controllers.AnimationController; +import kamkeel.npcs.controllers.data.ability.enums.UserType; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.api.ability.type.IAbilityDodge; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.ArrayList; +import java.util.List; + +/** + * Dodge ability: Completely cancels incoming attacks and plays a random dodge animation. + */ +public class AbilityDodge extends AbilityDefend implements IAbilityDodge { + + private int dodgeAnimation1Id = -1; + private String dodgeAnimation1Name = ""; + private int dodgeAnimation2Id = -1; + private String dodgeAnimation2Name = ""; + private int dodgeAnimation3Id = -1; + private String dodgeAnimation3Name = ""; + + public AbilityDodge() { + this.typeId = "ability.cnpc.dodge"; + this.name = "Dodge"; + this.cooldownTicks = 0; + this.windUpTicks = 10; + this.allowedBy = UserType.BOTH; + + this.activeAnimationName = ""; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png") + }; + } + + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOKS + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected float performDefend(EntityLivingBase attacker, float amount) { + return 0; + } + + @Override + protected Animation getDefendAnimation() { + return getRandomDodgeAnimation(); + } + + /** + * Returns a random dodge animation from the configured slots (non-empty only). + */ + public Animation getRandomDodgeAnimation() { + if (AnimationController.Instance == null) return null; + + List available = new ArrayList<>(); + Animation a1 = getDodgeAnimation(dodgeAnimation1Id, dodgeAnimation1Name); + Animation a2 = getDodgeAnimation(dodgeAnimation2Id, dodgeAnimation2Name); + Animation a3 = getDodgeAnimation(dodgeAnimation3Id, dodgeAnimation3Name); + if (a1 != null) available.add(a1); + if (a2 != null) available.add(a2); + if (a3 != null) available.add(a3); + + if (available.isEmpty()) return null; + return available.get((int) (Math.random() * available.size())); + } + + private Animation getDodgeAnimation(int id, String name) { + if (id >= 0) { + return (Animation) AnimationController.Instance.get(id); + } + if (name != null && !name.isEmpty()) { + return (Animation) AnimationController.Instance.get(name, true); + } + return null; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void writeSubTypeNBT(NBTTagCompound nbt) { + nbt.setInteger("dodgeAnimation1Id", dodgeAnimation1Id); + nbt.setString("dodgeAnimation1Name", resolveAnimationName(dodgeAnimation1Id, dodgeAnimation1Name)); + nbt.setInteger("dodgeAnimation2Id", dodgeAnimation2Id); + nbt.setString("dodgeAnimation2Name", resolveAnimationName(dodgeAnimation2Id, dodgeAnimation2Name)); + nbt.setInteger("dodgeAnimation3Id", dodgeAnimation3Id); + nbt.setString("dodgeAnimation3Name", resolveAnimationName(dodgeAnimation3Id, dodgeAnimation3Name)); + } + + @Override + protected void readSubTypeNBT(NBTTagCompound nbt) { + this.dodgeAnimation1Id = nbt.getInteger("dodgeAnimation1Id"); + this.dodgeAnimation1Name = nbt.getString("dodgeAnimation1Name"); + this.dodgeAnimation2Id = nbt.getInteger("dodgeAnimation2Id"); + this.dodgeAnimation2Name = nbt.getString("dodgeAnimation2Name"); + this.dodgeAnimation3Id = nbt.getInteger("dodgeAnimation3Id"); + this.dodgeAnimation3Name = nbt.getString("dodgeAnimation3Name"); + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + protected void getTypeDefinitions(List defs) { + defs.add(FieldDef.section("ability.section.dodgeAnimations")); + + FieldDef.insertAfter(defs, "ability.dazedAnimation", + FieldDef.animSubGui("ability.dodgeAnimation1", + this::getDodgeAnimation1Id, this::setDodgeAnimation1Id, + this::getDodgeAnimation1Name, this::setDodgeAnimation1Name) + .tab("Effects")); + + FieldDef.insertAfter(defs, "ability.dodgeAnimation1", + FieldDef.animSubGui("ability.dodgeAnimation2", + this::getDodgeAnimation2Id, this::setDodgeAnimation2Id, + this::getDodgeAnimation2Name, this::setDodgeAnimation2Name) + .tab("Effects")); + + FieldDef.insertAfter(defs, "ability.dodgeAnimation2", + FieldDef.animSubGui("ability.dodgeAnimation3", + this::getDodgeAnimation3Id, this::setDodgeAnimation3Id, + this::getDodgeAnimation3Name, this::setDodgeAnimation3Name) + .tab("Effects")); + + FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); + FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ + + @Override + public int getDodgeAnimation1Id() { + return dodgeAnimation1Id; + } + + @Override + public void setDodgeAnimation1Id(int animationId) { + this.dodgeAnimation1Id = animationId; + } + + public String getDodgeAnimation1Name() { + return dodgeAnimation1Name; + } + + public void setDodgeAnimation1Name(String name) { + this.dodgeAnimation1Name = name != null ? name : ""; + } + + @Override + public int getDodgeAnimation2Id() { + return dodgeAnimation2Id; + } + + @Override + public void setDodgeAnimation2Id(int animationId) { + this.dodgeAnimation2Id = animationId; + } + + public String getDodgeAnimation2Name() { + return dodgeAnimation2Name; + } + + public void setDodgeAnimation2Name(String name) { + this.dodgeAnimation2Name = name != null ? name : ""; + } + + @Override + public int getDodgeAnimation3Id() { + return dodgeAnimation3Id; + } + + @Override + public void setDodgeAnimation3Id(int animationId) { + this.dodgeAnimation3Id = animationId; + } + + public String getDodgeAnimation3Name() { + return dodgeAnimation3Name; + } + + public void setDodgeAnimation3Name(String name) { + this.dodgeAnimation3Name = name != null ? name : ""; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java index b979f255c..ae27b98a9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEffect.java @@ -78,6 +78,11 @@ public class AbilityEffect extends Ability implements IAbilityEffect { this.windUpTicks = 30; this.telegraphType = TelegraphType.NONE; this.showTelegraph = false; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/effect.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/effect_overlay.png", + this::getActiveColor) + }; } // ==================== ABILITY TYPE OVERRIDES ==================== diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java index 97a29b5b0..636c02f3c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java @@ -2,285 +2,72 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; -import kamkeel.npcs.controllers.data.ability.enums.LockMode; -import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; import kamkeel.npcs.controllers.data.ability.enums.UserType; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; -import net.minecraft.world.World; import noppes.npcs.api.ability.type.IAbilityGuard; -import noppes.npcs.api.handler.data.IAnimation; import noppes.npcs.client.gui.builder.FieldDef; -import noppes.npcs.controllers.AnimationController; -import noppes.npcs.controllers.data.Animation; -import noppes.npcs.controllers.data.PlayerData; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; -import java.util.Arrays; import java.util.List; /** * Guard ability: Defensive stance that reduces incoming damage. - * Can optionally counter-attack when hit. */ -public class AbilityGuard extends Ability implements IAbilityGuard { +public class AbilityGuard extends AbilityDefend implements IAbilityGuard { - private int durationTicks = 60; private float damageReduction = 0.5f; - private AbilityGuard.CounterType counterType = AbilityGuard.CounterType.FLAT; - private float counterValue = 6.0f; - private String counterSound = "random.anvil_land"; - private boolean canCounter = false; - private int counterWindow = 10; - private int counterAnimationId = -1; - private String counterAnimationName; - - // Runtime state - private transient EntityLivingBase lastAttacker; - private transient boolean counterTriggered; - private transient boolean counterEligible; - private transient float lastDamageTaken; public AbilityGuard() { this.typeId = "ability.cnpc.guard"; this.name = "Guard"; - this.targetingMode = TargetingMode.SELF; - this.lockMovement = LockMode.ACTIVE; this.cooldownTicks = 0; - this.windUpTicks = 0; - this.interruptible = false; // Hard to interrupt while guarding - // No telegraph for guard - it's a defensive stance - this.telegraphType = TelegraphType.NONE; - this.showTelegraph = false; - this.activeSound = "random.anvil_use"; this.allowedBy = UserType.BOTH; this.activeAnimationName = "Ability_Guard_Active"; - this.counterAnimationName = "Ability_Guard_Counter"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png") + }; } + // ═══════════════════════════════════════════════════════════════════ + // DEFEND HOOKS + // ═══════════════════════════════════════════════════════════════════ + @Override - public boolean hasDamage() { - return canCounter; + protected float performDefend(EntityLivingBase attacker, float amount) { + return Math.max(0, amount * (1.0f - damageReduction)); } + // ═══════════════════════════════════════════════════════════════════ + // NBT + // ═══════════════════════════════════════════════════════════════════ + @Override - public boolean allowBurst() { - return false; - } - - public enum CounterType { - FLAT, - PERCENT; - - @Override - public String toString() { - switch (this) { - case FLAT: - return "ability.counter.flat"; - case PERCENT: - return "ability.counter.percent"; - default: - return name(); - } - } - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.SELF}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target) { - lastAttacker = null; - counterTriggered = false; - lastDamageTaken = 0.0f; - counterEligible = true; - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { - if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !caster.worldObj.isRemote) { - performCounter(caster, caster.worldObj); - } - - if (tick > counterWindow && counterEligible) { - counterEligible = false; - } - - if (tick >= durationTicks) { - signalCompletion(); - return; - } - - // Just enough to see the counter animation - if (counterTriggered && tick >= counterWindow + 10) { - signalCompletion(); - } - } - - public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) { - if (!isGuarding() || attacker == null) return; - - lastAttacker = attacker; - lastDamageTaken = damage; - - // Players: damage reduction handled via LivingHurtEvent (event.ammount modification) - // NPCs: called AFTER damageEntity() so health was already reduced — heal back here - if (caster instanceof EntityPlayer) { - if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) { - counterTriggered = true; - } - } else { - float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage); - float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth()); - - if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) { - caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); - counterTriggered = true; - } else { - caster.setHealth(newHealth); - } - } - } - - private boolean isDirectHit(DamageSource source) { - if (source == null) return false; - if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) return false; - return source.getEntity() instanceof EntityLivingBase; - } - - private void performCounter(EntityLivingBase caster, World world) { - float counterDamage = counterType == AbilityGuard.CounterType.PERCENT - ? lastDamageTaken * (counterValue / 100.0f) - : counterValue; - - boolean wasHit = applyAbilityDamage(caster, lastAttacker, counterDamage, 0.5f); - if (wasHit && counterSound != null && !counterSound.isEmpty()) { - world.playSoundAtEntity(caster, counterSound, 1.0f, 1.2f); - } - // Use shared animation utility - only available for NPCs - if (caster instanceof EntityNPCInterface) { - if (getCounterAnimation() instanceof IAnimation) { - ((EntityNPCInterface) caster).abilities.playAbilityAnimation((Animation) getCounterAnimation()); - } - } else if (caster instanceof EntityPlayer) { - if (getCounterAnimation() instanceof IAnimation) { - PlayerData.get((EntityPlayer) caster).abilityData.playAbilityAnimation((Animation) getCounterAnimation()); - } - } - - counterEligible = false; - lastAttacker = null; - lastDamageTaken = 0.0f; - } - - private IAnimation getCounterAnimation() { - if (AnimationController.Instance == null) return null; - - if (counterAnimationId > 0) { - return AnimationController.Instance.get(counterAnimationId); - } - - if (counterAnimationName != null && !counterAnimationName.isEmpty()) { - return AnimationController.Instance.get(counterAnimationName, true); - } - - return null; - } - - /** - * Get the damage reduction factor while guarding. - * Returns 0.5 for 50% reduction. - */ - public float getDamageReductionFactor() { - if (isExecuting() && getPhase() == AbilityPhase.ACTIVE) { - return damageReduction; - } - return 0.0f; - } - - /** - * Check if the caster is currently in guard stance. - */ - public boolean isGuarding() { - return isExecuting() && getPhase() == AbilityPhase.ACTIVE; - } - - @Override - public void reset() { - super.reset(); - lastAttacker = null; - counterTriggered = false; - lastDamageTaken = 0.0f; - } - - @Override - public float getTelegraphRadius() { - return 0; // No telegraph for guard - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); + protected void writeSubTypeNBT(NBTTagCompound nbt) { nbt.setFloat("damageReduction", damageReduction); - nbt.setBoolean("canCounter", canCounter); - nbt.setInteger("counterWindow", counterWindow); - nbt.setString("counterType", counterType.name()); - nbt.setFloat("counterValue", counterValue); - nbt.setString("counterSound", counterSound); - nbt.setInteger("counterAnimationId", counterAnimationId); - nbt.setString("counterAnimationName", counterAnimationName); } @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; + protected void readSubTypeNBT(NBTTagCompound nbt) { this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f; - this.canCounter = nbt.getBoolean("canCounter"); - this.counterWindow = nbt.getInteger("counterWindow"); - try { - this.counterType = CounterType.valueOf(nbt.getString("counterType")); - } catch (Exception e) { - this.counterType = CounterType.FLAT; - } - this.counterValue = nbt.getFloat("counterValue"); - this.counterSound = nbt.getString("counterSound"); - this.counterAnimationId = nbt.getInteger("counterAnimationId"); - this.counterAnimationName = nbt.getString("counterAnimationName"); } - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } + // ═══════════════════════════════════════════════════════════════════ + // GUI + // ═══════════════════════════════════════════════════════════════════ + @SideOnly(Side.CLIENT) @Override - public int getCounterWindow() { - return this.counterWindow; + protected void getTypeDefinitions(List defs) { + defs.add(FieldDef.floatField("ability.damageReduction", this::getDamageReduction, this::setDamageReduction)); + + FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); + FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); } - @Override - public void setCounterWindow(int ticks) { - this.counterWindow = Math.min(durationTicks, ticks); - } + // ═══════════════════════════════════════════════════════════════════ + // GETTERS / SETTERS + // ═══════════════════════════════════════════════════════════════════ @Override public float getDamageReduction() { @@ -291,105 +78,4 @@ public class AbilityGuard extends Ability implements IAbilityGuard { public void setDamageReduction(float damageReduction) { this.damageReduction = damageReduction; } - - - @Override - public boolean canCounter() { - return canCounter; - } - - public void setCanCounter(boolean canCounter) { - this.canCounter = canCounter; - } - - public CounterType getCounterTypeEnum() { - return counterType; - } - - public void setCounterTypeEnum(CounterType counterType) { - this.counterType = counterType; - } - - @Override - public int getCounterType() { - return counterType.ordinal(); - } - - @Override - public void setCounterType(int type) { - CounterType[] values = CounterType.values(); - this.counterType = type >= 0 && type < values.length ? values[type] : CounterType.FLAT; - } - - public float getCounterValue() { - return counterValue; - } - - public void setCounterValue(float counterValue) { - this.counterValue = counterValue; - } - - public String getCounterSound() { - return counterSound; - } - - public void setCounterSound(String counterSound) { - this.counterSound = counterSound; - } - - public int getCounterAnimationId() { - return counterAnimationId; - } - - public void setCounterAnimationId(int counterAnimationId) { - this.counterAnimationId = counterAnimationId; - } - - public boolean isCounterTriggered() { - return counterTriggered; - } - - public String getCounterAnimationName() { - return counterAnimationName; - } - - public void setCounterAnimationName(String name) { - this.counterAnimationName = name != null ? name : ""; - } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 1000), - FieldDef.floatField("ability.damageReduction", this::getDamageReduction, this::setDamageReduction), - FieldDef.section("ability.section.counter"), - FieldDef.boolField("gui.enabled", this::canCounter, this::setCanCounter).hover("ability.hover.canCounter"), - FieldDef.enumField("gui.type", CounterType.class, this::getCounterTypeEnum, this::setCounterTypeEnum) - .hover("ability.hover.counterType").visibleWhen(this::canCounter), - FieldDef.row( - FieldDef.floatField("gui.value", this::getCounterValue, this::setCounterValue) - .visibleWhen(this::canCounter), - FieldDef.intField("ability.counterWindow", this::getCounterWindow, this::setCounterWindow) - .visibleWhen(this::canCounter) - ), - FieldDef.stringField("gui.sound", this::getCounterSound, this::setCounterSound) - .visibleWhen(this::canCounter), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) - - )); - - FieldDef.insertAfter(defs, "ability.activeSound", - FieldDef.soundSubGui("ability.counterSound", this::getCounterSound, this::setCounterSound) - .tab("Effects").visibleWhen(this::canCounter)); - - FieldDef.insertAfter(defs, "ability.dazedAnimation", - FieldDef.animSubGui("ability.counterAnimation", - this::getCounterAnimationId, this::setCounterAnimationId, - this::getCounterAnimationName, this::setCounterAnimationName) - .tab("Effects").visibleWhen(this::canCounter)); - - FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); - FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); - } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 64638510a..23ff298db 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -30,6 +30,12 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard { this.windUpTicks = 30; this.windUpAnimationName = "Ability_Zone_Windup"; this.activeAnimationName = "Ability_Zone_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/hazard.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/hazard_overlay.png", + this::getActiveColor) + }; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java index 510193d54..2e5de3006 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -47,6 +47,11 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.activeSound = "random.anvil_land"; this.windUpAnimationName = "Ability_HeavyHit_Windup"; this.activeAnimationName = "Ability_HeavyHit_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/heavy_hit.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/heavy_hit_overlay.png", + this::getActiveColor) + }; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index c77994789..a41da923c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -43,6 +43,11 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.activeSound = "random.explode"; this.windUpAnimationName = "Ability_Shockwave_Windup"; this.activeAnimationName = "Ability_Shockwave_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/shockwave.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/shockwave_overlay.png", + this::getActiveColor) + }; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java index 8f4eeaf8c..d7a0f4cd6 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -83,6 +83,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { // Default built-in animations this.windUpAnimationName = "Ability_Slam_Windup"; this.activeAnimationName = "Ability_Slam_Active"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/slam.png") + }; } /** diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index 2e1490ffb..448a431af 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -86,6 +86,9 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.showTelegraph = false; this.windUpSound = "mob.endermen.portal"; this.activeSound = "mob.endermen.portal"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/teleport.png") + }; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index acd0e1378..21b5ff0e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -36,6 +36,11 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap { this.windUpTicks = 30; this.windUpAnimationName = "Ability_Zone_Windup"; this.activeAnimationName = "Ability_Zone_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/trap.png", + this::getActiveColor) + }; } @Override diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index fc6ab66f4..d397b32db 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -16,10 +16,11 @@ import net.minecraft.world.World; import noppes.npcs.api.ability.type.IAbilityVortex; import noppes.npcs.client.gui.builder.FieldDef; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; +import java.util.HashMap; import java.util.List; -import java.util.Set; +import java.util.Map; import java.util.UUID; /** @@ -37,13 +38,25 @@ public class AbilityVortex extends Ability implements IAbilityVortex { private float pullDamage = 0.0f; // Runtime state - private transient Set pulledEntities; + private transient Map pulledEntities; private transient boolean pullComplete = false; private transient int ticksSincePullDamage = 0; - private Set getPulledEntities() { + private static class PullState { + double lastX, lastY, lastZ; + int stuckTicks; + + PullState(EntityLivingBase entity) { + this.lastX = entity.posX; + this.lastY = entity.posY; + this.lastZ = entity.posZ; + this.stuckTicks = 0; + } + } + + private Map getPulledEntities() { if (pulledEntities == null) { - pulledEntities = new HashSet<>(); + pulledEntities = new HashMap<>(); } return pulledEntities; } @@ -59,6 +72,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex { this.telegraphType = TelegraphType.CIRCLE; this.windUpSound = "mob.ghast.charge"; this.activeSound = "mob.ghast.fireball"; + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/vortex.png", + this::getActiveColor) + }; } @Override @@ -96,37 +113,36 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double dist = caster.getDistanceToEntity(entity); if (dist <= pullRadius) { - getPulledEntities().add(entity.getUniqueID()); + getPulledEntities().put(entity.getUniqueID(), new PullState(entity)); } } } else { - // SINGULAR: pull one target - // NPC: pull aggro target if valid, otherwise nearest enemy - // Player: pull nearest enemy in range + // SINGULAR: pull one random target within range + // NPC: pull aggro target if valid, otherwise random enemy + // Player: pull random enemy in range if (!isPlayerCaster(caster) && target != null && !target.isDead) { double dist = caster.getDistanceToEntity(target); if (dist <= pullRadius) { - getPulledEntities().add(target.getUniqueID()); + getPulledEntities().put(target.getUniqueID(), new PullState(target)); return; } } - // Find nearest valid enemy - EntityLivingBase nearest = null; - double nearestDist = Double.MAX_VALUE; + // Collect all valid enemies, then pick one at random + List validTargets = new ArrayList<>(); for (EntityLivingBase entity : entities) { if (entity == caster) continue; if (entity.isDead) continue; if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue; double dist = caster.getDistanceToEntity(entity); - if (dist <= pullRadius && dist < nearestDist) { - nearest = entity; - nearestDist = dist; + if (dist <= pullRadius) { + validTargets.add(entity); } } - if (nearest != null) { - getPulledEntities().add(nearest.getUniqueID()); + if (!validTargets.isEmpty()) { + EntityLivingBase chosen = validTargets.get(caster.worldObj.rand.nextInt(validTargets.size())); + getPulledEntities().put(chosen.getUniqueID(), new PullState(chosen)); } } } @@ -147,6 +163,21 @@ public class AbilityVortex extends Ability implements IAbilityVortex { if (caster.worldObj.isRemote) return; + // Safety cap: force-complete if active too long + int maxActiveTicks = Math.max(40, (int)(pullRadius / pullStrength * 3)); + if (tick >= maxActiveTicks) { + for (Map.Entry entry : new HashMap<>(getPulledEntities()).entrySet()) { + EntityLivingBase entity = findEntity(caster, caster.worldObj, entry.getKey()); + if (entity != null && !entity.isDead) { + onTargetArrived(caster, entity, caster.worldObj); + } + } + getPulledEntities().clear(); + pullComplete = true; + signalCompletion(); + return; + } + double destX = caster.posX; double destY = caster.posY; double destZ = caster.posZ; @@ -158,7 +189,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex { ticksSincePullDamage = 0; } - for (UUID uuid : new HashSet<>(getPulledEntities())) { + for (Map.Entry entry : new HashMap<>(getPulledEntities()).entrySet()) { + UUID uuid = entry.getKey(); + PullState state = entry.getValue(); + EntityLivingBase entity = findEntity(caster, caster.worldObj, uuid); if (entity == null || entity.isDead) { getPulledEntities().remove(uuid); @@ -170,7 +204,28 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double dz = destZ - entity.posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= 1.5f) { + if (dist <= 1.5) { + getPulledEntities().remove(uuid); + onTargetArrived(caster, entity, caster.worldObj); + continue; + } + + // Stuck detection: check if entity made progress since last tick + double lastDx = destX - state.lastX; + double lastDy = destY - state.lastY; + double lastDz = destZ - state.lastZ; + double lastDist = Math.sqrt(lastDx * lastDx + lastDy * lastDy + lastDz * lastDz); + double progress = lastDist - dist; // positive = entity moved closer + + double expectedProgress = Math.min(pullStrength, dist * 0.5); + if (progress < expectedProgress * 0.3) { + state.stuckTicks++; + } else { + state.stuckTicks = 0; + } + + if (state.stuckTicks >= 5) { + // Entity is stuck (wall, block, partial obstruction) - treat as arrived getPulledEntities().remove(uuid); onTargetArrived(caster, entity, caster.worldObj); continue; @@ -182,21 +237,20 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double maxSpeed = dist * 0.5; double effectiveSpeed = Math.min(pullStrength, maxSpeed); double factor = effectiveSpeed / dist; - double nextX = dx * factor; - double nextY = dy * factor * 0.5; - double nextZ = dz * factor; + double motionX = dx * factor; + double motionY = dy * factor * 0.5; + double motionZ = dz * factor; - AxisAlignedBB nextBox = entity.boundingBox.copy().offset(nextX, nextY, nextZ); - if (!caster.worldObj.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) { - getPulledEntities().remove(uuid); - continue; - } - - entity.motionX = nextX; - entity.motionY = nextY; - entity.motionZ = nextZ; + entity.motionX = motionX; + entity.motionY = motionY; + entity.motionZ = motionZ; entity.velocityChanged = true; + // Update tracked position for next tick's stuck detection + state.lastX = entity.posX; + state.lastY = entity.posY; + state.lastZ = entity.posZ; + if (shouldDealPullDamage) { entity.hurtResistantTime = 0; applyAbilityDamage(caster, entity, pullDamage * 0.5f, 0); @@ -222,11 +276,12 @@ public class AbilityVortex extends Ability implements IAbilityVortex { /** * Find an entity by UUID within the vortex pull area. * Uses AABB search instead of iterating all loaded entities. + * Search area is expanded beyond pullRadius to account for entity drift. */ @SuppressWarnings("unchecked") private EntityLivingBase findEntity(EntityLivingBase caster, World world, UUID uuid) { - // Search within pull radius (entities being pulled should be within this area) - AxisAlignedBB searchBox = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); + double searchRadius = pullRadius + 5; + AxisAlignedBB searchBox = caster.boundingBox.expand(searchRadius, searchRadius / 2, searchRadius); List nearbyEntities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); for (EntityLivingBase entity : nearbyEntities) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java index d1054e858..1a7734a1e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBarrier.java @@ -5,7 +5,7 @@ import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; -import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityEnergyBarrier; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; @@ -21,8 +21,13 @@ public abstract class AbilityBarrier extends AbilityEnergy { protected final EnergyBarrierData barrierData; + // Spawn position offsets (relative to caster) + protected float offsetX = 0.0f; + protected float offsetY = 0.0f; + protected float offsetZ = 0.0f; + // Runtime entity tracking - protected transient EntityAbilityBarrier barrierEntity; + protected transient EntityEnergyBarrier barrierEntity; protected AbilityBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) { super(displayData); @@ -34,7 +39,7 @@ public abstract class AbilityBarrier extends AbilityEnergy { /** * Create and spawn the barrier entity during execution. */ - protected abstract EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); + protected abstract EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target); /** * Add type-specific GUI field definitions. @@ -157,10 +162,16 @@ public abstract class AbilityBarrier extends AbilityEnergy { writeBarrierTypeNBT(nbt); writeEnergyNBT(nbt); barrierData.writeNBT(nbt); + nbt.setFloat("barrierOffsetX", offsetX); + nbt.setFloat("barrierOffsetY", offsetY); + nbt.setFloat("barrierOffsetZ", offsetZ); } @Override public final void readTypeNBT(NBTTagCompound nbt) { + offsetX = nbt.hasKey("barrierOffsetX") ? nbt.getFloat("barrierOffsetX") : 0.0f; + offsetY = nbt.hasKey("barrierOffsetY") ? nbt.getFloat("barrierOffsetY") : 0.0f; + offsetZ = nbt.hasKey("barrierOffsetZ") ? nbt.getFloat("barrierOffsetZ") : 0.0f; readBarrierTypeNBT(nbt); readEnergyNBT(nbt); barrierData.readNBT(nbt); @@ -271,6 +282,14 @@ public abstract class AbilityBarrier extends AbilityEnergy { barrierData.setReflectStrengthPct(strengthPct); } + public boolean isTargetOwner() { + return barrierData.targetOwner; + } + + public void setTargetOwner(boolean targetOwner) { + barrierData.targetOwner = targetOwner; + } + // Melee data public boolean isMeleeEnabled() { return barrierData.meleeEnabled; @@ -288,6 +307,31 @@ public abstract class AbilityBarrier extends AbilityEnergy { barrierData.meleeDamageMultiplier = mult; } + // Offset data + public float getOffsetX() { + return offsetX; + } + + public void setOffsetX(float offsetX) { + this.offsetX = offsetX; + } + + public float getOffsetY() { + return offsetY; + } + + public void setOffsetY(float offsetY) { + this.offsetY = offsetY; + } + + public float getOffsetZ() { + return offsetZ; + } + + public void setOffsetZ(float offsetZ) { + this.offsetZ = offsetZ; + } + // ==================== GUI ==================== @SideOnly(Side.CLIENT) @@ -296,6 +340,14 @@ public abstract class AbilityBarrier extends AbilityEnergy { // Type-specific fields first addBarrierTypeDefinitions(defs); + // Offset section + defs.add(FieldDef.section("ability.section.offset")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.offsetX", this::getOffsetX, this::setOffsetX).min(Float.NEGATIVE_INFINITY), + FieldDef.floatField("ability.offsetY", this::getOffsetY, this::setOffsetY).min(Float.NEGATIVE_INFINITY) + )); + defs.add(FieldDef.floatField("ability.offsetZ", this::getOffsetZ, this::setOffsetZ).min(Float.NEGATIVE_INFINITY)); + // Barrier section defs.add(FieldDef.section("ability.section.barrier")); defs.add(FieldDef.boolField("ability.useHealth", this::isUseHealth, this::setUseHealth)); @@ -320,6 +372,9 @@ public abstract class AbilityBarrier extends AbilityEnergy { .hover("ability.hover.reflect")); defs.add(FieldDef.floatField("ability.reflectStrength", this::getReflectStrengthPct, this::setReflectStrengthPct) .range(0, 100).visibleWhen(this::isReflect)); + defs.add(FieldDef.boolField("ability.targetOwner", this::isTargetOwner, this::setTargetOwner) + .hover("ability.hover.targetOwner") + .visibleWhen(this::isReflect)); defs.add(FieldDef.boolField("ability.meleeEnabled", this::isMeleeEnabled, this::setMeleeEnabled) .hover("ability.hover.meleeEnabled")); defs.add(FieldDef.floatField("ability.meleeDamageMultiplier", this::getMeleeDamageMultiplier, this::setMeleeDamageMultiplier) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java index 1d9a0374d..f811cef9e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityBeam.java @@ -33,6 +33,7 @@ public class AbilityBeam extends AbilityEnergyProjectile impl private float beamWidth = 0.4f; private float headSize = 0.6f; + private boolean freeAim = false; public AbilityBeam() { super( @@ -55,6 +56,11 @@ public class AbilityBeam extends AbilityEnergyProjectile impl this.showTelegraph = true; this.windUpAnimationName = "Ability_Beam_Windup"; this.activeAnimationName = "Ability_Beam_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/beam.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } // ==================== ABSTRACT IMPLEMENTATIONS ==================== @@ -62,12 +68,14 @@ public class AbilityBeam extends AbilityEnergyProjectile impl @Override protected EntityAbilityBeam createEntity(EntityLivingBase caster, EntityLivingBase target, Vec3 spawnPos, EnergyDisplayData resolved, int index) { - return new EntityAbilityBeam( + EntityAbilityBeam beam = new EntityAbilityBeam( caster.worldObj, caster, target, spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, beamWidth, headSize, resolved, combatData, homingData, lightningData, lifespanData, lockMovement.locksActive()); + beam.setFreeAim(freeAim); + return beam; } @Override @@ -95,6 +103,18 @@ public class AbilityBeam extends AbilityEnergyProjectile impl return new EntityAbilityBeam[size]; } + @Override + public void detach() { + if (entities != null) { + for (EntityAbilityBeam beam : entities) { + if (beam != null && !beam.isDead) { + beam.setAttachedToOwner(false); + } + } + } + super.detach(); + } + @Override protected float getProjectileTelegraphRadius() { return headSize * 2.0f; @@ -134,12 +154,14 @@ public class AbilityBeam extends AbilityEnergyProjectile impl protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("beamWidth", beamWidth); nbt.setFloat("headSize", headSize); + nbt.setBoolean("freeAim", freeAim); } @Override protected void readTypeSpecificNBT(NBTTagCompound nbt) { this.beamWidth = nbt.getFloat("beamWidth"); this.headSize = nbt.getFloat("headSize"); + this.freeAim = nbt.getBoolean("freeAim"); } // ==================== TYPE-SPECIFIC GETTERS ==================== @@ -168,6 +190,14 @@ public class AbilityBeam extends AbilityEnergyProjectile impl this.headSize = headSize; } + public boolean isFreeAim() { + return freeAim; + } + + public void setFreeAim(boolean freeAim) { + this.freeAim = freeAim; + } + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @@ -184,6 +214,9 @@ public class AbilityBeam extends AbilityEnergyProjectile impl )); defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); defs.add(FieldDef.section("ability.section.beam")); + defs.add(FieldDef.boolField("ability.freeAim", this::isFreeAim, this::setFreeAim) + .hover("ability.hover.freeAim") + .enabledWhen(() -> lockMovement.locksActive() && rotationMode == RotationMode.FREE && !freeOnCast)); defs.add(FieldDef.row( FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth).range(0.1f, 100.0f), FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize).range(0.1f, 100.0f) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java index afb6d0400..1d3dacc19 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDisc.java @@ -55,6 +55,12 @@ public class AbilityDisc extends AbilityEnergyProjectile impl this.showTelegraph = true; this.windUpAnimationName = "Ability_Disc_Windup"; this.activeAnimationName = "Ability_Disc_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/disc.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/disc_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } // ==================== ABSTRACT IMPLEMENTATIONS ==================== diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java index 99b431477..cacda2061 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityDome.java @@ -8,8 +8,8 @@ import kamkeel.npcs.controllers.data.ability.enums.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBarrier; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -42,18 +42,24 @@ public class AbilityDome extends AbilityBarrier { this.showTelegraph = true; this.windUpAnimationName = ""; this.activeAnimationName = ""; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/dome.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { - EntityAbilityDome dome = new EntityAbilityDome( + protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + EntityEnergyDome dome = new EntityEnergyDome( caster.worldObj, caster, - caster.posX, caster.posY, caster.posZ, + caster.posX + offsetX, caster.posY + offsetY, caster.posZ + offsetZ, domeRadius, displayData.copy(), lightningData.copy(), barrierData.copy() ); dome.setFollowCaster(followCaster); + dome.setOffsets(offsetX, offsetY, offsetZ); dome.setSourceAbility(this); return dome; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java index e0e096b3c..8d8949f07 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityEnergyProjectile.java @@ -192,20 +192,6 @@ public abstract class AbilityEnergyProjectile this.fireDelay = Math.max(0, delay); } - /** - * @deprecated Use {@link #getFireDelay()} - */ - public int getDualFireDelay() { - return fireDelay; - } - - /** - * @deprecated Use {@link #setFireDelay(int)} - */ - public void setDualFireDelay(int delay) { - setFireDelay(delay); - } - protected int clampIndex(int index) { return Math.max(0, Math.min(index, projectileCount - 1)); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaser.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaser.java index 75480b622..918f493ba 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaser.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityLaser.java @@ -53,6 +53,12 @@ public class AbilityLaser extends AbilityEnergyProjectile im this.showTelegraph = true; this.windUpAnimationName = "Ability_Laser_Windup"; this.activeAnimationName = "Ability_Laser_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/laser_shot.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/laser_shot_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } // ==================== OVERRIDES ==================== @@ -207,7 +213,10 @@ public class AbilityLaser extends AbilityEnergyProjectile im FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth).range(0.1f, 100.0f), FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed).range(0.1f, 50.0f) )); - defs.add(FieldDef.floatField("ability.maxLength", this::getMaxLength, this::setMaxLength).range(1.0f, 500.0f)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxLength", this::getMaxLength, this::setMaxLength).range(1.0f, 500.0f), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200) + )); defs.add(FieldDef.section("ability.section.explosive")); defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java index b28813262..7ef631dda 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityOrb.java @@ -49,6 +49,12 @@ public class AbilityOrb extends AbilityEnergyProjectile implem this.showTelegraph = true; this.windUpAnimationName = "Ability_Orb_Windup"; this.activeAnimationName = "Ability_Orb_Active"; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/orb.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/orb_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } // ==================== ABSTRACT IMPLEMENTATIONS ==================== diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java index f7cbaa8fd..0adf474ca 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityShield.java @@ -10,8 +10,8 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBarrier; -import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyPanel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -45,24 +45,31 @@ public class AbilityShield extends AbilityBarrier { this.windUpAnimationName = ""; this.activeAnimationName = ""; this.allowedBy = UserType.BOTH; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/shield.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { - EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, 0.0f); + protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, offsetY); + panelData.offsetX = offsetX; + panelData.offsetZ = offsetZ; float frontDist = 1.5f; float yawRad = (float) Math.toRadians(caster.rotationYaw); - double spawnX = caster.posX + (-Math.sin(yawRad) * frontDist); + double spawnX = caster.posX + (-Math.sin(yawRad) * frontDist) + offsetX; double spawnY = caster.posY + (caster.height * 0.5f); - double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist); + double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist) + offsetZ; - EntityAbilityPanel panel = new EntityAbilityPanel( + EntityEnergyPanel panel = new EntityEnergyPanel( caster.worldObj, caster, spawnX, spawnY, spawnZ, caster.rotationYaw, - EntityAbilityPanel.PanelMode.HELD, + EntityEnergyPanel.PanelMode.HELD, displayData.copy(), lightningData.copy(), barrierData.copy(), panelData ); panel.setSourceAbility(this); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java index 655a2c194..f87561174 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilitySweeper.java @@ -9,7 +9,7 @@ import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.Telegraph; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergySweeper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.api.ability.type.IAbilitySweeper; @@ -23,7 +23,7 @@ import java.util.List; * Players can jump over it. The beam completes a set number of rotations before ending. * Telegraph shows a large circle on the ground indicating range. *

- * All damage logic is handled by the EntityAbilitySweeper entity to ensure + * All damage logic is handled by the EntityEnergySweeper entity to ensure * visual and damage hitbox alignment. */ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { @@ -40,7 +40,7 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { private boolean lockOnTarget = false; // Runtime state (transient) - private transient EntityAbilitySweeper activeEntity = null; + private transient EntityEnergySweeper activeEntity = null; public AbilitySweeper() { super(new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f)); @@ -55,6 +55,12 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { // Circle telegraph to show range this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/sweeper.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/sweeper_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } @Override @@ -92,7 +98,7 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper { // Spawn the sweeper entity that handles BOTH visuals AND damage. // NPC: target is the aggro target — lockOnTarget tracks it during sweep. // Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect. - activeEntity = new EntityAbilitySweeper(caster.worldObj, caster, target, + activeEntity = new EntityEnergySweeper(caster.worldObj, caster, target, beamLength, beamWidth, beamHeight, displayData, sweepSpeed, numberOfRotations, diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java index 1d820851d..104cae221 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/energy/AbilityWall.java @@ -9,8 +9,8 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData; import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBarrier; -import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyPanel; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.gui.builder.FieldDef; @@ -45,6 +45,12 @@ public class AbilityWall extends AbilityBarrier { this.showTelegraph = true; this.windUpAnimationName = ""; this.activeAnimationName = ""; + + this.defaultIconLayers = new DefaultIconLayer[]{ + new DefaultIconLayer("customnpcs:textures/gui/ability/wall.png"), + new DefaultIconLayer("customnpcs:textures/gui/ability/wall_overlay.png", + () -> isOuterColorEnabled() ? getOuterColor() : getInnerColor()) + }; } @Override @@ -55,7 +61,7 @@ public class AbilityWall extends AbilityBarrier { // ==================== ABSTRACT IMPLEMENTATIONS ==================== @Override - protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { + protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) { // Place wall between caster and target double placeX, placeY, placeZ; float yaw; @@ -87,14 +93,21 @@ public class AbilityWall extends AbilityBarrier { yaw = caster.rotationYaw; } - EntityAbilityPanel.PanelMode mode = panelData.launching - ? EntityAbilityPanel.PanelMode.LAUNCHED - : EntityAbilityPanel.PanelMode.PLACED; + placeX += offsetX; + placeY += offsetY; + placeZ += offsetZ; - EntityAbilityPanel panel = new EntityAbilityPanel( + EntityEnergyPanel.PanelMode mode = panelData.launching + ? EntityEnergyPanel.PanelMode.LAUNCHED + : EntityEnergyPanel.PanelMode.PLACED; + + EnergyPanelData data = panelData.copy(); + data.heightOffset = 0.0f; // Y offset now handled by base class via placeY + + EntityEnergyPanel panel = new EntityEnergyPanel( caster.worldObj, caster, placeX, placeY, placeZ, yaw, mode, - displayData.copy(), lightningData.copy(), barrierData.copy(), panelData.copy() + displayData.copy(), lightningData.copy(), barrierData.copy(), data ); panel.setSourceAbility(this); return panel; @@ -134,6 +147,11 @@ public class AbilityWall extends AbilityBarrier { @Override protected void readBarrierTypeNBT(NBTTagCompound nbt) { panelData.readNBT(nbt); + // Migrate legacy heightOffset → base class offsetY + if (!nbt.hasKey("barrierOffsetY") && panelData.heightOffset != 0.0f) { + offsetY = panelData.heightOffset; + panelData.heightOffset = 0.0f; + } } // ==================== GETTERS & SETTERS ==================== @@ -158,14 +176,6 @@ public class AbilityWall extends AbilityBarrier { panelData.setPanelHeight(height); } - public float getHeightOffset() { - return panelData.heightOffset; - } - - public void setHeightOffset(float offset) { - panelData.heightOffset = offset; - } - public boolean isLaunching() { return panelData.launching; } @@ -208,8 +218,6 @@ public class AbilityWall extends AbilityBarrier { FieldDef.floatField("gui.width", this::getPanelWidth, this::setPanelWidth).range(0.5f, 100.0f), FieldDef.floatField("gui.height", this::getPanelHeight, this::setPanelHeight).range(0.5f, 100.0f) )); - defs.add(FieldDef.floatField("ability.heightOffset", this::getHeightOffset, this::setHeightOffset) - .min(Float.NEGATIVE_INFINITY)); defs.add(FieldDef.section("ability.section.launch")); defs.add(FieldDef.boolField("gui.enabled", this::isLaunching, this::setLaunching) .hover("ability.hover.launching")); diff --git a/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java b/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java index 04ce9b66c..002fdb52f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/profile/Profile.java @@ -2,6 +2,7 @@ package kamkeel.npcs.controllers.data.profile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.handler.data.IProfile; @@ -15,6 +16,7 @@ public class Profile implements IProfile { public EntityPlayer player; public int currentSlotId; private final Map slots = new HashMap<>(); + public Map sharedQuestTimestamps = new HashMap<>(); private boolean locked = false; public Profile(EntityPlayer player, NBTTagCompound compound) { @@ -39,6 +41,14 @@ public class Profile implements IProfile { } } } + + if (compound.hasKey("SharedQuestTimestamps")) { + NBTTagList list = compound.getTagList("SharedQuestTimestamps", 10); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound entry = list.getCompoundTagAt(i); + sharedQuestTimestamps.put(entry.getInteger("Quest"), entry.getLong("Date")); + } + } } public Profile(EntityPlayer player) { @@ -88,6 +98,16 @@ public class Profile implements IProfile { slotsCompound.setTag(String.valueOf(entry.getKey()), entry.getValue().toNBT()); } compound.setTag("Slots", slotsCompound); + + NBTTagList questList = new NBTTagList(); + for (Map.Entry entry : sharedQuestTimestamps.entrySet()) { + NBTTagCompound questEntry = new NBTTagCompound(); + questEntry.setInteger("Quest", entry.getKey()); + questEntry.setLong("Date", entry.getValue()); + questList.appendTag(questEntry); + } + compound.setTag("SharedQuestTimestamps", questList); + return compound; } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 47e2c7d8d..15b1e5cbf 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -11,6 +11,7 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.AxisAlignedBB; @@ -55,6 +56,10 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { // Beam behavior mode (single source of truth). private BeamMode beamMode = BeamMode.ANCHORED; + // Free Aim (players only) - steers beam toward player's look direction + private boolean freeAim = false; + private static final float FREE_AIM_STRENGTH = 0.15f; + // Charging state (beam-specific) private float chargeOffsetDistance = 1.0f; private int trailFadeTime = 20; // Ticks for trail to fully fade @@ -433,8 +438,64 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { addTrailPoint(); } + /** + * Steer beam toward player's look direction (Free Aim mode). + * Target point is projected along look vector at the current head distance from origin. + */ + private void updateFreeAim() { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityPlayer)) return; + + Vec3 look = getOwnerLookVector(); + if (look == null) return; + + double headDist = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ); + if (headDist < 0.1) return; + + // Target point along look vector at current head distance + double targetX = startX + look.xCoord * headDist; + double targetY = startY + look.yCoord * headDist; + double targetZ = startZ + look.zCoord * headDist; + + // Current head world position + double headWorldX = startX + headOffsetX; + double headWorldY = startY + headOffsetY; + double headWorldZ = startZ + headOffsetZ; + + double dx = targetX - headWorldX; + double dy = targetY - headWorldY; + double dz = targetZ - headWorldZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + if (dist < 0.01) return; + + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); + + motionX += (desiredVX - motionX) * FREE_AIM_STRENGTH; + motionY += (desiredVY - motionY) * FREE_AIM_STRENGTH; + motionZ += (desiredVZ - motionZ) * FREE_AIM_STRENGTH; + + double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + if (vLen > 0) { + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); + } + } + @Override protected void updateHoming() { + if (freeAim) { + Entity owner = getOwnerEntity(); + if (owner instanceof EntityPlayer) { + updateFreeAim(); + return; + } + // NPCs fall through to normal homing + } + if (!isHoming()) return; Entity target = getTargetEntity(); @@ -545,6 +606,14 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { setBeamMode(modeFromAnchored(attached)); } + public boolean isFreeAim() { + return freeAim; + } + + public void setFreeAim(boolean freeAim) { + this.freeAim = freeAim; + } + /** * Get interpolated head offset for smooth rendering. * Returns offset RELATIVE to origin. @@ -630,7 +699,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { // ==================== REFLECTION ==================== @Override - protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) { + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { boolean reflected = super.reflectFromBarrier(barrier, reflectStrengthPct); if (reflected) { // Switch to FREE_TRAIL: detach from caster (tail-less), trail fades out. @@ -643,9 +712,14 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { resetHeadOffsets(); resetTrailStorage(); - // Disable homing — reflected beams fly straight. - homingData.setHoming(false); - setTargetEntityId(-1); + // Free aim only works for the original caster + freeAim = false; + + // If targeting owner, keep homing so beam tracks back to caster + if (!barrier.getBarrierData().isTargetOwner()) { + homingData.setHoming(false); + setTargetEntityId(-1); + } } return reflected; } @@ -668,6 +742,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { resetHeadOffsets(); resetTrailStorage(); homingData.setHoming(false); + freeAim = false; setTargetEntityId(-1); } @@ -686,6 +761,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { readChargingNBT(nbt); this.chargeOffsetDistance = nbt.hasKey("ChargeOffsetDistance") ? nbt.getFloat("ChargeOffsetDistance") : 1.0f; this.trailFadeTime = nbt.hasKey("TrailFadeTime") ? nbt.getInteger("TrailFadeTime") : 20; + this.freeAim = nbt.getBoolean("FreeAim"); boolean attachedLegacy = !nbt.hasKey("AttachedToOwner") || nbt.getBoolean("AttachedToOwner"); BeamMode loadedMode = modeFromAnchored(attachedLegacy); @@ -737,6 +813,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile { nbt.setString("BeamMode", beamMode.name()); writeChargingNBT(nbt); nbt.setFloat("ChargeOffsetDistance", chargeOffsetDistance); + nbt.setBoolean("FreeAim", freeAim); nbt.setBoolean("FadeTrail", isFadingMode()); nbt.setInteger("TrailFadeTime", trailFadeTime); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index d7c74c3dc..10036b3c8 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -409,7 +409,7 @@ public class EntityAbilityDisc extends EntityEnergyProjectile { // ==================== REFLECTION ==================== @Override - protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) { + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { boolean reflected = super.reflectFromBarrier(barrier, reflectStrengthPct); if (reflected) { // Disable boomerang on reflected discs — the original owner is no longer diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 3c948d0f0..4581340a9 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -419,8 +419,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { private boolean checkLaserBarrierCollision() { if (currentLength <= 0) return false; - List barriers = EntityAbilityBarrier.getActiveBarriers(worldObj); - for (EntityAbilityBarrier barrier : barriers) { + List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); + for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead || barrier.isCharging()) continue; if (barrier.getOwnerEntityId() == this.ownerEntityId) continue; @@ -433,17 +433,17 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { } } - if (barrier instanceof EntityAbilityDome) { - EntityAbilityDome dome = (EntityAbilityDome) barrier; + if (barrier instanceof EntityEnergyDome) { + EntityEnergyDome dome = (EntityEnergyDome) barrier; float intersectDist = getLineSphereIntersection(dome); if (intersectDist >= 0) { float damage = getModifiedDamage(); - EntityAbilityBarrier.ProjectileHitOutcome hitOutcome = dome.onProjectileHitResolved(this, damage); - if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) { + EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = dome.onProjectileHitResolved(this, damage); + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { continue; } - if (hitOutcome.result != EntityAbilityBarrier.ProjectileHitResult.BROKEN) { + if (hitOutcome.result != EntityEnergyBarrier.ProjectileHitResult.BROKEN) { currentLength = Math.max(0.0f, intersectDist); endX = startX + dirX * currentLength; endY = startY + dirY * currentLength; @@ -469,12 +469,12 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { if (incoming) { float damage = getModifiedDamage(); - EntityAbilityBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage); - if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) { + EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage); + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { continue; } - if (hitOutcome.result != EntityAbilityBarrier.ProjectileHitResult.BROKEN) { + if (hitOutcome.result != EntityEnergyBarrier.ProjectileHitResult.BROKEN) { endX = startX + dirX * currentLength; endY = startY + dirY * currentLength; endZ = startZ + dirZ * currentLength; @@ -491,7 +491,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { } @Override - protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) { + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { if (barrier == null) { return false; } @@ -568,12 +568,21 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { } sourceAbility = null; + // Save original owner before transfer for potential target retargeting + int originalOwnerId = ownerEntityId; + Entity barrierOwner = barrier.getOwnerEntity(); if (barrierOwner != null) { setOwnerEntityId(barrierOwner.getEntityId()); trackProjectile(this); } - setTargetEntityId(-1); + + // Target Owner: set the reflected projectile's target to the original caster + if (barrier.getBarrierData().isTargetOwner() && originalOwnerId != -1) { + setTargetEntityId(originalOwnerId); + } else { + setTargetEntityId(-1); + } setInnerColor(barrier.getInnerColor()); setOuterColor(barrier.getOuterColor()); @@ -593,7 +602,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile { * Returns the distance along the laser direction to the first entry point, * or -1 if no intersection from outside. */ - private float getLineSphereIntersection(EntityAbilityDome dome) { + private float getLineSphereIntersection(EntityEnergyDome dome) { double cx = dome.posX; double cy = dome.posY; double cz = dome.posZ; diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java index 7922f7191..d3fac4faf 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyAbility.java @@ -88,6 +88,15 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit this.chargeDuration = duration; } + /** + * Reset chargeTick back to chargeDuration so the charging timeout + * grace period restarts. Used by items that let the player hold + * a fully-charged orb indefinitely. + */ + public void resetChargeTick() { + this.chargeTick = this.chargeDuration; + } + public float getChargeProgress() { if (chargeDuration <= 0) return 1.0f; return Math.min(1.0f, (float) chargeTick / chargeDuration); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java similarity index 96% rename from src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java rename to src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java index 3cb3fe021..82781eed7 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBarrier.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyBarrier.java @@ -25,7 +25,7 @@ import java.util.List; * and barrier lifecycle management. * Extends EntityEnergyAbility for shared visual/owner/charging state. */ -public abstract class EntityAbilityBarrier extends EntityEnergyAbility { +public abstract class EntityEnergyBarrier extends EntityEnergyAbility { /** * Outcome of a projectile vs barrier interaction. @@ -72,26 +72,26 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility { } public boolean shouldReflect() { - return reflectEnabled && useHealth && result == ProjectileHitResult.BLOCKED; + return reflectEnabled && result == ProjectileHitResult.BLOCKED; } } // ==================== ACTIVE BARRIER REGISTRY ==================== - private static final List> activeBarriers = new ArrayList<>(); + private static final List> activeBarriers = new ArrayList<>(); private boolean tracked = false; - public static void trackBarrier(EntityAbilityBarrier barrier) { + public static void trackBarrier(EntityEnergyBarrier barrier) { activeBarriers.add(new WeakReference<>(barrier)); } /** * Get all living barriers in the given world. Auto-cleans dead refs. */ - public static List getActiveBarriers(World world) { - List result = new ArrayList<>(); - Iterator> it = activeBarriers.iterator(); + public static List getActiveBarriers(World world) { + List result = new ArrayList<>(); + Iterator> it = activeBarriers.iterator(); while (it.hasNext()) { - EntityAbilityBarrier b = it.next().get(); + EntityEnergyBarrier b = it.next().get(); if (b == null || b.isDead) { it.remove(); } else if (b.worldObj == world) { @@ -114,7 +114,7 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility { protected static final int DW_HEALTH_PERCENT = 21; protected static final int DW_HIT_FLASH = 22; - public EntityAbilityBarrier(World world) { + public EntityEnergyBarrier(World world) { super(world); this.noClip = true; } @@ -267,7 +267,7 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility { healthBefore, 0.0f, 0.0f, - false, + barrierData.reflect, barrierData.reflectStrengthPct, false ); @@ -506,10 +506,10 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility { * Find a barrier that would absorb damage for the given entity (its caster). * Returns the barrier if: absorbing is enabled AND entity is the barrier's owner. */ - public static EntityAbilityBarrier getAbsorbingBarrier(Entity entity) { + public static EntityEnergyBarrier getAbsorbingBarrier(Entity entity) { if (entity == null || entity.worldObj == null) return null; - List barriers = getActiveBarriers(entity.worldObj); - for (EntityAbilityBarrier barrier : barriers) { + List barriers = getActiveBarriers(entity.worldObj); + for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead) continue; if (!barrier.barrierData.absorbing) continue; if (barrier.ownerEntityId == entity.getEntityId()) { diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java similarity index 93% rename from src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java rename to src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java index 6f6b75469..0e8f0bf56 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDome.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyDome.java @@ -22,29 +22,32 @@ import java.util.List; * Energy Dome entity - a spherical barrier that blocks incoming energy projectiles. * Centered on the caster's position at time of casting. * Only blocks incoming attacks (not outgoing from allies inside). - * Extends EntityAbilityBarrier for shared barrier logic. + * Extends EntityEnergyBarrier for shared barrier logic. */ -public class EntityAbilityDome extends EntityAbilityBarrier { +public class EntityEnergyDome extends EntityEnergyBarrier { // ==================== DOME-SPECIFIC PROPERTIES ==================== protected float domeRadius = 5.0f; protected float targetDomeRadius = 5.0f; protected boolean followCaster = false; + protected float offsetX = 0.0f; + protected float offsetY = 0.0f; + protected float offsetZ = 0.0f; // Server-side melee detection state private boolean inTickMelee = false; private final HashSet processedMeleeSwings = new HashSet<>(); - public EntityAbilityDome(World world) { + public EntityEnergyDome(World world) { super(world); this.noClip = true; this.stepHeight = 0.0F; this.setSize(1.0f, 1.0f); } - public EntityAbilityDome(World world, EntityLivingBase owner, double x, double y, double z, - float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, - EnergyBarrierData barrier) { + public EntityEnergyDome(World world, EntityLivingBase owner, double x, double y, double z, + float domeRadius, EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier) { this(world); this.noClip = true; this.stepHeight = 0.0F; @@ -81,11 +84,11 @@ public class EntityAbilityDome extends EntityAbilityBarrier { if (followCaster) { Entity owner = ownerEntityId >= 0 ? worldObj.getEntityByID(ownerEntityId) : null; if (owner != null) { - this.setPosition(owner.posX, owner.posY, owner.posZ); + this.setPosition(owner.posX + offsetX, owner.posY + offsetY, owner.posZ + offsetZ); // Sync prevPos with owner's prevPos for smooth interpolation - this.prevPosX = owner.prevPosX; - this.prevPosY = owner.prevPosY; - this.prevPosZ = owner.prevPosZ; + this.prevPosX = owner.prevPosX + offsetX; + this.prevPosY = owner.prevPosY + offsetY; + this.prevPosZ = owner.prevPosZ + offsetZ; } } @@ -186,13 +189,17 @@ public class EntityAbilityDome extends EntityAbilityBarrier { } } - double prevX = projectile.posX - projectile.motionX; - double prevY = projectile.posY - projectile.motionY; - double prevZ = projectile.posZ - projectile.motionZ; + // Test the UPCOMING movement (this tick) so the barrier intercepts before + // entity collision runs in updateProjectile(). Using the previous tick's + // segment caused small domes to miss fast projectiles that could cross the + // dome and hit the player in a single tick. + double nextX = projectile.posX + projectile.motionX; + double nextY = projectile.posY + projectile.motionY; + double nextZ = projectile.posZ + projectile.motionZ; return isIncomingRay( + nextX, nextY, nextZ, projectile.posX, projectile.posY, projectile.posZ, - prevX, prevY, prevZ, projectile.getOwnerEntityId()); } @@ -585,6 +592,12 @@ public class EntityAbilityDome extends EntityAbilityBarrier { this.followCaster = follow; } + public void setOffsets(float x, float y, float z) { + this.offsetX = x; + this.offsetY = y; + this.offsetZ = z; + } + @Override @SideOnly(Side.CLIENT) public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int increments) { @@ -627,6 +640,9 @@ public class EntityAbilityDome extends EntityAbilityBarrier { nbt.setFloat("DomeRadius", domeRadius); nbt.setFloat("TargetDomeRadius", targetDomeRadius); nbt.setBoolean("FollowCaster", followCaster); + nbt.setFloat("OffsetX", offsetX); + nbt.setFloat("OffsetY", offsetY); + nbt.setFloat("OffsetZ", offsetZ); } @Override @@ -635,5 +651,8 @@ public class EntityAbilityDome extends EntityAbilityBarrier { this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS)); this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS); this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster"); + this.offsetX = nbt.hasKey("OffsetX") ? nbt.getFloat("OffsetX") : 0.0f; + this.offsetY = nbt.hasKey("OffsetY") ? nbt.getFloat("OffsetY") : 0.0f; + this.offsetZ = nbt.hasKey("OffsetZ") ? nbt.getFloat("OffsetZ") : 0.0f; } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java similarity index 96% rename from src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java rename to src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java index 717250fdd..ad25afa0b 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityPanel.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyPanel.java @@ -21,9 +21,9 @@ import java.util.List; /** * Energy Panel entity - a flat rectangular barrier used by Wall and Shield abilities. * Supports three modes: PLACED (stationary), HELD (tracks caster), LAUNCHED (moves forward). - * Extends EntityAbilityBarrier for shared barrier logic. + * Extends EntityEnergyBarrier for shared barrier logic. */ -public class EntityAbilityPanel extends EntityAbilityBarrier { +public class EntityEnergyPanel extends EntityEnergyBarrier { public enum PanelMode { PLACED, // Stationary wall @@ -41,15 +41,15 @@ public class EntityAbilityPanel extends EntityAbilityBarrier { protected float targetPanelWidth; protected float targetPanelHeight; - public EntityAbilityPanel(World world) { + public EntityEnergyPanel(World world) { super(world); this.setSize(0.5f, 0.5f); } - public EntityAbilityPanel(World world, EntityLivingBase owner, double x, double y, double z, - float yaw, PanelMode mode, - EnergyDisplayData display, EnergyLightningData lightning, - EnergyBarrierData barrier, EnergyPanelData panel) { + public EntityEnergyPanel(World world, EntityLivingBase owner, double x, double y, double z, + float yaw, PanelMode mode, + EnergyDisplayData display, EnergyLightningData lightning, + EnergyBarrierData barrier, EnergyPanelData panel) { this(world); this.setPosition(x, y + panel.heightOffset, z); this.ownerEntityId = owner.getEntityId(); @@ -157,17 +157,17 @@ public class EntityAbilityPanel extends EntityAbilityBarrier { // Follow owner position float frontDist = 1.5f; float yawRad = (float) Math.toRadians(panelYaw); - double newX = owner.posX + (-Math.sin(yawRad) * frontDist); + double newX = owner.posX + (-Math.sin(yawRad) * frontDist) + panelData.offsetX; double newY = owner.posY + panelData.heightOffset + (owner.height * 0.5f); - double newZ = owner.posZ + (Math.cos(yawRad) * frontDist); + double newZ = owner.posZ + (Math.cos(yawRad) * frontDist) + panelData.offsetZ; this.setPosition(newX, newY, newZ); // Sync prevPos with owner's prevPos for smooth interpolation float prevYawRad = (float) Math.toRadians(owner.prevRotationYaw); - this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist); + this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist) + panelData.offsetX; this.prevPosY = owner.prevPosY + panelData.heightOffset + (owner.height * 0.5f); - this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist); + this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist) + panelData.offsetZ; } @Override @@ -340,13 +340,15 @@ public class EntityAbilityPanel extends EntityAbilityBarrier { } } - double prevX = projectile.posX - projectile.motionX; - double prevY = projectile.posY - projectile.motionY; - double prevZ = projectile.posZ - projectile.motionZ; + // Test the UPCOMING movement so the barrier intercepts before entity + // collision runs in updateProjectile(). + double nextX = projectile.posX + projectile.motionX; + double nextY = projectile.posY + projectile.motionY; + double nextZ = projectile.posZ + projectile.motionZ; return isIncomingRay( + nextX, nextY, nextZ, projectile.posX, projectile.posY, projectile.posZ, - prevX, prevY, prevZ, projectile.getOwnerEntityId()); } diff --git a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java index 02a124ae3..fbfc91d79 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergyProjectile.java @@ -439,8 +439,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { * @return true if barrier interaction was handled (caller should stop processing this tick) */ protected boolean checkBarrierCollision() { - List barriers = EntityAbilityBarrier.getActiveBarriers(worldObj); - for (EntityAbilityBarrier barrier : barriers) { + List barriers = EntityEnergyBarrier.getActiveBarriers(worldObj); + for (EntityEnergyBarrier barrier : barriers) { if (barrier.isDead) continue; // Quick distance pre-filter @@ -453,8 +453,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { if (barrier.isIncomingProjectile(this)) { float damage = getModifiedDamage(); - EntityAbilityBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage); - if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) { + EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage); + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { continue; } if (handleBarrierHitOutcome(barrier, hitOutcome, damage)) { @@ -473,12 +473,12 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { * @param fullDamage The DBC-scaled damage that was passed to the barrier (from getModifiedDamage). * @return true if caller should stop processing this tick. */ - protected boolean handleBarrierHitOutcome(EntityAbilityBarrier barrier, EntityAbilityBarrier.ProjectileHitOutcome hitOutcome, float fullDamage) { - if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) { + protected boolean handleBarrierHitOutcome(EntityEnergyBarrier barrier, EntityEnergyBarrier.ProjectileHitOutcome hitOutcome, float fullDamage) { + if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) { return false; } - if (hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.BROKEN) { + if (hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.BROKEN) { if (hitOutcome.remainingProjectileDamage <= 0.0f) { damageMultiplier = 0.0f; setBarrierSparkTicks(Math.max(getBarrierSparkTicks(), BARRIER_BREAK_SPARK_TICKS)); @@ -511,7 +511,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { return true; } - protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) { + protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) { if (barrier == null) { return false; } @@ -582,14 +582,22 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { } sourceAbility = null; + // Save original owner before transfer for potential target retargeting + int originalOwnerId = ownerEntityId; + Entity barrierOwner = barrier.getOwnerEntity(); if (barrierOwner != null) { setOwnerEntityId(barrierOwner.getEntityId()); // Ensure ownership-sensitive systems can query this projectile under the new owner. trackProjectile(this); } - // Old homing target may now be the new owner or ally; clear it after reflection. - setTargetEntityId(-1); + + // Target Owner: set the reflected projectile's target to the original caster + if (barrier.getBarrierData().isTargetOwner() && originalOwnerId != -1) { + setTargetEntityId(originalOwnerId); + } else { + setTargetEntityId(-1); + } setInnerColor(barrier.getInnerColor()); setOuterColor(barrier.getOuterColor()); @@ -672,14 +680,14 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { ProjectileReflectPacket.sendToTracking(this, writeReflectionData()); } - protected double[] getBarrierImpactNormal(EntityAbilityBarrier barrier, double velocityX, double velocityY, double velocityZ) { - if (barrier instanceof EntityAbilityDome) { - EntityAbilityDome dome = (EntityAbilityDome) barrier; + protected double[] getBarrierImpactNormal(EntityEnergyBarrier barrier, double velocityX, double velocityY, double velocityZ) { + if (barrier instanceof EntityEnergyDome) { + EntityEnergyDome dome = (EntityEnergyDome) barrier; return normalizeVector(posX - dome.posX, posY - dome.posY, posZ - dome.posZ, velocityX, velocityY, velocityZ); } - if (barrier instanceof EntityAbilityPanel) { - EntityAbilityPanel panel = (EntityAbilityPanel) barrier; + if (barrier instanceof EntityEnergyPanel) { + EntityEnergyPanel panel = (EntityEnergyPanel) barrier; float yawRad = (float) Math.toRadians(panel.getPanelYaw()); double nx = -Math.sin(yawRad); double nz = Math.cos(yawRad); @@ -716,7 +724,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { return new double[]{0.0, 1.0, 0.0}; } - protected void beginBarrierImpactPause(boolean destroyOnResume, EntityAbilityBarrier barrier) { + protected void beginBarrierImpactPause(boolean destroyOnResume, EntityEnergyBarrier barrier) { if (barrierImpactPauseTicks <= 0) { pausedMotionX = motionX; pausedMotionY = motionY; @@ -740,12 +748,12 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { return Math.max(0.06f, Math.min(0.22f, size * 0.18f + 0.03f)); } - protected void snapOutsideBarrierForPause(EntityAbilityBarrier barrier) { + protected void snapOutsideBarrierForPause(EntityEnergyBarrier barrier) { if (barrier == null) return; float bias = getBarrierPauseOutsideDistance(); - if (barrier instanceof EntityAbilityDome) { - EntityAbilityDome dome = (EntityAbilityDome) barrier; + if (barrier instanceof EntityEnergyDome) { + EntityEnergyDome dome = (EntityEnergyDome) barrier; double nx = posX - dome.posX; double ny = posY - dome.posY; double nz = posZ - dome.posZ; @@ -776,8 +784,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility { return; } - if (barrier instanceof EntityAbilityPanel) { - EntityAbilityPanel panel = (EntityAbilityPanel) barrier; + if (barrier instanceof EntityEnergyPanel) { + EntityEnergyPanel panel = (EntityEnergyPanel) barrier; float yawRad = (float) Math.toRadians(panel.getPanelYaw()); double normalX = -Math.sin(yawRad); double normalZ = Math.cos(yawRad); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java similarity index 96% rename from src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java rename to src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java index 69d43da0c..e64b0f6eb 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityEnergySweeper.java @@ -29,7 +29,7 @@ import java.util.Set; *

* Design: Similar to Beam trail visuals but rotating around origin. */ -public class EntityAbilitySweeper extends EntityEnergyAbility { +public class EntityEnergySweeper extends EntityEnergyAbility { // Beam properties private float beamLength = 10.0f; @@ -61,18 +61,18 @@ public class EntityAbilitySweeper extends EntityEnergyAbility { private transient int ticksSinceDamage = 0; private transient Set hitThisTick = new HashSet<>(); - public EntityAbilitySweeper(World world) { + public EntityEnergySweeper(World world) { super(world); this.setSize(0.1f, 0.1f); this.noClip = true; } - public EntityAbilitySweeper(World world, EntityLivingBase owner, EntityLivingBase target, - float beamLength, float beamWidth, float beamHeight, - EnergyDisplayData displayData, - float sweepSpeed, int numberOfRotations, - float damage, int damageInterval, boolean piercing, - boolean lockOnTarget) { + public EntityEnergySweeper(World world, EntityLivingBase owner, EntityLivingBase target, + float beamLength, float beamWidth, float beamHeight, + EnergyDisplayData displayData, + float sweepSpeed, int numberOfRotations, + float damage, int damageInterval, boolean piercing, + boolean lockOnTarget) { this(world); this.ownerEntityId = owner.getEntityId(); diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index a66f56fc4..7c73a3edb 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -226,6 +226,8 @@ import kamkeel.npcs.network.packets.request.role.RoleCompanionUpdatePacket; import kamkeel.npcs.network.packets.request.role.RoleGetPacket; import kamkeel.npcs.network.packets.request.role.RoleSavePacket; import kamkeel.npcs.network.packets.request.script.BlockScriptPacket; +import kamkeel.npcs.network.packets.request.script.AbilityScriptPacket; +import kamkeel.npcs.network.packets.request.script.ChainedAbilityScriptPacket; import kamkeel.npcs.network.packets.request.script.EffectScriptPacket; import kamkeel.npcs.network.packets.request.script.EventScriptPacket; import kamkeel.npcs.network.packets.request.script.ForgeScriptPacket; @@ -316,6 +318,8 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new ScriptInfoPacket()); REQUEST_PACKET.registerPacket(new ScriptFilesPacket()); REQUEST_PACKET.registerPacket(new EffectScriptPacket()); + REQUEST_PACKET.registerPacket(new AbilityScriptPacket()); + REQUEST_PACKET.registerPacket(new ChainedAbilityScriptPacket()); // Cloner Packets REQUEST_PACKET.registerPacket(new CloneListPacket()); diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java index 8592163be..03e605af7 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java @@ -214,4 +214,6 @@ public enum EnumRequestPacket { RecipeScript, ManageAuctionAction, + AbilityScript, + ChainedAbilityScript, } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java index 67a8f8241..42a63a79e 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java @@ -62,7 +62,7 @@ public final class BuiltInAbilityGetPacket extends AbstractPacket { String name = ByteBufUtils.readString(in); Ability ability = AbilityController.Instance.getAbilityByDisplayName(name); if (ability != null) { - NBTTagCompound compound = ability.writeNBT(); + NBTTagCompound compound = ability.writeNBT(false); compound.setBoolean("BuiltIn", true); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java index 2bcc48601..cecc8c9e5 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilityGetPacket.java @@ -61,7 +61,7 @@ public final class ChainedAbilityGetPacket extends AbstractPacket { String chainName = ByteBufUtils.readString(in); ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName); if (chain != null) { - NBTTagCompound compound = chain.writeNBT(); + NBTTagCompound compound = chain.writeNBT(false); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java index e4564e8f0..f270a8785 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/ChainedAbilitySavePacket.java @@ -73,7 +73,7 @@ public final class ChainedAbilitySavePacket extends AbstractPacket { if (chain.getName() != null && !chain.getName().isEmpty()) { AbilityController.Instance.saveChainedAbility(chain); NoppesUtilServer.sendChainedAbilitiesData((EntityPlayerMP) player); - GuiDataPacket.sendGuiData((EntityPlayerMP) player, chain.writeNBT()); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, chain.writeNBT(false)); } } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java index b4588935b..b0556926a 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilityGetPacket.java @@ -61,7 +61,7 @@ public final class CustomAbilityGetPacket extends AbstractPacket { String abilityName = ByteBufUtils.readString(in); Ability ability = AbilityController.Instance.getCustomAbility(abilityName); if (ability != null) { - NBTTagCompound compound = ability.writeNBT(); + NBTTagCompound compound = ability.writeNBT(false); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java index f360b0eff..3d91f5a86 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitySavePacket.java @@ -70,7 +70,7 @@ public final class CustomAbilitySavePacket extends AbstractPacket { if (ability != null) { AbilityController.Instance.saveCustomAbility(ability); NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); - NBTTagCompound responseNbt = ability.writeNBT(); + NBTTagCompound responseNbt = ability.writeNBT(false); GuiDataPacket.sendGuiData((EntityPlayerMP) player, responseNbt); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/AbilityScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/AbilityScriptPacket.java new file mode 100644 index 000000000..411d98a00 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/AbilityScriptPacket.java @@ -0,0 +1,117 @@ +package kamkeel.npcs.network.packets.request.script; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.LogWriter; +import noppes.npcs.config.ConfigDebug; +import noppes.npcs.config.ConfigScript; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.IScriptHandler; + +import java.io.IOException; + +public final class AbilityScriptPacket extends AbstractPacket { + public static String packetName = "Request|AbilityScript"; + + private Action type; + private String abilityId; + private int page; + private int maxSize; + private NBTTagCompound compound; + + public AbilityScriptPacket() { + } + + public AbilityScriptPacket(Action type, String abilityId, int page, int maxSize, NBTTagCompound compound) { + this.type = type; + this.abilityId = abilityId; + this.page = page; + this.maxSize = maxSize; + this.compound = compound; + } + + @Override + public Enum getType() { + return EnumRequestPacket.AbilityScript; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.SCRIPT_PLAYER; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(type.ordinal()); + ByteBufUtils.writeUTF8String(out, abilityId); + + if (type == Action.SAVE) { + out.writeInt(this.page); + out.writeInt(this.maxSize); + ByteBufUtils.writeNBT(out, this.compound); + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) + return; + + Action requestedAction = Action.values()[in.readInt()]; + String id = ByteBufUtils.readUTF8String(in); + + Ability ability = AbilityController.Instance.resolveAbility(id); + if (ability == null) + return; + + AbilityScript data = ability.getOrCreateScriptHandler(); + if (requestedAction == Action.GET) { + PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player); + } else { + data.saveScript(in); + // Persist to disk + AbilityController.Instance.saveCustomAbility(ability); + if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { + LogWriter.script(String.format("[%s] (Player) %s SAVED ABILITY SCRIPT %s [%s]", + "ABILITY SCRIPTS", player.getCommandSenderName(), ability.getName(), ability.getId())); + } + } + } + + public static void Save(String abilityId, int id, int maxSize, NBTTagCompound compound) { + PacketClient.sendClient(new AbilityScriptPacket(Action.SAVE, abilityId, id, maxSize, compound)); + } + + public static void Get(String abilityId) { + PacketClient.sendClient(new AbilityScriptPacket(Action.GET, abilityId, -1, -1, new NBTTagCompound())); + } + + private enum Action { + GET, + SAVE + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/ChainedAbilityScriptPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/ChainedAbilityScriptPacket.java new file mode 100644 index 000000000..2589b0e13 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/ChainedAbilityScriptPacket.java @@ -0,0 +1,117 @@ +package kamkeel.npcs.network.packets.request.script; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.AbilityController; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.LogWriter; +import noppes.npcs.config.ConfigDebug; +import noppes.npcs.config.ConfigScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import noppes.npcs.controllers.data.IScriptHandler; + +import java.io.IOException; + +public final class ChainedAbilityScriptPacket extends AbstractPacket { + public static String packetName = "Request|ChainedAbilityScript"; + + private Action type; + private String chainId; + private int page; + private int maxSize; + private NBTTagCompound compound; + + public ChainedAbilityScriptPacket() { + } + + public ChainedAbilityScriptPacket(Action type, String chainId, int page, int maxSize, NBTTagCompound compound) { + this.type = type; + this.chainId = chainId; + this.page = page; + this.maxSize = maxSize; + this.compound = compound; + } + + @Override + public Enum getType() { + return EnumRequestPacket.ChainedAbilityScript; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.SCRIPT_PLAYER; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeInt(type.ordinal()); + ByteBufUtils.writeUTF8String(out, chainId); + + if (type == Action.SAVE) { + out.writeInt(this.page); + out.writeInt(this.maxSize); + ByteBufUtils.writeNBT(out, this.compound); + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) + return; + + Action requestedAction = Action.values()[in.readInt()]; + String id = ByteBufUtils.readUTF8String(in); + + ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(id); + if (chain == null) + return; + + ChainedAbilityScript data = chain.getOrCreateScriptHandler(); + if (requestedAction == Action.GET) { + PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player); + } else { + data.saveScript(in); + // Persist to disk + AbilityController.Instance.saveChainedAbility(chain); + if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { + LogWriter.script(String.format("[%s] (Player) %s SAVED CHAIN SCRIPT %s [%s]", + "CHAIN SCRIPTS", player.getCommandSenderName(), chain.getName(), chain.getId())); + } + } + } + + public static void Save(String chainId, int id, int maxSize, NBTTagCompound compound) { + PacketClient.sendClient(new ChainedAbilityScriptPacket(Action.SAVE, chainId, id, maxSize, compound)); + } + + public static void Get(String chainId) { + PacketClient.sendClient(new ChainedAbilityScriptPacket(Action.GET, chainId, -1, -1, new NBTTagCompound())); + } + + private enum Action { + GET, + SAVE + } +} diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index a01ef84c1..53f4f092b 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -93,7 +93,7 @@ public class Register { public void register() { for (Map.Entry> entry : entries.entrySet()) { - AbilityController.Instance.registerType(entry.getKey(), entry.getValue()); + AbilityController.Instance.registerType(entry.getValue()); if (!typeOnly.contains(entry.getKey())) { AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get()); } diff --git a/src/main/java/noppes/npcs/AbstractDataAbilities.java b/src/main/java/noppes/npcs/AbstractDataAbilities.java index 58a8c2fb3..3f44394f3 100644 --- a/src/main/java/noppes/npcs/AbstractDataAbilities.java +++ b/src/main/java/noppes/npcs/AbstractDataAbilities.java @@ -2,6 +2,7 @@ package noppes.npcs; import kamkeel.npcs.controllers.AbilityController; import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; @@ -11,6 +12,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.DamageSource; import noppes.npcs.controllers.AnimationController; +import noppes.npcs.scripted.event.AbilityEvent; import noppes.npcs.controllers.data.Animation; import java.util.ArrayList; @@ -124,28 +126,53 @@ public abstract class AbstractDataAbilities { */ protected abstract long getWorldTime(); - // -- Event Firing -- + // -- Event Firing (unified via EventHooks) -- - /** - * Fire tick event. Implementation differs between NPC (NpcAPI) and Player (ScriptController). - */ - protected abstract void fireTickEvent(Ability ability, EntityLivingBase target); + protected void fireTickEvent(Ability ability, EntityLivingBase target) { + EventHooks.onAbilityTick(ability, getEntity(), target, ability.getPhase().ordinal(), ability.getCurrentTick()); + } - /** - * Fire execute event. Returns true if cancelled. - */ - protected abstract boolean fireExecuteEvent(Ability ability, EntityLivingBase target); + protected boolean fireExecuteEvent(Ability ability, EntityLivingBase target) { + return EventHooks.onAbilityExecute(ability, getEntity(), target); + } - /** - * Fire complete event. - */ - protected abstract void fireCompleteEvent(Ability ability, EntityLivingBase target); + protected void fireCompleteEvent(Ability ability, EntityLivingBase target) { + EventHooks.onAbilityComplete(ability, getEntity(), target); + } - /** - * Fire interrupt event. - */ - protected abstract void fireInterruptEvent(Ability ability, EntityLivingBase target, - DamageSource source, float damage); + protected void fireInterruptEvent(Ability ability, EntityLivingBase target, + DamageSource source, float damage) { + EventHooks.onAbilityInterrupt(ability, getEntity(), target, source, damage); + } + + protected boolean fireToggleEvent(Ability ability, int oldState, int newState) { + return EventHooks.onAbilityToggle(ability, getEntity(), oldState, newState); + } + + protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) { + AbilityEvent.ToggleUpdateEvent event = new AbilityEvent.ToggleUpdateEvent(getEntity(), ability, tick, state); + EventHooks.onAbilityToggleUpdate(ability, event); + return event.isEnabled(); + } + + // -- Chain Events (unified via EventHooks) -- + + protected void fireChainStartEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) { + EventHooks.onChainStart(chain, getEntity(), entryIndex, target); + } + + protected void fireChainNextEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) { + EventHooks.onChainNext(chain, getEntity(), entryIndex, target); + } + + protected void fireChainCompleteEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) { + EventHooks.onChainComplete(chain, getEntity(), entryIndex, target); + } + + protected void fireChainInterruptEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target, + DamageSource source, float damage) { + EventHooks.onChainInterrupt(chain, getEntity(), entryIndex, target, source, damage); + } // -- Telegraph -- @@ -291,6 +318,19 @@ public abstract class AbstractDataAbilities { return currentAbility; } + /** + * Get the active defend ability if one is currently defending. + */ + public AbilityDefend getActiveDefend() { + if (currentAbility instanceof AbilityDefend) { + AbilityDefend defend = (AbilityDefend) currentAbility; + if (defend.isDefending()) { + return defend; + } + } + return null; + } + /** * Check if a chained ability is currently executing. */ @@ -391,8 +431,7 @@ public abstract class AbstractDataAbilities { AbilityToggleEntry entry = new AbilityToggleEntry(ability, state); activeToggles.put(key, entry); - ability.onToggleOn(getEntity()); - ability.onToggleStateChanged(getEntity(), 0, state); + ability.onToggle(getEntity(), 0, state); onToggleStateChanged(key, true, state); return true; } @@ -404,7 +443,7 @@ public abstract class AbstractDataAbilities { if (fireToggleEvent(ability, oldState, newState)) return oldState; entry.setState(newState); - ability.onToggleStateChanged(getEntity(), oldState, newState); + ability.onToggle(getEntity(), oldState, newState); onToggleStateChanged(key, true, newState); return newState; } @@ -417,8 +456,7 @@ public abstract class AbstractDataAbilities { if (fireToggleEvent(entry.getAbility(), oldState, 0)) return; activeToggles.remove(key); - entry.getAbility().onToggleOff(getEntity()); - entry.getAbility().onToggleStateChanged(getEntity(), oldState, 0); + entry.getAbility().onToggle(getEntity(), oldState, 0); onToggleStateChanged(key, false, 0); } @@ -460,8 +498,7 @@ public abstract class AbstractDataAbilities { AbilityToggleEntry entry = activeToggles.remove(key); if (entry != null) { int oldState = entry.getState(); - entry.getAbility().onToggleOff(entity); - entry.getAbility().onToggleStateChanged(entity, oldState, 0); + entry.getAbility().onToggle(entity, oldState, 0); onToggleStateChanged(key, false, 0); } } @@ -474,41 +511,23 @@ public abstract class AbstractDataAbilities { protected void onToggleStateChanged(String key, boolean active, int state) { } - /** - * Fire a toggle event before state change. - * @param oldState Previous state (0 = off) - * @param newState Target state (0 = off) - * @return true if the event was canceled - */ - protected boolean fireToggleEvent(Ability ability, int oldState, int newState) { - return false; - } - - /** - * Fire a toggle update event every 10 ticks. - * @return true if the toggle should remain active, false to force-deactivate - */ - protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) { - return true; - } /** * Clear all active toggles (e.g., on death/reset). - * Calls onToggleOff and onToggleStateChanged for each active toggle. + * Calls onToggle for each active toggle to signal deactivation. */ protected void clearActiveToggles() { if (activeToggles.isEmpty()) return; EntityLivingBase entity = getEntity(); for (Map.Entry mapEntry : activeToggles.entrySet()) { AbilityToggleEntry entry = mapEntry.getValue(); - entry.getAbility().onToggleOff(entity); - entry.getAbility().onToggleStateChanged(entity, entry.getState(), 0); + entry.getAbility().onToggle(entity, entry.getState(), 0); } activeToggles.clear(); } /** - * Add a toggle entry directly without calling onToggleOn. + * Add a toggle entry directly without calling onToggle. * Used for client-side sync and NBT restoration. * @param key The ability key * @param state The toggle state (0 = remove, 1+ = set at state) @@ -747,6 +766,7 @@ public abstract class AbstractDataAbilities { } } if (startChainEntry(chainTarget)) { + fireChainNextEvent(currentChain, chainEntryIndex, chainTarget); launchConsecutiveConcurrentEntries(chainTarget); } } @@ -849,6 +869,24 @@ public abstract class AbstractDataAbilities { currentAbility.onActiveTick(entity, target, currentAbility.getCurrentTick()); + // Play pending defend reaction animation + sound (counter strike, dodge roll, etc.) + if (currentAbility instanceof AbilityDefend) { + AbilityDefend defend = (AbilityDefend) currentAbility; + Animation defendAnim = defend.consumeDefendAnimation(); + if (defendAnim != null) { + playAbilityAnimation(defendAnim); + playAbilitySound(currentAbility.getActiveSound()); + defend.scheduleReturnToActive(currentAbility.getCurrentTick(), defendAnim); + } + // Return to active animation after defend animation finishes (Counter → guard stance) + if (defend.shouldReturnToActiveAnimation(currentAbility.getCurrentTick())) { + Animation activeAnim = currentAbility.getActiveAnimation(); + if (activeAnim != null) { + playAbilityAnimation(activeAnim); + } + } + } + // Check if ability completed during onActiveTick if (currentAbility.getPhase() == AbilityPhase.IDLE) { handleAbilityCompletion(target); @@ -1036,10 +1074,11 @@ public abstract class AbstractDataAbilities { releaseRotationControl(); releaseLockedPosition(); - // If chain was active, roll chain cooldown and clear chain state + // If chain was active, fire interrupt event, roll cooldown and clear chain state if (currentChain != null) { rollChainCooldown(currentChain); interruptCooldownRolled = true; + fireChainInterruptEvent(currentChain, chainEntryIndex, getTarget(), source, damage); currentChain = null; chainEntryIndex = -1; chainDelayRemaining = -1; @@ -1116,6 +1155,25 @@ public abstract class AbstractDataAbilities { onAbilityComplete(); } + /** + * Cleanly complete the currently executing ability. + * Unlike cancel/interrupt, this triggers the normal completion path + * (fires abilityComplete event, rolls cooldown, advances chains). + * Only works during the ACTIVE phase. + */ + public void completeCurrentAbility() { + if (currentAbility == null || !currentAbility.isExecuting()) return; + if (currentAbility.getPhase() != AbilityPhase.ACTIVE) return; + + // Signal completion on the ability (handles cleanup, detach/freeOnCast, burst logic) + if (!currentAbility.signalCompletion()) return; + + // If signalCompletion moved to IDLE, handle the clean completion path + if (currentAbility.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(getTarget()); + } + } + // ═══════════════════════════════════════════════════════════════════ // CHAINED ABILITY EXECUTION // ═══════════════════════════════════════════════════════════════════ @@ -1137,6 +1195,7 @@ public abstract class AbstractDataAbilities { // AFTER semantics: no delay before first entry (delay applies after each entry completes) boolean started = startChainEntry(target); if (started) { + fireChainStartEvent(currentChain, 0, target); launchConsecutiveConcurrentEntries(target); } return started; @@ -1253,7 +1312,7 @@ public abstract class AbstractDataAbilities { chainEntryIndex++; // Deep copy the ability so it has its own state - Ability concurrentCopy = AbilityController.Instance.fromNBT(resolved.writeNBT()); + Ability concurrentCopy = AbilityController.Instance.fromNBT(resolved.writeNBT(true)); if (concurrentCopy == null) continue; ConcurrentSlot slot = new ConcurrentSlot(concurrentCopy); @@ -1279,6 +1338,7 @@ public abstract class AbstractDataAbilities { protected void completeChain() { if (currentChain != null) { rollChainCooldown(currentChain); + fireChainCompleteEvent(currentChain, chainEntryIndex, getTarget()); } currentChain = null; chainEntryIndex = -1; diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 73f87c7f6..32ac9b796 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -29,15 +29,15 @@ import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker; import kamkeel.npcs.controllers.data.profile.CNPCData; import kamkeel.npcs.developer.Developer; -import kamkeel.npcs.entity.EntityAbilityBarrier; +import kamkeel.npcs.entity.EntityEnergyBarrier; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.entity.EntityAbilityPanel; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityEnergySweeper; import kamkeel.npcs.entity.EntityAbilityZone; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyDome; import kamkeel.npcs.entity.EntityEnergyProjectile; import kamkeel.npcs.entity.EntityEnergySlicer; import kamkeel.npcs.network.PacketHandler; @@ -298,10 +298,10 @@ public class CustomNpcs { registerNewEntity(EntityAbilityDisc.class, "abilitydisc", 64, 1, true); registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 1, true); registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 160, 1, true); - registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true); + registerNewEntity(EntityEnergySweeper.class, "abilitysweeper", 64, 3, true); registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true); - registerNewEntity(EntityAbilityDome.class, "energydome", 64, 3, true); - registerNewEntity(EntityAbilityPanel.class, "energypanel", 64, 3, true); + registerNewEntity(EntityEnergyDome.class, "energydome", 64, 3, true); + registerNewEntity(EntityEnergyPanel.class, "energypanel", 64, 3, true); registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 1, true); new RecipeController(); @@ -433,7 +433,7 @@ public class CustomNpcs { } EntityEnergyProjectile.clearAllProjectiles(); - EntityAbilityBarrier.clearAllBarriers(); + EntityEnergyBarrier.clearAllBarriers(); EnergyChargeTracker.Instance.clear(); if (FMLCommonHandler.instance().getSide().isClient()) diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 31b6b02c6..e56bf772d 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -7,18 +7,19 @@ import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry; -import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.DamageSource; import noppes.npcs.controllers.data.Animation; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AbilityEvent; +import noppes.npcs.EventHooks; import java.util.ArrayList; import java.util.List; @@ -124,51 +125,6 @@ public class DataAbilities extends AbstractDataAbilities { return npc.worldObj.getTotalWorldTime(); } - @Override - protected void fireTickEvent(Ability ability, EntityLivingBase target) { - AbilityEvent.TickEvent event = new AbilityEvent.TickEvent( - npc.wrappedNPC, ability, target, - ability.getPhase().ordinal(), ability.getCurrentTick()); - NpcAPI.EVENT_BUS.post(event); - } - - @Override - protected boolean fireExecuteEvent(Ability ability, EntityLivingBase target) { - AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent( - npc.wrappedNPC, ability, target); - return NpcAPI.EVENT_BUS.post(executeEvent); - } - - @Override - protected void fireCompleteEvent(Ability ability, EntityLivingBase target) { - AbilityEvent.CompleteEvent completeEvent = new AbilityEvent.CompleteEvent( - npc.wrappedNPC, ability, target); - NpcAPI.EVENT_BUS.post(completeEvent); - } - - @Override - protected void fireInterruptEvent(Ability ability, EntityLivingBase target, - DamageSource source, float damage) { - AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent( - npc.wrappedNPC, ability, target, source, damage); - NpcAPI.EVENT_BUS.post(interruptEvent); - } - - @Override - protected boolean fireToggleEvent(Ability ability, int oldState, int newState) { - AbilityEvent.ToggleEvent event = new AbilityEvent.ToggleEvent( - npc.wrappedNPC, ability, oldState, newState); - return NpcAPI.EVENT_BUS.post(event); - } - - @Override - protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) { - AbilityEvent.ToggleUpdateEvent event = new AbilityEvent.ToggleUpdateEvent( - npc.wrappedNPC, ability, tick, state); - NpcAPI.EVENT_BUS.post(event); - return event.isEnabled(); - } - @Override protected void spawnTelegraph(Ability ability, EntityLivingBase target) { List telegraphs = ability.createTelegraphs(npc, target); @@ -502,10 +458,7 @@ public class DataAbilities extends AbstractDataAbilities { */ private boolean startAbility(Ability ability, EntityLivingBase target) { // Fire start event (cancelable) - AbilityEvent.StartEvent startEvent = new AbilityEvent.StartEvent( - npc.wrappedNPC, ability, target); - if (NpcAPI.EVENT_BUS.post(startEvent)) { - // Event was cancelled - don't start the ability + if (EventHooks.onAbilityStart(ability, npc, target)) { return false; } @@ -564,11 +517,6 @@ public class DataAbilities extends AbstractDataAbilities { // Track hit for hit count condition recordHit(); - - net.minecraft.entity.Entity sourceEntity = source.getEntity(); - EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null; - currentAbility.onDamageTaken(npc, attacker, source, amount); - if (currentAbility.canInterrupt(source)) { interruptCurrentAbility(source, amount); return true; @@ -577,18 +525,6 @@ public class DataAbilities extends AbstractDataAbilities { return false; } - /** - * Get the damage reduction factor if a Guard ability is currently active. - * - * @return The damage reduction factor (0.0 = no reduction, 1.0 = full immunity), or 0 if not guarding - */ - public float getGuardDamageReduction() { - if (currentAbility instanceof AbilityGuard) { - return ((AbilityGuard) currentAbility).getDamageReductionFactor(); - } - return 0.0f; - } - /** * Record a hit for the hit count condition. * Includes periodic cleanup to prevent memory leak. @@ -698,29 +634,6 @@ public class DataAbilities extends AbstractDataAbilities { // SCRIPT EVENTS // ═══════════════════════════════════════════════════════════════════ - /** - * Fire an ability hit event. Called by abilities when they hit an entity. - * Returns null if the event was cancelled, otherwise returns the (possibly modified) event. - * - * @param ability The ability doing the hit - * @param target The original target of the ability - * @param hitEntity The entity being hit - * @param damage The damage amount - * @param knockback The horizontal knockback - * @param knockbackUp The vertical knockback - * @return The event (with possibly modified values), or null if cancelled - */ - public AbilityEvent.HitEvent fireHitEvent(Ability ability, EntityLivingBase target, - EntityLivingBase hitEntity, float damage, - float knockback, float knockbackUp) { - AbilityEvent.HitEvent event = new AbilityEvent.HitEvent( - npc.wrappedNPC, ability, target, hitEntity, damage, knockback, knockbackUp); - if (NpcAPI.EVENT_BUS.post(event)) { - return null; // Cancelled - } - return event; - } - /** * Get the NPC this DataAbilities belongs to. */ @@ -1091,7 +1004,7 @@ public class DataAbilities extends AbstractDataAbilities { NBTTagList actionList = new NBTTagList(); for (AbilityAction slot : actionSlots) { - actionList.appendTag(slot.writeNBT()); + actionList.appendTag(slot.writeNBT(true)); } compound.setTag("AbilityActions", actionList); @@ -1146,7 +1059,7 @@ public class DataAbilities extends AbstractDataAbilities { } } - // Active toggles - restore state directly (no onToggleOn callback during load) + // Active toggles - restore state directly (no onToggle callback during load) activeToggles.clear(); if (compound.hasKey("ActiveToggles")) { NBTTagList toggleNbt = compound.getTagList("ActiveToggles", 10); // 10 = TAG_COMPOUND diff --git a/src/main/java/noppes/npcs/EventHooks.java b/src/main/java/noppes/npcs/EventHooks.java index 76029adab..7063b7653 100644 --- a/src/main/java/noppes/npcs/EventHooks.java +++ b/src/main/java/noppes/npcs/EventHooks.java @@ -53,7 +53,16 @@ import noppes.npcs.controllers.data.RecipeScript; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.entity.EntityProjectile; import noppes.npcs.scripted.NpcAPI; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.api.event.IAbilityEvent; +import noppes.npcs.api.event.IChainEvent; +import noppes.npcs.controllers.data.AbilityScript; +import noppes.npcs.controllers.data.ChainedAbilityScript; +import noppes.npcs.scripted.event.AbilityEvent; import noppes.npcs.scripted.event.AnimationEvent; +import noppes.npcs.scripted.event.ChainEvent; import noppes.npcs.scripted.event.BlockEvent; import noppes.npcs.scripted.event.CustomNPCsEvent; import noppes.npcs.scripted.event.EnergyProjectileEvent; @@ -68,7 +77,6 @@ import noppes.npcs.scripted.event.player.AuctionEvent; import noppes.npcs.scripted.event.player.CustomGuiEvent; import noppes.npcs.scripted.event.player.DialogEvent; import noppes.npcs.scripted.event.player.FactionEvent; -import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import noppes.npcs.scripted.event.player.PlayerEvent; import noppes.npcs.scripted.event.player.PlayerEvent.ChatEvent; import noppes.npcs.scripted.event.player.PlayerEvent.ContainerOpen; @@ -851,44 +859,146 @@ public class EventHooks { return NpcAPI.EVENT_BUS.post(event); } - public static boolean onPlayerAbilityStart(PlayerDataScript handler, PlayerAbilityEvent.StartEvent event) { - handler.callScript(EnumScriptType.ABILITY_START, event); + // ==================== ABILITY EVENTS (Unified NPC/Player) ==================== + + private static IScriptHandler getEntityScriptHandler(IEntityLivingBase entity) { + if (entity instanceof ICustomNpc) { + return ((EntityNPCInterface) ((ICustomNpc) entity).getMCEntity()).script; + } else if (entity instanceof IPlayer && ScriptController.Instance != null) { + return ScriptController.Instance.getPlayerScripts( + (EntityPlayer) ((IPlayer) entity).getMCEntity()); + } + return null; + } + + /** + * Dispatches an ability event through the three-tier routing chain: + *

    + *
  1. AbilityScript — fires for BOTH NPC and Player casters
  2. + *
  3. Entity script handler — routes to the caster's own handler: + * NPC casters fire on the NPC script handler only, + * Player casters fire on the Player script handler only
  4. + *
  5. EVENT_BUS — global event bus, fires last
  6. + *
+ * + * @return true if the event was cancelled (for @Cancelable events) + */ + private static boolean postAbilityEvent(Ability ability, Event event) { + IAbilityEvent abilityEvent = (IAbilityEvent) event; + + // 1. Internal ability script (fires for ALL — both NPC and Player) + AbilityScript abScript = ability.getScriptHandler(); + if (abScript != null) { + abScript.callScript(abilityEvent.getHookName(), event); + } + + // Short-circuit if cancelled by ability script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 2. Entity script handler (NPC → NPC handler, Player → Player handler, never cross-fires) + IScriptHandler handler = getEntityScriptHandler(abilityEvent.getEntity()); + if (handler != null && !handler.isClient()) { + handler.callScript(abilityEvent.getHookName(), event); + } + + // Short-circuit if cancelled by entity script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 3. EVENT_BUS (global — fires last) return NpcAPI.EVENT_BUS.post(event); } - public static boolean onPlayerAbilityExecute(PlayerDataScript handler, PlayerAbilityEvent.ExecuteEvent event) { - handler.callScript(EnumScriptType.ABILITY_EXECUTE, event); + private static boolean postChainEvent(ChainedAbility chain, Event event) { + IChainEvent chainEvent = (IChainEvent) event; + + // 1. Internal chain script (fires first) + ChainedAbilityScript chainScript = chain.getScriptHandler(); + if (chainScript != null) { + chainScript.callScript(chainEvent.getHookName(), event); + } + + // Short-circuit if cancelled by chain script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 2. Entity script handler (NPC or Player) + IScriptHandler handler = getEntityScriptHandler(chainEvent.getEntity()); + if (handler != null && !handler.isClient()) { + handler.callScript(chainEvent.getHookName(), event); + } + + // Short-circuit if cancelled by entity script + if (event.isCancelable() && event.isCanceled()) { + return true; + } + + // 3. EVENT_BUS (global — fires last) return NpcAPI.EVENT_BUS.post(event); } - public static void onPlayerAbilityTick(PlayerDataScript handler, PlayerAbilityEvent.TickEvent event) { - handler.callScript(EnumScriptType.ABILITY_TICK, event); - NpcAPI.EVENT_BUS.post(event); + public static boolean onAbilityStart(Ability ability, EntityLivingBase entity, EntityLivingBase target) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.StartEvent(entity, ability, target)); } - public static void onPlayerAbilityInterrupt(PlayerDataScript handler, PlayerAbilityEvent.InterruptEvent event) { - handler.callScript(EnumScriptType.ABILITY_INTERRUPT, event); - NpcAPI.EVENT_BUS.post(event); + public static boolean onAbilityExecute(Ability ability, EntityLivingBase entity, EntityLivingBase target) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.ExecuteEvent(entity, ability, target)); } - public static void onPlayerAbilityComplete(PlayerDataScript handler, PlayerAbilityEvent.CompleteEvent event) { - handler.callScript(EnumScriptType.ABILITY_COMPLETE, event); - NpcAPI.EVENT_BUS.post(event); + public static boolean onAbilityTick(Ability ability, EntityLivingBase entity, EntityLivingBase target, int phase, int tick) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.TickEvent(entity, ability, target, phase, tick)); } - public static boolean onPlayerAbilityHit(PlayerDataScript handler, PlayerAbilityEvent.HitEvent event) { - handler.callScript(EnumScriptType.ABILITY_HIT, event); - return NpcAPI.EVENT_BUS.post(event); + public static boolean onAbilityComplete(Ability ability, EntityLivingBase entity, EntityLivingBase target) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.CompleteEvent(entity, ability, target)); } - public static boolean onPlayerAbilityToggle(PlayerDataScript handler, PlayerAbilityEvent.ToggleEvent event) { - handler.callScript(EnumScriptType.ABILITY_TOGGLE, event); - return NpcAPI.EVENT_BUS.post(event); + public static boolean onAbilityInterrupt(Ability ability, EntityLivingBase entity, EntityLivingBase target, + DamageSource source, float damage) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.InterruptEvent(entity, ability, target, source, damage)); } - public static void onPlayerAbilityToggleUpdate(PlayerDataScript handler, PlayerAbilityEvent.ToggleUpdateEvent event) { - handler.callScript(EnumScriptType.ABILITY_TOGGLE_UPDATE, event); - NpcAPI.EVENT_BUS.post(event); + public static boolean onAbilityHit(Ability ability, AbilityEvent.HitEvent event) { + if (ability == null || event == null) return false; + return postAbilityEvent(ability, event); + } + + public static boolean onAbilityToggle(Ability ability, EntityLivingBase entity, int oldState, int newState) { + if (ability == null || entity == null) return false; + return postAbilityEvent(ability, new AbilityEvent.ToggleEvent(entity, ability, oldState, newState)); + } + + public static boolean onAbilityToggleUpdate(Ability ability, AbilityEvent.ToggleUpdateEvent event) { + if (ability == null || event == null) return false; + return postAbilityEvent(ability, event); + } + + // Chain events + + public static void onChainStart(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) { + postChainEvent(chain, new ChainEvent.StartEvent(entity, chain, entryIndex, target)); + } + + public static void onChainNext(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) { + postChainEvent(chain, new ChainEvent.NextEvent(entity, chain, entryIndex, target)); + } + + public static void onChainComplete(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) { + postChainEvent(chain, new ChainEvent.CompleteEvent(entity, chain, entryIndex, target)); + } + + public static void onChainInterrupt(ChainedAbility chain, EntityLivingBase entity, int entryIndex, + EntityLivingBase target, DamageSource source, float damage) { + postChainEvent(chain, new ChainEvent.InterruptEvent(entity, chain, entryIndex, target, source, damage)); } public static void onPlayerChangeDim(PlayerDataScript handler, IPlayer player, int fromDim, int toDim) { diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 3da3ccc56..27db9ae4e 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -10,10 +10,15 @@ 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.controllers.data.ability.type.AbilityCounter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; +import kamkeel.npcs.controllers.data.ability.type.AbilityDodge; +import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; 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; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.ContainerPlayer; @@ -596,6 +601,7 @@ public class ScriptPlayerEventHandler { if (event.entityLiving.worldObj instanceof WorldServer) { boolean cancel = event.isCanceled(); Entity source = NoppesUtilServer.GetDamageSource(event.source); + if (event.entityLiving instanceof EntityPlayerMP) { PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); noppes.npcs.scripted.event.player.PlayerEvent.AttackedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.AttackedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source); @@ -623,6 +629,22 @@ public class ScriptPlayerEventHandler { noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent pevent1 = new noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.source.getEntity()), event.entityLiving, attackAmount, event.source); cancel = cancel || EventHooks.onPlayerAttack(handler, pevent1); } + + // Dodge & Counter: cancel attack entirely + if (!cancel && event.entityLiving instanceof EntityPlayerMP) { + PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving); + if (pData != null && pData.abilityData != null) { + AbilityDefend defend = pData.abilityData.getActiveDefend(); + if (defend instanceof AbilityDodge || defend instanceof AbilityCounter) { + EntityLivingBase attacker = source instanceof EntityLivingBase ? (EntityLivingBase) source : null; + float result = defend.onDefend(attacker, event.source, event.ammount); + if (result != event.ammount) { + cancel = true; + } + } + } + } + event.setCanceled(cancel); } } @@ -645,20 +667,28 @@ public class ScriptPlayerEventHandler { } if (event.entityLiving instanceof EntityPlayerMP) { - // Handle ability damage interactions (Guard counter, damage reduction) + // Handle ability damage interactions PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving); if (pData != null && pData.abilityData != null && pData.abilityData.isExecutingAbility()) { if (pData.abilityData.isCurrentAbilityInvulnerable()) { event.ammount = 0; cancel = true; } else { - event.ammount = pData.abilityData.onDamage(event.source, event.ammount); + // Guard: reduce damage + AbilityDefend defend = pData.abilityData.getActiveDefend(); + if (defend instanceof AbilityGuard) { + EntityLivingBase attacker = source instanceof EntityLivingBase ? (EntityLivingBase) source : null; + event.ammount = defend.onDefend(attacker, event.source, event.ammount); + } + + float modified = pData.abilityData.onDamage(event.source, event.ammount); + event.ammount = modified; } } PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source); - cancel = EventHooks.onPlayerDamaged(handler, pevent); + cancel = cancel || EventHooks.onPlayerDamaged(handler, pevent); event.ammount = pevent.damage; } diff --git a/src/main/java/noppes/npcs/ServerEventsHandler.java b/src/main/java/noppes/npcs/ServerEventsHandler.java index 9cbede79a..04e0406d8 100644 --- a/src/main/java/noppes/npcs/ServerEventsHandler.java +++ b/src/main/java/noppes/npcs/ServerEventsHandler.java @@ -5,8 +5,8 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.controllers.SyncController; import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker; -import kamkeel.npcs.entity.EntityAbilityBarrier; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; import kamkeel.npcs.network.enums.EnumSyncAction; @@ -159,7 +159,7 @@ public class ServerEventsHandler { if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote) return; - EntityAbilityBarrier barrier = EntityAbilityBarrier.getAbsorbingBarrier(event.entityLiving); + EntityEnergyBarrier barrier = EntityEnergyBarrier.getAbsorbingBarrier(event.entityLiving); if (barrier != null) { // Redirect the caster's damage to their barrier barrier.absorbDamage(event.ammount); @@ -191,9 +191,9 @@ public class ServerEventsHandler { } if (!blacklisted) return; - List barriers = EntityAbilityBarrier.getActiveBarriers(player.worldObj); - for (EntityAbilityBarrier barrier : barriers) { - if (barrier instanceof EntityAbilityDome && barrier.isEntityInside(player)) { + List barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj); + for (EntityEnergyBarrier barrier : barriers) { + if (barrier instanceof EntityEnergyDome && barrier.isEntityInside(player)) { event.setCanceled(true); return; } diff --git a/src/main/java/noppes/npcs/ai/CombatHandler.java b/src/main/java/noppes/npcs/ai/CombatHandler.java index 97d9a90eb..6947a986e 100644 --- a/src/main/java/noppes/npcs/ai/CombatHandler.java +++ b/src/main/java/noppes/npcs/ai/CombatHandler.java @@ -79,16 +79,6 @@ public class CombatHandler { aggressors.put(el, f + damageAmount); } - // Handle guard counter before interruption - -// if (npc.abilities.getCurrentAbility() instanceof AbilityGuard) { -// AbilityGuard guard = -// (AbilityGuard) npc.abilities.getCurrentAbility(); -// if (guard.isGuarding() && e instanceof EntityLivingBase) { -// guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount); -// } -// } - // Check for ability interruption npc.abilities.onDamage(source, damageAmount); } diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index 95b78fe82..6eab7f0db 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -7,14 +7,14 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ObfuscationReflectionHelper; import kamkeel.npcs.addon.client.DBCClient; import kamkeel.npcs.client.command.CommandCNPCDebugger; -import kamkeel.npcs.client.renderer.RenderAbilityBeam; -import kamkeel.npcs.client.renderer.RenderAbilityDisc; -import kamkeel.npcs.client.renderer.RenderAbilityLaser; -import kamkeel.npcs.client.renderer.RenderAbilityOrb; -import kamkeel.npcs.client.renderer.RenderAbilitySweeper; -import kamkeel.npcs.client.renderer.RenderAbilityZone; -import kamkeel.npcs.client.renderer.RenderAbilityDome; -import kamkeel.npcs.client.renderer.RenderAbilityPanel; +import kamkeel.npcs.client.renderer.RenderEnergyBeam; +import kamkeel.npcs.client.renderer.RenderEnergyDisc; +import kamkeel.npcs.client.renderer.RenderEnergyLaser; +import kamkeel.npcs.client.renderer.RenderEnergyOrb; +import kamkeel.npcs.client.renderer.RenderSweeper; +import kamkeel.npcs.client.renderer.RenderZone; +import kamkeel.npcs.client.renderer.RenderEnergyDome; +import kamkeel.npcs.client.renderer.RenderEnergyPanel; import kamkeel.npcs.client.renderer.EnergyChargePreviewRenderer; import kamkeel.npcs.client.renderer.RenderEnergyExplosion; import kamkeel.npcs.client.renderer.RenderEnergySlicer; @@ -26,10 +26,10 @@ import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergySweeper; import kamkeel.npcs.entity.EntityAbilityZone; -import kamkeel.npcs.entity.EntityAbilityDome; -import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityEnergyDome; +import kamkeel.npcs.entity.EntityEnergyPanel; import kamkeel.npcs.entity.EntityEnergyExplosion; import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.client.Minecraft; @@ -282,14 +282,14 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerEntityRenderingHandler(EntityNpcDragon.class, new RenderNpcDragon(new ModelNpcDragon(0.0F), 0.5F)); RenderingRegistry.registerEntityRenderingHandler(EntityNpcSlime.class, new RenderNpcSlime(new ModelNpcSlime(16), new ModelNpcSlime(0), 0.25F)); RenderingRegistry.registerEntityRenderingHandler(EntityProjectile.class, new RenderProjectile()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderAbilityOrb()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderAbilityDisc()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDome.class, new RenderAbilityDome()); - RenderingRegistry.registerEntityRenderingHandler(EntityAbilityPanel.class, new RenderAbilityPanel()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderEnergyOrb()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderEnergyDisc()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderEnergyLaser()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderEnergyBeam()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergySweeper.class, new RenderSweeper()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderZone()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome()); + RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel()); RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer()); RenderingRegistry.registerEntityRenderingHandler(EntityEnergyExplosion.class, new RenderEnergyExplosion()); diff --git a/src/main/java/noppes/npcs/client/ImageDownloadAlt.java b/src/main/java/noppes/npcs/client/ImageDownloadAlt.java index 7d986948f..f8d3b4857 100644 --- a/src/main/java/noppes/npcs/client/ImageDownloadAlt.java +++ b/src/main/java/noppes/npcs/client/ImageDownloadAlt.java @@ -8,6 +8,7 @@ import net.minecraft.client.renderer.texture.SimpleTexture; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; +import noppes.npcs.config.ConfigClient; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -101,18 +102,10 @@ public class ImageDownloadAlt extends SimpleTexture { HttpURLConnection connection = null; try { URL url = new URL(ImageDownloadAlt.this.imageUrl); - connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy()); - connection.setDoInput(true); - connection.setDoOutput(false); - connection.setRequestProperty("Content-Type", "image/png"); - connection.setRequestProperty("Expect", "100-continue"); - //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"); - connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - // Modify Accept Redirect - if (isImgurLink(url)) { - connection.setRequestProperty("Accept", "*/*"); - } + // Adding a config so people can switch back if needed. + // TODO: Remove config option if improved works better + connection = ConfigClient.ImprovedImageDownloadConnection ? setupConnectionImproved(url) : setupConnectionOld(url); connection.connect(); @@ -152,6 +145,44 @@ public class ImageDownloadAlt extends SimpleTexture { this.imageThread.start(); } + private HttpURLConnection setupConnectionOld(URL url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy()); + // setups stuff which basically tells the browser if this a get or post request + connection.setDoInput(true); + connection.setDoOutput(false); + + // ??? I believe these are used to tell the receiver what you are sending to them + // Not what you expect to receive from them. + connection.setRequestProperty("Content-Type", "image/png"); + connection.setRequestProperty("Expect", "100-continue"); + //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + + // Modify Accept Redirect + if (isImgurLink(url)) { + connection.setRequestProperty("Accept", "*/*"); + } + return connection; + } + + private HttpURLConnection setupConnectionImproved(URL url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy()); + + connection.setRequestMethod("GET"); + // Basically redundant because I set it as a GET request? + // Better safe than sorry ig. + connection.setDoInput(true); + connection.setDoOutput(false); + + // Random ass user agent I grabbed from my snooping on imgur + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0"); + // I tell the server what I want to receive. + // TODO: Should this just accept PNGs? + connection.setRequestProperty("Accept", "image/png,image/*"); + + return connection; + } + // Check if the URL is an Imgur link private static boolean isImgurLink(URL url) { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java index 0b21d028d..ce8aa221d 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiEffectGeneral.java @@ -8,6 +8,7 @@ import net.minecraft.util.ResourceLocation; import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.client.gui.global.GuiNPCManageEffects; import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.gui.util.GuiMenuTopButton; import noppes.npcs.client.gui.util.GuiNpcButtonYesNo; import noppes.npcs.client.gui.util.GuiNpcLabel; @@ -129,6 +130,12 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi int width = data.getTotalWidth(); int height = data.getTotalHeight(); + // Animation V offset for preview + if (data.isAnimated()) { + iconY += (int) (data.getCurrentFrameVOffset() * height); + } else if (effect.animated && effect.frameCount > 1) { + iconY += (int) (AnimationHelper.getFrameVOffset(height, effect.frameCount, effect.frametime) * height); + } func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height); @@ -183,6 +190,33 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi effect.height )); scrollWindow.addLabel(new GuiNpcLabel(9, "effect.editor.height", scrollWindow.getTextField(9).xPosition - 43, y + 6, 0xFFFFFF)); + y += 25; + + // Animation controls + scrollWindow.addLabel(new GuiNpcLabel(11, "gui.animated", x, y + 5, 0xFFFFFF)); + GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(11, x + 70, y, 50, 20, effect.animated); + animBtn.setHoverText("gui.animated.hover"); + scrollWindow.addButton(animBtn); + + if (effect.animated) { + y += 23; + scrollWindow.addLabel(new GuiNpcLabel(12, "gui.frameCount", x, y + 6, 0xFFFFFF)); + scrollWindow.addTextField(setIntegerOnly( + new GuiNpcTextField(12, this, x + 80, y, 60, 20, "" + effect.frameCount), + 1, + 256, + effect.frameCount + )); + + y += 23; + scrollWindow.addLabel(new GuiNpcLabel(13, "gui.frameTime", x, y + 6, 0xFFFFFF)); + scrollWindow.addTextField(setIntegerOnly( + new GuiNpcTextField(13, this, x + 80, y, 60, 20, "" + effect.frametime), + 1, + 100, + effect.frametime + )); + } } @@ -209,6 +243,11 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton; effect.lossOnDeath = button.getBoolean(); } + if (id == 11) { + GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton; + effect.animated = button.getBoolean(); + initGui(); + } } @Override @@ -248,6 +287,12 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi case 9: effect.height = guiNpcTextField.getInteger(); break; + case 12: + effect.frameCount = Math.max(1, guiNpcTextField.getInteger()); + break; + case 13: + effect.frametime = Math.max(1, guiNpcTextField.getInteger()); + break; } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index 23d18ad20..b1e58d94a 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -649,9 +649,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Search matches either the display name or the typeId (strip color codes for matching) String stripped = displayName.replaceAll("\u00A7.", ""); if (search.isEmpty() || stripped.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) { - // Yellow for concurrent-capable types, gray for other built-in types + // Lime green for concurrent-capable types, gray for other built-in types if (AbilityController.Instance.isConcurrentCapableType(typeId)) { - displayName = "\u00A7e" + displayName; + displayName = "\u00A7a" + displayName; } else if (AbilityController.Instance.isBuiltInType(typeId)) { displayName = "\u00A77" + displayName; } @@ -787,7 +787,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC NBTTagList actionList = new NBTTagList(); for (AbilityAction slot : npcSlots) { - actionList.appendTag(slot.writeNBT()); + actionList.appendTag(slot.writeNBT(false)); } compound.setTag("AbilityActions", actionList); @@ -1105,7 +1105,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC public void onAbilitySaved(Ability ability) { // Editing a global parent ability via "Modify Parent" on a chain entry if (editingChainEntryParent) { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); return; } @@ -1119,7 +1119,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC AbilityAction slot = npcSlots.get(selectedAbilityIndex); if (slot.isReference()) { // Modify Parent on standalone reference — save to global preset - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); } else { // Inline ability — update slot data npcSlots.set(selectedAbilityIndex, AbilityAction.inline(ability)); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index 544a7fefd..46447712b 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -3,6 +3,8 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; +import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.controllers.data.AbilityScript; import net.minecraft.client.gui.GuiButton; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; @@ -143,6 +145,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi GuiMenuTopButton closeBtn = new GuiMenuTopButton(-1000, guiLeft + xSize - 22, guiTop - 17, "X"); addTopButton(closeBtn); + GuiMenuTopButton scriptBtn = new GuiMenuTopButton(-999, "script.scripts", closeBtn); + addTopButton(scriptBtn); + // Build scroll window dimensions int swX = guiLeft + 4; int swY = guiTop + 5; @@ -152,9 +157,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi int y = 5; int labelCounter = LABEL_ID_START; - // General tab: type label + optional concurrent label at top — reserve space + // General tab: type label + optional info labels at top — reserve space if (activeTab == TAB_GENERAL) { y += ROW_H; + if ("ability.cnpc.custom".equals(ability.getTypeId())) { + y += 15; + } if (ability.isConcurrentCapable()) { y += 15; } @@ -168,14 +176,20 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); - // General tab: add type label + optional concurrent label at top of scroll window + // General tab: add type label + optional info labels at top of scroll window if (activeTab == TAB_GENERAL) { int baseId = builder.getNextLabelId(); + int infoY = 25; sw.addLabel(new GuiNpcLabel(baseId, "gui.type", 5, 10, 0xFFFFFF)); sw.addLabel(new GuiNpcLabel(baseId + 1, ability.getTypeId(), 55, 10, 0xFFFFFF)); - if (ability.isConcurrentCapable()) { + if ("ability.cnpc.custom".equals(ability.getTypeId())) { sw.addLabel(new GuiNpcLabel(baseId + 2, - StatCollector.translateToLocal("ability.concurrentInfo"), 5, 25, 0x55FF55)); + StatCollector.translateToLocal("ability.customScriptInfo"), 5, infoY, 0xFF55FF)); + infoY += 15; + } + if (ability.isConcurrentCapable()) { + sw.addLabel(new GuiNpcLabel(baseId + 3, + StatCollector.translateToLocal("ability.concurrentInfo"), 5, infoY, 0x55FF55)); } } @@ -302,6 +316,13 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi initGui(); return; } + if (id == -999) { + GuiNpcTextField.unfocus(); + applyToAbility(); + callback.onAbilitySaved(ability); + GuiScriptInterface.open(parent, new AbilityScript(ability.getId())); + return; + } if (id == -1000) { close(); return; @@ -405,7 +426,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi public void loadAbility(Ability loadedAbility) { if (loadedAbility == null) return; - NBTTagCompound nbt = loadedAbility.writeNBT(); + NBTTagCompound nbt = loadedAbility.writeNBT(false); nbt.setString("typeId", ability.getTypeId()); ability.readNBT(nbt); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java index a70b0318d..7f51b15e0 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java @@ -70,7 +70,7 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui private void doSave() { saved = true; - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); if (callback != null) { callback.onAbilitySaved(ability); } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java index b0c03a811..7d9c6cc32 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -83,8 +83,10 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS continue; String displayName = I18n.format(typeId); - if (AbilityController.Instance.isConcurrentCapableType(typeId)) { - displayName = "\u00A7e" + displayName; + if (typeId.equals("ability.cnpc.custom")) { + displayName = "\u00A7d" + displayName; + } else if (AbilityController.Instance.isConcurrentCapableType(typeId)) { + displayName = "\u00A7a" + displayName; } allDisplayNameToTypeId.put(displayName, typeId); } @@ -122,6 +124,21 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS } Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare( a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", ""))); + + // Pin Custom Ability to top of list + String customEntry = null; + for (String name : list) { + String tid = displayNameToTypeId.get(name); + if (tid != null && tid.equals("ability.cnpc.custom")) { + customEntry = name; + break; + } + } + if (customEntry != null) { + list.remove(customEntry); + list.add(0, customEntry); + } + return list; } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java index 400f38853..99af06e1c 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiChainedAbilityConfig.java @@ -5,6 +5,8 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityAction; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import noppes.npcs.client.gui.script.GuiScriptInterface; +import noppes.npcs.controllers.data.ChainedAbilityScript; import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry; import kamkeel.npcs.controllers.data.ability.data.AbilityIconData; import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider; @@ -57,6 +59,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText private static final int BTN_TAB_ENTRIES = 91; private static final int BTN_TAB_TARGET = 92; private static final int BTN_TAB_EXTRA_BASE = 93; + private static final int BTN_SCRIPT = -999; private static final int BTN_CLOSE = -1000; // ── Entries tab: per-entry ID encoding ───────────────────────────────────── @@ -160,14 +163,43 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText // ── Icon tab ────────────────────────────────────────────── AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain); - fieldDefs.add(FieldDef.stringField("gui.texture", chainIcon::getTexture, chainIcon::setTexture).tab("Icon")); - fieldDefs.add(FieldDef.section("ability.icon.section.uv").tab("Icon")); - fieldDefs.add(FieldDef.intField("ability.icon.x", chainIcon::getIconX, chainIcon::setIconX).tab("Icon").range(0, 4096)); - fieldDefs.add(FieldDef.intField("ability.icon.y", chainIcon::getIconY, chainIcon::setIconY).tab("Icon").range(0, 4096)); - fieldDefs.add(FieldDef.section("gui.size").tab("Icon")); - fieldDefs.add(FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).tab("Icon").range(1, 256)); - fieldDefs.add(FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).tab("Icon").range(1, 256)); + fieldDefs.add(FieldDef.row( + FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).range(1, 256), + FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).range(1, 256) + ).tab("Icon")); fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f)); + fieldDefs.add(FieldDef.intField("ability.icon.layers", chainIcon::getLayerCount, chainIcon::setLayerCount) + .tab("Icon").range(1, AbilityIconData.MAX_LAYERS)); + for (int i = 0; i < AbilityIconData.MAX_LAYERS; i++) { + final int idx = i; + java.util.function.BooleanSupplier layerVisible = () -> chainIcon.getLayerCount() > idx; + String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1); + fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.stringField("gui.texture", + () -> chainIcon.getLayer(idx).texture, + t -> chainIcon.setLayerTexture(idx, t)) + .tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.row( + FieldDef.intField("ability.icon.x", + () -> chainIcon.getLayer(idx).iconX, + x -> chainIcon.setLayerIconX(idx, x)).range(0, 4096), + FieldDef.intField("ability.icon.y", + () -> chainIcon.getLayer(idx).iconY, + y -> chainIcon.setLayerIconY(idx, y)).range(0, 4096) + ).tab("Icon").visibleWhen(layerVisible)); + fieldDefs.add(FieldDef.colorSubGui("ability.icon.tint", + () -> chainIcon.getLayer(idx).tintColor, + c -> chainIcon.setLayerTintColor(idx, c)) + .tab("Icon").visibleWhen(layerVisible)); + } + + // Animation + fieldDefs.add(FieldDef.section("Animation").tab("Icon")); + fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover")); + fieldDefs.add(FieldDef.intField("gui.frameCount", chainIcon::getFrameCount, chainIcon::setFrameCount) + .tab("Icon").range(1, 256).visibleWhen(chainIcon::isAnimated)); + fieldDefs.add(FieldDef.intField("gui.frameTime", chainIcon::getFrameTime, chainIcon::setFrameTime) + .tab("Icon").range(1, 100).visibleWhen(chainIcon::isAnimated)); // External field providers (e.g., DBC Addon injecting a "DBC" tab) if (AbilityController.Instance != null) { @@ -258,6 +290,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText GuiMenuTopButton closeBtn = new GuiMenuTopButton(BTN_CLOSE, guiLeft + xSize - 22, guiTop - 17, "X"); addTopButton(closeBtn); + GuiMenuTopButton scriptBtn = new GuiMenuTopButton(BTN_SCRIPT, "script.scripts", closeBtn); + addTopButton(scriptBtn); + // Scroll window dimensions int swX = guiLeft + 4; int swY = guiTop + 5; @@ -487,6 +522,10 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText initGui(); return; } + if (id == BTN_SCRIPT) { + GuiScriptInterface.open(parent, new ChainedAbilityScript(chain.getId())); + return; + } if (id == BTN_CLOSE) { saveOnClose = true; close(); @@ -853,7 +892,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText public void onAbilitySaved(Ability ability) { if (editingParentAbility) { // Persist the global parent ability to the server - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false))); editingParentAbility = false; return; } diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java index 757c37470..fe3267112 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -187,19 +187,27 @@ public class FieldDef { idSetter.accept(-1); } else { idSetter.accept(sel.selectedAnimationId); - nameSetter.accept(""); + String customName = sel.getSelectedName(); + nameSetter.accept(customName != null ? customName : ""); } }) .buttonLabel(() -> { String name = nameGetter.get(); - if (name != null && !name.isEmpty()) return name; int id = idGetter.get(); + if (id < 0 && name != null && !name.isEmpty()) { + // Built-in animation: show just the name + return name; + } if (id >= 0) { + // Custom animation: show (X) Name + if (name != null && !name.isEmpty()) { + return "(" + id + ") " + name; + } Animation anim = AnimationController.Instance != null ? (Animation) AnimationController.Instance.get(id) : null; String animName = anim != null ? anim.getName() : ""; return animName != null && !animName.isEmpty() - ? "(ID: " + id + ") " + animName : "ID: " + id; + ? "(" + id + ") " + animName : String.valueOf(id); } return "gui.none"; }) diff --git a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java index 6e6a48ab1..262754df1 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -347,9 +347,14 @@ public class GuiFieldBuilder { String translated = StatCollector.translateToLocal(def.getLabel()); int labelW = fontRenderer.getStringWidth(translated); int fieldX = colLLabel + labelW + labelPadding; - // Clamp field width so it doesn't extend under the scrollbar + // Available width before the scrollbar int maxW = contentRight - fieldX - 15; - if (maxW > 0 && fieldW > maxW) fieldW = maxW; + if (def.getType() == FieldType.SUB_GUI && maxW > 0) { + // SUB_GUI fields fill all available width up to the scrollbar + fieldW = maxW; + } else if (maxW > 0 && fieldW > maxW) { + fieldW = maxW; + } renderFieldAt(def, colLLabel, fieldX, fieldW, y); } diff --git a/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java b/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java index 58303db63..021323329 100644 --- a/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java +++ b/src/main/java/noppes/npcs/client/gui/custom/components/CustomGuiTexturedRect.java @@ -7,6 +7,7 @@ import noppes.npcs.api.gui.ICustomGuiComponent; import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.client.gui.custom.GuiCustom; import noppes.npcs.client.gui.custom.interfaces.IGuiComponent; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.scripted.gui.ScriptGuiTexturedRect; import org.lwjgl.opengl.GL11; @@ -30,6 +31,11 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { float alpha; float rotation; + // Animation + boolean animated; + int frameCount = 1; + int frametime = 2; + public CustomGuiTexturedRect(int id, String texture, int x, int y, int width, int height) { this(id, texture, x, y, width, height, 0, 0); } @@ -64,10 +70,18 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { int totalWidth = this.imageData.getTotalWidth(); int totalHeight = this.imageData.getTotalHeight(); + // Animation V offset + float vOff = 0f; + if (this.imageData.isAnimated()) { + vOff = this.imageData.getCurrentFrameVOffset(); + } else if (this.animated && this.frameCount > 1) { + vOff = AnimationHelper.getFrameVOffset(totalHeight, this.frameCount, this.frametime); + } + float u1 = (float) textureX / (float) totalWidth; float u2 = u1 + (float) width / (float) totalWidth; - float v1 = (float) textureY / (float) totalHeight; - float v2 = v1 + (float) height / (float) totalHeight; + float v1 = vOff + (float) textureY / (float) totalHeight; + float v2 = vOff + ((float) textureY + (float) height) / (float) totalHeight; GL11.glPushMatrix(); float red = (color >> 16 & 255) / 255f; @@ -104,6 +118,9 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { component.setColor(color); component.setAlpha(alpha); component.setRotation(rotation); + if (this.animated && this.frameCount > 1) { + component.setAnimation(this.frameCount, this.frametime); + } return component; } @@ -124,6 +141,12 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent { rect.alpha = component.getAlpha(); rect.rotation = component.getRotation(); + if (component.isAnimated()) { + rect.animated = true; + rect.frameCount = component.getFrameCount(); + rect.frametime = component.getFrameTime(); + } + return rect; } } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java index 64be9e499..cac2cccd5 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -5,6 +5,8 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; import kamkeel.npcs.network.PacketClient; + +import java.util.UUID; import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.ChainedAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.ChainedAbilityGetPacket; @@ -495,7 +497,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private void handleChainConfigClosed() { if (pendingSaveChain != null) { - PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT())); + PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT(false))); selected = pendingSaveChain.getName(); pendingSaveChain = null; } @@ -510,6 +512,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface Ability newAbility = AbilityController.Instance.create(pendingTypeId); if (newAbility != null) { gui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); pendingTypeId = null; openConfig(newAbility); return true; @@ -536,6 +539,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface if (variants.size() == 1) { variants.get(0).apply(newAbility); } + newAbility.setId(UUID.randomUUID().toString()); openConfig(newAbility); return true; } @@ -550,7 +554,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface if (pendingSaveAbility == null) return false; if (gui.isConfirmed()) { - PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false))); pendingSaveAbility = null; return false; } @@ -574,7 +578,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface setSubGui(new SubGuiDuplicateNameConfirm()); return true; } - PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false))); pendingSaveAbility = null; return false; } diff --git a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java index 09fc2e2da..2ed5f1512 100644 --- a/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java +++ b/src/main/java/noppes/npcs/client/gui/hud/ability/AbilityIcon.java @@ -13,6 +13,7 @@ import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import org.lwjgl.opengl.GL11; @@ -25,6 +26,11 @@ public class AbilityIcon extends Gui { public int width; public int height; + // Default icon layers (extracted from ability) + private Ability.DefaultIconLayer[] defaultLayers = null; + private int defaultIconWidth = 48; + private int defaultIconHeight = 48; + private AbilityIcon(AbilityIconData data) { this.data = data; this.width = data.width; @@ -33,7 +39,11 @@ public class AbilityIcon extends Gui { public static AbilityIcon fromAbility(Ability ability) { if (ability != null) { - return new AbilityIcon(AbilityIconData.fromAbility(ability)); + AbilityIcon icon = new AbilityIcon(AbilityIconData.fromAbility(ability)); + icon.defaultLayers = ability.getDefaultIconLayers(); + icon.defaultIconWidth = ability.getDefaultIconWidth(); + icon.defaultIconHeight = ability.getDefaultIconHeight(); + return icon; } return fromDefaults(); } @@ -66,44 +76,88 @@ public class AbilityIcon extends Gui { public void draw(int state, float alpha) { TextureManager renderEngine = Minecraft.getMinecraft().renderEngine; - ImageData imageData = null; - if (data.hasTexture()) { - imageData = ClientCacheHandler.getImageData(data.texture); - } - GL11.glPushMatrix(); - GL11.glColor4f(1, 1, 1, alpha); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Tessellator t; - - if (imageData == null || !imageData.imageLoaded()) { - GL11.glScalef(1.0f, 1.0f, 1); - renderEngine.bindTexture(FALLBACK_TEXTURE); - t = getFallbackTessellator(); - } else { + if (data.isEnabled()) { + // Path 1: Custom icon — draw each active layer bottom-to-top GL11.glScalef(data.scale, data.scale, 1); - renderEngine.bindTexture(imageData.getLocation()); - t = getTessellator(imageData, state); + boolean drewAny = false; + for (int i = 0; i < data.getLayerCount(); i++) { + AbilityIconData.Layer layer = data.getLayer(i); + if (!layer.hasTexture()) continue; + ImageData imageData = ClientCacheHandler.getImageData(layer.texture); + if (imageData != null && imageData.imageLoaded()) { + int tint = layer.tintColor; + float r = ((tint >> 16) & 0xFF) / 255f; + float g = ((tint >> 8) & 0xFF) / 255f; + float b = (tint & 0xFF) / 255f; + GL11.glColor4f(r, g, b, alpha); + renderEngine.bindTexture(imageData.getLocation()); + Tessellator t = getLayerTessellator(imageData, layer, i == 0 ? state : 0); + t.draw(); + drewAny = true; + } + } + if (!drewAny) { + GL11.glColor4f(1, 1, 1, alpha); + renderEngine.bindTexture(FALLBACK_TEXTURE); + getFallbackTessellator().draw(); + } + } else if (hasDefaultLayers()) { + // Path 2: Default layers — draw each layer with its dynamic color + for (Ability.DefaultIconLayer defLayer : defaultLayers) { + String texPath = defLayer.getTextureForState(state); + if (texPath == null || texPath.isEmpty()) continue; + ImageData imageData = ClientCacheHandler.getImageData(texPath); + if (imageData != null && imageData.imageLoaded()) { + int color = defLayer.getColor(); + float r = ((color >> 16) & 0xFF) / 255f; + float g = ((color >> 8) & 0xFF) / 255f; + float b = (color & 0xFF) / 255f; + GL11.glColor4f(r, g, b, alpha); + renderEngine.bindTexture(imageData.getLocation()); + getDefaultIconTessellator().draw(); + } + } + } else { + // Path 3: No custom icon, no default layers — generic fallback + GL11.glColor4f(1, 1, 1, alpha); + renderEngine.bindTexture(FALLBACK_TEXTURE); + getFallbackTessellator().draw(); } - t.draw(); GL11.glPopMatrix(); } - private Tessellator getTessellator(ImageData imageData, int state) { + private boolean hasDefaultLayers() { + return defaultLayers != null && defaultLayers.length > 0; + } + + private Tessellator getLayerTessellator(ImageData imageData, AbilityIconData.Layer layer, int state) { float hw = data.width / 2f; float hh = data.height / 2f; float texW = imageData.getTotalWidth(); float texH = imageData.getTotalHeight(); - int ix = data.getIconXForState(state); - int iy = data.getIconYForState(state); + // State UV overrides only apply to layer 0 + int ix = (state > 0) ? data.getIconXForState(state) : layer.iconX; + int iy = (state > 0) ? data.getIconYForState(state) : layer.iconY; + + // Animation V offset + float vOff = 0f; + if (imageData.isAnimated()) { + vOff = imageData.getCurrentFrameVOffset(); + } else if (data.isAnimated()) { + vOff = AnimationHelper.getFrameVOffset((int) texH, data.getFrameCount(), data.getFrameTime()); + } float u1 = ix / texW; - float v1 = iy / texH; + float v1 = vOff + iy / texH; float u2 = (ix + data.width) / texW; - float v2 = (iy + data.height) / texH; + float v2 = vOff + (iy + data.height) / texH; Tessellator t = Tessellator.instance; t.startDrawingQuads(); @@ -114,6 +168,19 @@ public class AbilityIcon extends Gui { return t; } + private Tessellator getDefaultIconTessellator() { + float hw = defaultIconWidth / 2f; + float hh = defaultIconHeight / 2f; + + Tessellator t = Tessellator.instance; + t.startDrawingQuads(); + t.addVertexWithUV(-hw, hh, zLevel, 0, 1); + t.addVertexWithUV(hw, hh, zLevel, 1, 1); + t.addVertexWithUV(hw, -hh, zLevel, 1, 0); + t.addVertexWithUV(-hw, -hh, zLevel, 0, 0); + return t; + } + private Tessellator getFallbackTessellator() { float hw = 16f; float hh = 16f; @@ -128,17 +195,20 @@ public class AbilityIcon extends Gui { } public boolean hasTexture() { - return data.hasTexture(); + return data.isEnabled() || hasDefaultLayers(); } /** * Returns the approximate visual size (max dimension) that draw() produces. - * Textured: max(width,height) * scale. Fallback: 32. + * Custom icon: max(width,height) * scale. Default icon: max(defaultW,defaultH). Fallback: 32. */ public float getDrawSize() { - if (data.hasTexture()) { + if (data.isEnabled()) { return Math.max(width, height) * data.scale; } + if (hasDefaultLayers()) { + return Math.max(defaultIconWidth, defaultIconHeight); + } return 32f; } } diff --git a/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java b/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java index b71f6642a..077c9fd9f 100644 --- a/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java +++ b/src/main/java/noppes/npcs/client/gui/item/SubGuiLinkedItem.java @@ -10,6 +10,7 @@ import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.util.ResourceLocation; import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.client.CustomNpcResourceListener; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.gui.SubGuiColorSelector; import noppes.npcs.client.gui.global.GuiNPCManageLinked; import noppes.npcs.client.gui.script.GuiScriptInterface; @@ -286,6 +287,31 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe scrollWindow.addLabel(new GuiNpcLabel(70, "display.durabilityShow", x, localY + 5, 0xFFFFFF)); GuiNpcButtonYesNo durabilityButton = new GuiNpcButtonYesNo(26, x + 120, localY, linkedItem.display.durabilityShow); scrollWindow.addButton(durabilityButton); + localY += 30; + + // Animation controls + scrollWindow.addLabel(new GuiNpcLabel(80, "gui.animated", x, localY + 5, 0xFFFFFF)); + boolean isAnim = linkedItem.display.animated != null && linkedItem.display.animated; + GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(29, x + 120, localY, isAnim); + animBtn.setHoverText("gui.animated.hover"); + scrollWindow.addButton(animBtn); + localY += 25; + + if (isAnim) { + scrollWindow.addLabel(new GuiNpcLabel(81, "gui.frameCount", x, localY + 5, 0xFFFFFF)); + GuiNpcTextField fcField = new GuiNpcTextField(71, this, x + 120, localY, 60, 20, + "" + (linkedItem.display.frameCount != null ? linkedItem.display.frameCount : 1)); + fcField.setIntegersOnly().setMinMaxDefault(1, 256, 1); + scrollWindow.addTextField(fcField); + localY += 25; + + scrollWindow.addLabel(new GuiNpcLabel(82, "gui.frameTime", x, localY + 5, 0xFFFFFF)); + GuiNpcTextField ftField = new GuiNpcTextField(72, this, x + 120, localY, 60, 20, + "" + (linkedItem.display.frametime != null ? linkedItem.display.frametime : 2)); + ftField.setIntegersOnly().setMinMaxDefault(1, 100, 2); + scrollWindow.addTextField(ftField); + localY += 25; + } scrollWindow.scrollY = 0; scrollWindow.maxScrollY = Math.max(localY - scrollWindow.clipHeight, 0); @@ -381,6 +407,9 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe linkedItem.isNormalItem = ((GuiNpcButtonYesNo) guibutton).getBoolean(); } else if (id == 26 && guibutton instanceof GuiNpcButtonYesNo) { linkedItem.display.durabilityShow = ((GuiNpcButtonYesNo) guibutton).getBoolean(); + } else if (id == 29 && guibutton instanceof GuiNpcButtonYesNo) { + linkedItem.display.animated = ((GuiNpcButtonYesNo) guibutton).getBoolean(); + initGui(); } } @@ -429,6 +458,10 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe linkedItem.display.translateY = textField.getFloat(); } else if (id == 63) { linkedItem.display.translateZ = textField.getFloat(); + } else if (id == 71) { + linkedItem.display.frameCount = Math.max(1, textField.getInteger()); + } else if (id == 72) { + linkedItem.display.frametime = Math.max(1, textField.getInteger()); } } @@ -472,7 +505,20 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe int iconWidth = data.getTotalWidth(); int iconHeight = data.getTotalWidth(); int width = data.getTotalWidth(); - int height = data.getTotalWidth(); + int height = data.getTotalHeight(); + + // Animation V offset for preview + if (data.isAnimated()) { + iconY += (int) (data.getCurrentFrameVOffset() * height); + iconHeight = data.getFrameHeight(); + } else if (linkedItem.display.animated != null && linkedItem.display.animated + && linkedItem.display.frameCount != null && linkedItem.display.frameCount > 1) { + iconY += (int) (AnimationHelper.getFrameVOffset(height, linkedItem.display.frameCount, linkedItem.display.frametime) * height); + iconHeight = height / linkedItem.display.frameCount; + } else { + iconHeight = data.getTotalWidth(); + height = data.getTotalWidth(); + } float[] colors = ColorUtil.hexToRGB(linkedItem.display.itemColor); GL11.glColor3f(colors[0], colors[1], colors[2]); diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java index aae3043ce..aba735970 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java @@ -145,11 +145,12 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL scrollSounds.resetScroll(); getTextField(66).setText(""); soundSearch = ""; + initGui(); } if (guiCustomScroll.id == 1) { selectedResource = new ResourceLocation(selectedDomain, guiCustomScroll.getSelected()); + getButton(1).enabled = true; } - initGui(); } @Override diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java index 29cf26134..b27f36519 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiEffectBar.java @@ -6,6 +6,7 @@ import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.texture.TextureManager; import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.controllers.data.CustomEffect; import noppes.npcs.controllers.data.PlayerEffect; @@ -82,6 +83,13 @@ public class GuiEffectBar extends GuiScreen { int texWidth = imageData.getTotalWidth(); int texHeight = imageData.getTotalHeight(); + // Animation V offset + if (imageData.isAnimated()) { + iconV += (int) (imageData.getCurrentFrameVOffset() * texHeight); + } else if (entry.effect.animated && entry.effect.frameCount > 1) { + iconV += (int) (AnimationHelper.getFrameVOffset(texHeight, entry.effect.frameCount, entry.effect.frametime) * texHeight); + } + // Use iconYOffset to vertically center the icon func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight); @@ -191,7 +199,14 @@ public class GuiEffectBar extends GuiScreen { if (imageData != null && imageData.imageLoaded()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); imageData.bindTexture(); - func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalHeight()); + int tooltipIconV = hoveredEffect.iconY; + int tooltipTexH = imageData.getTotalHeight(); + if (imageData.isAnimated()) { + tooltipIconV += (int) (imageData.getCurrentFrameVOffset() * tooltipTexH); + } else if (hoveredEffect.animated && hoveredEffect.frameCount > 1) { + tooltipIconV += (int) (AnimationHelper.getFrameVOffset(tooltipTexH, hoveredEffect.frameCount, hoveredEffect.frametime) * tooltipTexH); + } + func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, tooltipIconV, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), tooltipTexH); } textureManager.bindTexture(specialIcons); diff --git a/src/main/java/noppes/npcs/client/renderer/AnimationHelper.java b/src/main/java/noppes/npcs/client/renderer/AnimationHelper.java new file mode 100644 index 000000000..c847d6e14 --- /dev/null +++ b/src/main/java/noppes/npcs/client/renderer/AnimationHelper.java @@ -0,0 +1,49 @@ +package noppes.npcs.client.renderer; + +import net.minecraft.client.Minecraft; + +/** + * Static utility for computing animated texture UV offsets. + * Used by renderers when animation parameters come from data class fields + * rather than .mcmeta auto-detection on ImageData. + */ +public class AnimationHelper { + + /** + * Returns the V-coordinate offset (0.0-1.0) for the current animation frame. + * Based on system time for consistent sync across all animated textures. + * + * @param totalHeight Total pixel height of the sprite strip + * @param frameCount Number of frames in the strip + * @param frametime Ticks per frame (1 tick = 50ms) + * @return V offset in 0.0-1.0 range, or 0.0 if not animated + */ + public static float getFrameVOffset(int totalHeight, int frameCount, int frametime) { + if (frameCount <= 1 || totalHeight <= 0) { + return 0f; + } + + frametime = Math.max(1, frametime); + long millis = Minecraft.getSystemTime(); + int tick = (int) (millis / 50L); + int frameIdx = (tick / frametime) % frameCount; + int frameHeight = totalHeight / frameCount; + + return (float) (frameIdx * frameHeight) / (float) totalHeight; + } + + /** + * Returns the V-coordinate size of a single frame in 0.0-1.0 range. + * + * @param totalHeight Total pixel height of the sprite strip + * @param frameCount Number of frames in the strip + * @return V size of one frame, or 1.0 if not animated + */ + public static float getFrameVSize(int totalHeight, int frameCount) { + if (frameCount <= 1 || totalHeight <= 0) { + return 1f; + } + int frameHeight = totalHeight / frameCount; + return (float) frameHeight / (float) totalHeight; + } +} diff --git a/src/main/java/noppes/npcs/client/renderer/ImageData.java b/src/main/java/noppes/npcs/client/renderer/ImageData.java index 8e6f651c5..b85e51502 100644 --- a/src/main/java/noppes/npcs/client/renderer/ImageData.java +++ b/src/main/java/noppes/npcs/client/renderer/ImageData.java @@ -1,5 +1,8 @@ package noppes.npcs.client.renderer; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.IResource; @@ -11,6 +14,7 @@ import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; public class ImageData { private final ResourceLocation location; @@ -23,6 +27,14 @@ public class ImageData { private boolean gotWidthHeight; private boolean invalid; + // Animation fields + private boolean animated = false; + private int frameCount = 1; + private int frametime = 2; + private int[] frames = null; + private boolean interpolate = false; + private boolean mcmetaChecked = false; + public ImageData(String directory) { this.location = new ResourceLocation(directory); if (directory.startsWith("https://") || directory.startsWith("http://")) { @@ -141,6 +153,11 @@ public class ImageData { private void correctWidthHeight() { this.totalWidth = Math.max(this.totalWidth, 1); this.totalHeight = Math.max(this.totalHeight, 1); + + if (!this.isUrl && !this.mcmetaChecked) { + this.mcmetaChecked = true; + tryLoadMcmeta(); + } } public int getTotalWidth() { @@ -150,4 +167,112 @@ public class ImageData { public int getTotalHeight() { return this.gotWidthHeight ? this.totalHeight : -1; } + + // ═══════════════════════════════════════════════════════════════════ + // ANIMATION + // ═══════════════════════════════════════════════════════════════════ + + private void tryLoadMcmeta() { + try { + ResourceLocation mcmetaLoc = new ResourceLocation( + location.getResourceDomain(), + location.getResourcePath() + ".mcmeta" + ); + IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(mcmetaLoc); + InputStream stream = resource.getInputStream(); + try { + InputStreamReader reader = new InputStreamReader(stream); + JsonObject root = new JsonParser().parse(reader).getAsJsonObject(); + if (root.has("animation")) { + JsonObject anim = root.getAsJsonObject("animation"); + this.animated = true; + + if (anim.has("frametime")) { + this.frametime = Math.max(1, anim.get("frametime").getAsInt()); + } + if (anim.has("interpolate")) { + this.interpolate = anim.get("interpolate").getAsBoolean(); + } + if (anim.has("frames")) { + JsonArray framesArray = anim.getAsJsonArray("frames"); + this.frames = new int[framesArray.size()]; + int maxFrame = 0; + for (int i = 0; i < framesArray.size(); i++) { + this.frames[i] = framesArray.get(i).getAsInt(); + if (this.frames[i] > maxFrame) { + maxFrame = this.frames[i]; + } + } + this.frameCount = maxFrame + 1; + } else if (this.totalWidth > 0) { + this.frameCount = Math.max(1, this.totalHeight / this.totalWidth); + } + } + } finally { + stream.close(); + } + } catch (Exception ignored) { + // No .mcmeta found or parse error — not animated + } + } + + /** + * Programmatically enable animation on this ImageData. + * Used when animation settings come from data class fields rather than .mcmeta files. + */ + public void setAnimation(int frameCount, int frametime) { + if (frameCount > 1) { + this.animated = true; + this.frameCount = Math.max(1, frameCount); + this.frametime = Math.max(1, frametime); + } + } + + public boolean isAnimated() { + return this.animated && this.frameCount > 1; + } + + public int getFrameCount() { + return this.frameCount; + } + + public int getFrameTime() { + return this.frametime; + } + + /** + * Returns the pixel height of a single animation frame. + * For non-animated textures, returns the total height. + */ + public int getFrameHeight() { + if (this.animated && this.frameCount > 1) { + return Math.max(1, this.totalHeight / this.frameCount); + } + return this.gotWidthHeight ? this.totalHeight : -1; + } + + /** + * Returns the V-coordinate offset (0.0-1.0) for the current animation frame. + * Based on system time so all instances of the same texture animate in sync. + * Returns 0.0 for non-animated textures. + */ + public float getCurrentFrameVOffset() { + if (!this.animated || this.frameCount <= 1 || this.totalHeight <= 0) { + return 0f; + } + + long millis = Minecraft.getSystemTime(); + int tick = (int) (millis / 50L); + int frameIdx; + + if (this.frames != null && this.frames.length > 0) { + frameIdx = (tick / this.frametime) % this.frames.length; + frameIdx = this.frames[frameIdx]; + } else { + frameIdx = (tick / this.frametime) % this.frameCount; + } + + int frameHeight = this.totalHeight / this.frameCount; + return (float) (frameIdx * frameHeight) / (float) this.totalHeight; + } } diff --git a/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java b/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java index 8b8c1f452..83b83b9b6 100644 --- a/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java +++ b/src/main/java/noppes/npcs/client/renderer/items/ItemCustomRenderer.java @@ -17,6 +17,7 @@ import net.minecraftforge.client.IItemRenderer; import noppes.npcs.api.item.IItemCustomizable; import noppes.npcs.api.item.IItemStack; import noppes.npcs.client.ClientCacheHandler; +import noppes.npcs.client.renderer.AnimationHelper; import noppes.npcs.client.renderer.ImageData; import noppes.npcs.items.ItemCustomizable; import noppes.npcs.scripted.NpcAPI; @@ -222,7 +223,8 @@ public class ItemCustomRenderer implements IItemRenderer { int pass = 0; GL11.glPushMatrix(); - ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture(); + ImageData entityImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + entityImageData.bindTexture(); if (renderInFrame) { GL11.glTranslatef(0.0F, -0.05F, 0.0F); @@ -233,10 +235,22 @@ public class ItemCustomRenderer implements IItemRenderer { Tessellator tessellator = Tessellator.instance; + // Animation V offset for entity rendering + float entityVOff = 0f; + float entityVEnd = 1f; + if (entityImageData.isAnimated()) { + entityVOff = entityImageData.getCurrentFrameVOffset(); + entityVEnd = entityVOff + (float) entityImageData.getFrameHeight() / entityImageData.getTotalHeight(); + } else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() + && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) { + entityVOff = AnimationHelper.getFrameVOffset(entityImageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime()); + entityVEnd = entityVOff + AnimationHelper.getFrameVSize(entityImageData.getTotalHeight(), scriptCustomItem.getFrameCount()); + } + float f14 = 0.0F; float f15 = 1.0F; - float f4 = 0.0F; - float f5 = 1.0F; + float f4 = entityVOff; + float f5 = entityVEnd; float f6 = 1.0F; float f7 = 0.5F; float f8 = 0.25F; @@ -272,8 +286,11 @@ public class ItemCustomRenderer implements IItemRenderer { GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); }*/ - ImageData imageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); - ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, imageData.getTotalWidth(), imageData.getTotalHeight(), f9); + ImageData loopImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + int entityFrameH = loopImageData.isAnimated() ? loopImageData.getFrameHeight() + : (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1 + ? loopImageData.getTotalHeight() / scriptCustomItem.getFrameCount() : loopImageData.getTotalHeight()); + ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, loopImageData.getTotalWidth(), entityFrameH, f9); if (itemStack.hasEffect(pass)) { GL11.glDepthFunc(GL11.GL_EQUAL); @@ -359,8 +376,20 @@ public class ItemCustomRenderer implements IItemRenderer { GL11.glDisable(GL11.GL_LIGHTING); //Forge: Make sure that render states are reset, a renderEffect can derp them up. GL11.glEnable(GL11.GL_ALPHA_TEST); - ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture(); - renderCustomItemSlot(0, 0, 16, 16, itemRed, itemGreen, itemBlue); + ImageData imageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + imageData.bindTexture(); + + float vOff = 0f; + float vEnd = 1f; + if (imageData.isAnimated()) { + vOff = imageData.getCurrentFrameVOffset(); + vEnd = vOff + (float) imageData.getFrameHeight() / imageData.getTotalHeight(); + } else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() + && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) { + vOff = AnimationHelper.getFrameVOffset(imageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime()); + vEnd = vOff + AnimationHelper.getFrameVSize(imageData.getTotalHeight(), scriptCustomItem.getFrameCount()); + } + renderCustomItemSlot(0, 0, 16, 16, itemRed, itemGreen, itemBlue, vOff, vEnd); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); @@ -412,13 +441,17 @@ public class ItemCustomRenderer implements IItemRenderer { } public void renderCustomItemSlot(int posX, int posY, int imageWidth, int imageHeight, float itemRed, float itemGreen, float itemBlue) { + renderCustomItemSlot(posX, posY, imageWidth, imageHeight, itemRed, itemGreen, itemBlue, 0f, 1f); + } + + public void renderCustomItemSlot(int posX, int posY, int imageWidth, int imageHeight, float itemRed, float itemGreen, float itemBlue, float vOff, float vEnd) { Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.setColorRGBA_F(itemRed, itemGreen, itemBlue, 1.0F); - tessellator.addVertexWithUV((double) (posX), (double) (posY + imageHeight), 0, 0, 1); - tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY + imageHeight), 0, 1, 1); - tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY), 0, 1, 0); - tessellator.addVertexWithUV((double) (posX), (double) (posY), 0, 0, 0); + tessellator.addVertexWithUV((double) (posX), (double) (posY + imageHeight), 0, 0, vEnd); + tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY + imageHeight), 0, 1, vEnd); + tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY), 0, 1, vOff); + tessellator.addVertexWithUV((double) (posX), (double) (posY), 0, 0, vOff); tessellator.draw(); } @@ -429,7 +462,8 @@ public class ItemCustomRenderer implements IItemRenderer { TextureManager texturemanager = mc.getTextureManager(); int par3 = 0; - ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture(); + ImageData item3dImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture()); + item3dImageData.bindTexture(); Tessellator tessellator = Tessellator.instance; IIcon icon = entityLivingBase.getItemIcon(itemStack, par3); @@ -447,7 +481,19 @@ public class ItemCustomRenderer implements IItemRenderer { GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F); - renderCustomItemIn2D(scriptCustomItem, tessellator, 1.0F, 0.0F, 0.0F, 1.0F, 0.0625F); + // Animation V offset for 3D handheld rendering + float item3dVOff = 0f; + float item3dVEnd = 1f; + if (item3dImageData.isAnimated()) { + item3dVOff = item3dImageData.getCurrentFrameVOffset(); + item3dVEnd = item3dVOff + (float) item3dImageData.getFrameHeight() / item3dImageData.getTotalHeight(); + } else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() + && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) { + item3dVOff = AnimationHelper.getFrameVOffset(item3dImageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime()); + item3dVEnd = item3dVOff + AnimationHelper.getFrameVSize(item3dImageData.getTotalHeight(), scriptCustomItem.getFrameCount()); + } + + renderCustomItemIn2D(scriptCustomItem, tessellator, 1.0F, item3dVOff, 0.0F, item3dVEnd, 0.0625F); if (itemStack.hasEffect(par3)) { GL11.glDepthFunc(GL11.GL_EQUAL); @@ -485,7 +531,10 @@ public class ItemCustomRenderer implements IItemRenderer { public static void renderCustomItemIn2D(IItemCustomizable wrapper, Tessellator p_78439_0_, float p_78439_1_, float p_78439_2_, float p_78439_3_, float p_78439_4_, float p_78439_7_) { ImageData imageData = ClientCacheHandler.getImageData(wrapper.getTexture()); int width = imageData.getTotalWidth(); - int height = imageData.getTotalHeight(); + // Use frame height for edge pixel calculations so animated strips render correctly + int height = imageData.isAnimated() ? imageData.getFrameHeight() + : (wrapper.isTextureAnimated() != null && wrapper.isTextureAnimated() && wrapper.getFrameCount() != null && wrapper.getFrameCount() > 1 + ? imageData.getTotalHeight() / wrapper.getFrameCount() : imageData.getTotalHeight()); p_78439_0_.startDrawingQuads(); p_78439_0_.setNormal(0.0F, 0.0F, 1.0F); diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index 79a647026..ef0650db0 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -157,6 +157,7 @@ public class ConfigClient { public static boolean LegacyTallLamp = false; public static boolean LegacyPedestal = false; public static boolean LegacyMailbox = false; + public static boolean ImprovedImageDownloadConnection = true; public static void init(File configFile) { config = new Configuration(configFile); @@ -303,6 +304,7 @@ public class ConfigClient { BannerAlerts = BannerAlertsProperty.getBoolean(true); WoodTextures = config.get(TEXTURE, "Wood Textures", false, "Models like Chairs and Stools will use default MC Wood Textures").getBoolean(false); + ImprovedImageDownloadConnection = config.get(TEXTURE, "DEBUG: Better handling of image downloads: ", true).getBoolean(true); LegacyCampfire = config.get(MODEL, "Legacy Campfire Model", false).getBoolean(false); LegacyBanner = config.get(MODEL, "Legacy Banner Model", false).getBoolean(false); @@ -333,6 +335,7 @@ public class ConfigClient { FontSize = LegacyConfig.FontSize; FontSizeProperty.set(FontSize); } + } catch (Exception e) { FMLLog.log(Level.ERROR, e, "CNPC+ has had a problem loading its client configuration"); } finally { diff --git a/src/main/java/noppes/npcs/constants/EnumScriptType.java b/src/main/java/noppes/npcs/constants/EnumScriptType.java index 5b5a318b3..01fa36ac2 100644 --- a/src/main/java/noppes/npcs/constants/EnumScriptType.java +++ b/src/main/java/noppes/npcs/constants/EnumScriptType.java @@ -127,7 +127,12 @@ public enum EnumScriptType { ABILITY_HIT("abilityHit"), ABILITY_TICK("abilityTick"), ABILITY_TOGGLE("abilityToggle"), - ABILITY_TOGGLE_UPDATE("abilityToggleUpdate"), + ABILITY_TOGGLE_TICK("abilityToggleTick"), + + CHAIN_START("chainStart"), + CHAIN_NEXT("chainNext"), + CHAIN_COMPLETE("chainComplete"), + CHAIN_INTERRUPT("chainInterrupt"), ENERGY_PROJECTILE_FIRED("energyProjectileFired"), ENERGY_PROJECTILE_TICK("energyProjectileTick"), diff --git a/src/main/java/noppes/npcs/constants/ScriptContext.java b/src/main/java/noppes/npcs/constants/ScriptContext.java index 9b06001ff..e35a361d7 100644 --- a/src/main/java/noppes/npcs/constants/ScriptContext.java +++ b/src/main/java/noppes/npcs/constants/ScriptContext.java @@ -13,7 +13,7 @@ import noppes.npcs.api.event.IForgeEvent; import noppes.npcs.api.event.IItemEvent; import noppes.npcs.api.event.INpcEvent; import noppes.npcs.api.event.IPartyEvent; -import noppes.npcs.api.event.IPlayerAbilityEvent; +import noppes.npcs.api.event.IChainEvent; import noppes.npcs.api.event.IPlayerEvent; import noppes.npcs.api.event.IProjectileEvent; import noppes.npcs.api.event.IQuestEvent; @@ -61,6 +61,7 @@ public class ScriptContext { IEnergyProjectileEvent.class, IEnergyBarrierEvent.class, IAbilityEvent.class, + IChainEvent.class, IAnimationEvent.class ); @@ -74,7 +75,8 @@ public class ScriptContext { ICustomGuiEvent.class, IEnergyProjectileEvent.class, IEnergyBarrierEvent.class, - IPlayerAbilityEvent.class, + IAbilityEvent.class, + IChainEvent.class, IAuctionEvent.class ); @@ -102,6 +104,14 @@ public class ScriptContext { "Effect" ); + public static final ScriptContext ABILITY = register("ABILITY", "ability", + "Ability" + ); + + public static final ScriptContext CHAINED_ABILITY = register("CHAINED_ABILITY", "chained_ability", + "ChainedAbility" + ); + public static final ScriptContext GLOBAL = register("GLOBAL", "", "Global" // Special case: Global namespace doesn't have a corresponding event class ); diff --git a/src/main/java/noppes/npcs/controllers/PlayerQuestController.java b/src/main/java/noppes/npcs/controllers/PlayerQuestController.java index 7b99f40d8..288c24f79 100644 --- a/src/main/java/noppes/npcs/controllers/PlayerQuestController.java +++ b/src/main/java/noppes/npcs/controllers/PlayerQuestController.java @@ -1,6 +1,7 @@ package noppes.npcs.controllers; import kamkeel.npcs.controllers.ProfileController; +import kamkeel.npcs.controllers.data.profile.Profile; import kamkeel.npcs.network.packets.data.AchievementPacket; import kamkeel.npcs.network.packets.data.ChatAlertPacket; import net.minecraft.entity.player.EntityPlayer; @@ -91,7 +92,9 @@ public class PlayerQuestController { questData.finishedQuests.put(quest.id, completeTime); } - if (ConfigMain.ProfilesEnabled && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) + if (ConfigMain.ProfilesEnabled && quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) ProfileController.Instance.shareQuestCompletion(player, quest.id, completeTime); } @@ -125,27 +128,29 @@ public class PlayerQuestController { if (data.activeQuests.containsKey(quest.id)) return false; - if (!data.finishedQuests.containsKey(quest.id) || quest.repeat == EnumQuestRepeat.REPEATABLE) + boolean finishedLocally = data.finishedQuests.containsKey(quest.id); + boolean completedShared = false; + boolean hasCooldownShared = false; + if (ConfigMain.ProfilesEnabled && quest.profileOptions.enableOptions) { + Profile profile = ProfileController.Instance.getProfile(player); + if (profile != null && profile.sharedQuestTimestamps.containsKey(quest.id)) { + if (quest.profileOptions.completeControl == EnumProfileSync.Shared) + completedShared = true; + if (quest.profileOptions.cooldownControl == EnumProfileSync.Shared) + hasCooldownShared = true; + } + } + + boolean isFinished = finishedLocally || completedShared; + + if (!isFinished && !hasCooldownShared) + return true; + if (quest.repeat == EnumQuestRepeat.REPEATABLE) return true; if (quest.repeat == EnumQuestRepeat.NONE) - return false; + return !isFinished; - long questTime = data.finishedQuests.get(quest.id); - - if (quest.repeat == EnumQuestRepeat.MCDAILY) { - return player.worldObj.getTotalWorldTime() - questTime >= 24000; - } else if (quest.repeat == EnumQuestRepeat.MCWEEKLY) { - return player.worldObj.getTotalWorldTime() - questTime >= 168000; - } else if (quest.repeat == EnumQuestRepeat.MCCUSTOM) { - return player.worldObj.getTotalWorldTime() - questTime >= quest.customCooldown; - } else if (quest.repeat == EnumQuestRepeat.RLDAILY) { - return System.currentTimeMillis() - questTime >= 86400000; - } else if (quest.repeat == EnumQuestRepeat.RLWEEKLY) { - return System.currentTimeMillis() - questTime >= 604800000; - } else if (quest.repeat == EnumQuestRepeat.RLCUSTOM) { - return System.currentTimeMillis() - questTime >= quest.customCooldown; - } - return false; + return quest.getTimeUntilRepeat(player) <= 0; } public static Vector getActiveQuests(EntityPlayer player) { diff --git a/src/main/java/noppes/npcs/controllers/QuestController.java b/src/main/java/noppes/npcs/controllers/QuestController.java index 72688b7e5..e9b403ee7 100644 --- a/src/main/java/noppes/npcs/controllers/QuestController.java +++ b/src/main/java/noppes/npcs/controllers/QuestController.java @@ -80,7 +80,9 @@ public class QuestController implements IQuestHandler { ite.remove(); } else { quests.put(id, quest); - if (quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) { + if (quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) { sharedQuests.put(id, quest); } } @@ -225,7 +227,9 @@ public class QuestController implements IQuestHandler { category.quests.put(quest.id, quest); sharedQuests.remove(quest.id); - if (quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared) { + if (quest.profileOptions.enableOptions + && (quest.profileOptions.completeControl == EnumProfileSync.Shared + || quest.profileOptions.cooldownControl == EnumProfileSync.Shared)) { sharedQuests.put(quest.id, quest); } diff --git a/src/main/java/noppes/npcs/controllers/ScriptHookController.java b/src/main/java/noppes/npcs/controllers/ScriptHookController.java index dd8c18550..5547fb203 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptHookController.java +++ b/src/main/java/noppes/npcs/controllers/ScriptHookController.java @@ -1,6 +1,7 @@ package noppes.npcs.controllers; import noppes.npcs.api.event.IAbilityEvent; +import noppes.npcs.api.event.IChainEvent; import noppes.npcs.api.event.IAnimationEvent; import noppes.npcs.api.event.IAuctionEvent; import noppes.npcs.api.event.IBlockEvent; @@ -15,7 +16,6 @@ import noppes.npcs.api.event.IItemEvent; import noppes.npcs.api.event.ILinkedItemEvent; import noppes.npcs.api.event.INpcEvent; import noppes.npcs.api.event.IPartyEvent; -import noppes.npcs.api.event.IPlayerAbilityEvent; import noppes.npcs.api.event.IPlayerEvent; import noppes.npcs.api.event.IProjectileEvent; import noppes.npcs.api.event.IQuestEvent; @@ -41,6 +41,8 @@ import static noppes.npcs.constants.ScriptContext.ITEM; import static noppes.npcs.constants.ScriptContext.LINKED_ITEM; import static noppes.npcs.constants.ScriptContext.NPC; import static noppes.npcs.constants.ScriptContext.PLAYER; +import static noppes.npcs.constants.ScriptContext.ABILITY; +import static noppes.npcs.constants.ScriptContext.CHAINED_ABILITY; import static noppes.npcs.constants.ScriptContext.RECIPE; /** @@ -81,6 +83,7 @@ public class ScriptHookController implements IScriptHookHandler { initializeLinkedItemHooks(); initializeRecipeHooks(); initializeEffectHooks(); + initializeAbilityHooks(); initializeForgeHooks(); } @@ -124,6 +127,14 @@ public class ScriptHookController implements IScriptHookHandler { hook(NPC, ABILITY_TICK, IAbilityEvent.TickEvent.class); hook(NPC, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); hook(NPC, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + hook(NPC, ABILITY_TOGGLE, IAbilityEvent.ToggleEvent.class); + hook(NPC, ABILITY_TOGGLE_TICK, IAbilityEvent.ToggleUpdateEvent.class); + + // Chain + hook(NPC, CHAIN_START, IChainEvent.StartEvent.class); + hook(NPC, CHAIN_NEXT, IChainEvent.NextEvent.class); + hook(NPC, CHAIN_COMPLETE, IChainEvent.CompleteEvent.class); + hook(NPC, CHAIN_INTERRUPT, IChainEvent.InterruptEvent.class); // Energy Barrier hook(NPC, ENERGY_BARRIER_SPAWNED, IEnergyBarrierEvent.SpawnedEvent.class); @@ -245,12 +256,20 @@ public class ScriptHookController implements IScriptHookHandler { hook(PLAYER, ENERGY_BARRIER_DESTROYED, IEnergyBarrierEvent.DestroyedEvent.class); // Ability - hook(PLAYER, ABILITY_START, IPlayerAbilityEvent.StartEvent.class); - hook(PLAYER, ABILITY_EXECUTE, IPlayerAbilityEvent.ExecuteEvent.class); - hook(PLAYER, ABILITY_HIT, IPlayerAbilityEvent.HitEvent.class); - hook(PLAYER, ABILITY_TICK, IPlayerAbilityEvent.TickEvent.class); - hook(PLAYER, ABILITY_INTERRUPT, IPlayerAbilityEvent.InterruptEvent.class); - hook(PLAYER, ABILITY_COMPLETE, IPlayerAbilityEvent.CompleteEvent.class); + hook(PLAYER, ABILITY_START, IAbilityEvent.StartEvent.class); + hook(PLAYER, ABILITY_EXECUTE, IAbilityEvent.ExecuteEvent.class); + hook(PLAYER, ABILITY_HIT, IAbilityEvent.HitEvent.class); + hook(PLAYER, ABILITY_TICK, IAbilityEvent.TickEvent.class); + hook(PLAYER, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); + hook(PLAYER, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + hook(PLAYER, ABILITY_TOGGLE, IAbilityEvent.ToggleEvent.class); + hook(PLAYER, ABILITY_TOGGLE_TICK, IAbilityEvent.ToggleUpdateEvent.class); + + // Chain + hook(PLAYER, CHAIN_START, IChainEvent.StartEvent.class); + hook(PLAYER, CHAIN_NEXT, IChainEvent.NextEvent.class); + hook(PLAYER, CHAIN_COMPLETE, IChainEvent.CompleteEvent.class); + hook(PLAYER, CHAIN_INTERRUPT, IChainEvent.InterruptEvent.class); // Auction hook(PLAYER, AUCTION_CREATE, IAuctionEvent.CreateEvent.class); @@ -333,6 +352,24 @@ public class ScriptHookController implements IScriptHookHandler { hook(EFFECT, ON_EFFECT_REMOVE, IPlayerEvent.EffectEvent.Removed.class); } + private void initializeAbilityHooks() { + // Ability context (internal per-ability scripts) + hook(ABILITY, ABILITY_START, IAbilityEvent.StartEvent.class); + hook(ABILITY, ABILITY_EXECUTE, IAbilityEvent.ExecuteEvent.class); + hook(ABILITY, ABILITY_HIT, IAbilityEvent.HitEvent.class); + hook(ABILITY, ABILITY_TICK, IAbilityEvent.TickEvent.class); + hook(ABILITY, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); + hook(ABILITY, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + hook(ABILITY, ABILITY_TOGGLE, IAbilityEvent.ToggleEvent.class); + hook(ABILITY, ABILITY_TOGGLE_TICK, IAbilityEvent.ToggleUpdateEvent.class); + + // Chained ability context (chain-level lifecycle hooks) + hook(CHAINED_ABILITY, CHAIN_START, IChainEvent.StartEvent.class); + hook(CHAINED_ABILITY, CHAIN_NEXT, IChainEvent.NextEvent.class); + hook(CHAINED_ABILITY, CHAIN_COMPLETE, IChainEvent.CompleteEvent.class); + hook(CHAINED_ABILITY, CHAIN_INTERRUPT, IChainEvent.InterruptEvent.class); + } + private void initializeForgeHooks() { hook(FORGE, INIT, IForgeEvent.InitEvent.class); hook(FORGE, FORGE_WORLD, IForgeEvent.WorldEvent.class); diff --git a/src/main/java/noppes/npcs/controllers/data/AbilityScript.java b/src/main/java/noppes/npcs/controllers/data/AbilityScript.java new file mode 100644 index 000000000..82af01b52 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/AbilityScript.java @@ -0,0 +1,54 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.network.packets.request.script.AbilityScriptPacket; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.ScriptContext; + +/** + * Script handler for ability scripts. + * Manages a single script container for ability hooks (abilityStart, abilityTick, abilityComplete, etc.). + */ +public class AbilityScript extends SingleScriptHandler implements IScriptHandlerPacket { + + /** + * The ability ID (UUID) for packet communication. Empty if not bound. + */ + private String abilityId = ""; + + /** + * Create an unbound AbilityScript (for server-side use). + */ + public AbilityScript() { + } + + /** + * Create an AbilityScript bound to a specific ability (for GUI use). + * + * @param abilityId The UUID of the ability + */ + public AbilityScript(String abilityId) { + this.abilityId = abilityId != null ? abilityId : ""; + } + + @Override + public ScriptContext getContext() { + return ScriptContext.ABILITY; + } + + @Override + public String noticeString() { + return !abilityId.isEmpty() ? "Ability[" + abilityId + "]" : "Ability"; + } + + @Override + public void requestData() { + if (!abilityId.isEmpty()) + AbilityScriptPacket.Get(abilityId); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (!abilityId.isEmpty()) + AbilityScriptPacket.Save(abilityId, index, totalCount, nbt); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/ChainedAbilityScript.java b/src/main/java/noppes/npcs/controllers/data/ChainedAbilityScript.java new file mode 100644 index 000000000..e15b05d10 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/ChainedAbilityScript.java @@ -0,0 +1,54 @@ +package noppes.npcs.controllers.data; + +import kamkeel.npcs.network.packets.request.script.ChainedAbilityScriptPacket; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.ScriptContext; + +/** + * Script handler for chained ability scripts. + * Manages a single script container for chained ability hooks. + */ +public class ChainedAbilityScript extends SingleScriptHandler implements IScriptHandlerPacket { + + /** + * The chained ability ID (UUID) for packet communication. Empty if not bound. + */ + private String chainId = ""; + + /** + * Create an unbound ChainedAbilityScript (for server-side use). + */ + public ChainedAbilityScript() { + } + + /** + * Create a ChainedAbilityScript bound to a specific chained ability (for GUI use). + * + * @param chainId The UUID of the chained ability + */ + public ChainedAbilityScript(String chainId) { + this.chainId = chainId != null ? chainId : ""; + } + + @Override + public ScriptContext getContext() { + return ScriptContext.CHAINED_ABILITY; + } + + @Override + public String noticeString() { + return !chainId.isEmpty() ? "ChainedAbility[" + chainId + "]" : "ChainedAbility"; + } + + @Override + public void requestData() { + if (!chainId.isEmpty()) + ChainedAbilityScriptPacket.Get(chainId); + } + + @Override + public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) { + if (!chainId.isEmpty()) + ChainedAbilityScriptPacket.Save(chainId, index, totalCount, nbt); + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/CustomEffect.java b/src/main/java/noppes/npcs/controllers/data/CustomEffect.java index 7a5db74de..aec4eaf6e 100644 --- a/src/main/java/noppes/npcs/controllers/data/CustomEffect.java +++ b/src/main/java/noppes/npcs/controllers/data/CustomEffect.java @@ -26,15 +26,14 @@ public class CustomEffect implements ICustomEffect { public String icon = ""; public int iconX = 0, iconY = 0; - /** - * Experimental script stuff. - */ - public Consumer onAddedConsumer; - public Consumer onTickConsumer; - public Consumer onRemovedConsumer; public String menuName = "§aNEW EFFECT"; public int width = 16, height = 16; + // Animation + public boolean animated = false; + public int frameCount = 1; + public int frametime = 2; + public int index = 0; public CustomEffect() { @@ -143,6 +142,36 @@ public class CustomEffect implements ICustomEffect { this.height = height; } + @Override + public boolean isAnimated() { + return animated; + } + + @Override + public void setAnimated(boolean animated) { + this.animated = animated; + } + + @Override + public int getFrameCount() { + return frameCount; + } + + @Override + public void setFrameCount(int frameCount) { + this.frameCount = Math.max(1, frameCount); + } + + @Override + public int getFrameTime() { + return frametime; + } + + @Override + public void setFrameTime(int frametime) { + this.frametime = Math.max(1, frametime); + } + @Override public boolean isLossOnDeath() { return lossOnDeath; @@ -169,26 +198,10 @@ public class CustomEffect implements ICustomEffect { } - public void onAdded(Consumer function) { - onAddedConsumer = function; - } - - public void onTick(Consumer function) { - onTickConsumer = function; - } - - public void onRemoved(Consumer function) { - onRemovedConsumer = function; - } - public void onAdded(EntityPlayer player, PlayerEffect playerEffect) { IPlayer iPlayer = NoppesUtilServer.getIPlayer(player); if (playerEffect.index == 0) { PlayerEvent.EffectEvent.Added event = new PlayerEvent.EffectEvent.Added(iPlayer, playerEffect); - - if (onAddedConsumer != null) - onAddedConsumer.accept(event); - EffectScript script = getScriptHandler(); if (script == null) { return; @@ -204,11 +217,6 @@ public class CustomEffect implements ICustomEffect { IPlayer iPlayer = NoppesUtilServer.getIPlayer(player); if (playerEffect.index == 0) { PlayerEvent.EffectEvent.Ticked event = new PlayerEvent.EffectEvent.Ticked(iPlayer, playerEffect); - - if (onTickConsumer != null) { - onTickConsumer.accept(event); - } - EffectScript script = getScriptHandler(); if (script == null) { return; @@ -225,11 +233,6 @@ public class CustomEffect implements ICustomEffect { if (playerEffect.index == 0) { PlayerEvent.EffectEvent.Removed event = new PlayerEvent.EffectEvent.Removed(iPlayer, playerEffect, type); - - if (onRemovedConsumer != null) { - onRemovedConsumer.accept(event); - } - EffectScript script = getScriptHandler(); if (script == null) { return; @@ -254,6 +257,9 @@ public class CustomEffect implements ICustomEffect { compound.setInteger("iconHeight", height); compound.setString("icon", icon); compound.setBoolean("lossOnDeath", lossOnDeath); + compound.setBoolean("iconAnimated", animated); + compound.setInteger("iconFrameCount", frameCount); + compound.setInteger("iconFrameTime", frametime); if (saveScripts) { NBTTagCompound scriptData = new NBTTagCompound(); @@ -296,6 +302,13 @@ public class CustomEffect implements ICustomEffect { icon = compound.getString("icon"); lossOnDeath = compound.getBoolean("lossOnDeath"); + if (compound.hasKey("iconAnimated")) + animated = compound.getBoolean("iconAnimated"); + if (compound.hasKey("iconFrameCount")) + frameCount = Math.max(1, compound.getInteger("iconFrameCount")); + if (compound.hasKey("iconFrameTime")) + frametime = Math.max(1, compound.getInteger("iconFrameTime")); + if (compound.hasKey("ScriptData", Constants.NBT.TAG_COMPOUND)) { EffectScript handler = new EffectScript(); handler.readFromNBT(compound.getCompoundTag("ScriptData")); diff --git a/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java b/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java index e40452bfc..c26edbf0c 100644 --- a/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java +++ b/src/main/java/noppes/npcs/controllers/data/ItemDisplayData.java @@ -12,6 +12,11 @@ public class ItemDisplayData { public Boolean durabilityShow = false; public Integer durabilityColor = -1; + // Animation + public Boolean animated = false; + public Integer frameCount = 1; + public Integer frametime = 2; + public NBTTagCompound writeToNBT() { NBTTagCompound compound = new NBTTagCompound(); this.writeToNBT(compound); @@ -42,6 +47,10 @@ public class ItemDisplayData { this.setFloat(compound, "TranslateY", this.translateY); this.setFloat(compound, "TranslateZ", this.translateZ); + this.setBoolean(compound, "Animated", this.animated); + this.setInteger(compound, "FrameCount", this.frameCount); + this.setInteger(compound, "FrameTime", this.frametime); + return compound; } @@ -97,6 +106,16 @@ public class ItemDisplayData { if (compound.hasKey("TranslateZ")) { this.translateZ = compound.getFloat("TranslateZ"); } + + if (compound.hasKey("Animated")) { + this.animated = compound.getBoolean("Animated"); + } + if (compound.hasKey("FrameCount")) { + this.frameCount = Math.max(1, compound.getInteger("FrameCount")); + } + if (compound.hasKey("FrameTime")) { + this.frametime = Math.max(1, compound.getInteger("FrameTime")); + } } private void setBoolean(NBTTagCompound compound, String key, Boolean value) { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index f5a36e836..600926785 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -7,7 +7,6 @@ import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase; import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; import kamkeel.npcs.controllers.data.ability.data.IAbilityAction; import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry; -import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; @@ -25,10 +24,6 @@ import noppes.npcs.AbstractDataAbilities; import noppes.npcs.EventHooks; import noppes.npcs.LogWriter; import noppes.npcs.api.ability.IPlayerAbilityData; -import noppes.npcs.api.entity.IPlayer; -import noppes.npcs.controllers.ScriptController; -import noppes.npcs.scripted.NpcAPI; -import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import java.util.ArrayList; import java.util.Iterator; @@ -129,53 +124,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA return player != null ? player.worldObj.getTotalWorldTime() : 0; } - @Override - protected void fireTickEvent(Ability ability, EntityLivingBase target) { - EntityPlayer player = playerData.player; - if (ScriptController.Instance == null || player == null) return; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.TickEvent event = new PlayerAbilityEvent.TickEvent( - iPlayer, ability, target, ability.getPhase().ordinal(), ability.getCurrentTick()); - EventHooks.onPlayerAbilityTick(handler, event); - } - - @Override - protected boolean fireExecuteEvent(Ability ability, EntityLivingBase target) { - EntityPlayer player = playerData.player; - if (ScriptController.Instance == null || player == null) return false; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return false; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.ExecuteEvent event = new PlayerAbilityEvent.ExecuteEvent(iPlayer, ability, target); - return EventHooks.onPlayerAbilityExecute(handler, event); - } - - @Override - protected void fireCompleteEvent(Ability ability, EntityLivingBase target) { - EntityPlayer player = playerData.player; - if (ScriptController.Instance == null || player == null) return; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.CompleteEvent event = new PlayerAbilityEvent.CompleteEvent(iPlayer, ability, target); - EventHooks.onPlayerAbilityComplete(handler, event); - } - - @Override - protected void fireInterruptEvent(Ability ability, EntityLivingBase target, - DamageSource source, float damage) { - EntityPlayer player = playerData.player; - if (ScriptController.Instance == null || player == null) return; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.InterruptEvent event = new PlayerAbilityEvent.InterruptEvent( - iPlayer, ability, target, source, damage); - EventHooks.onPlayerAbilityInterrupt(handler, event); - } - @Override protected void spawnTelegraph(Ability ability, EntityLivingBase target) { EntityPlayer player = playerData.player; @@ -423,7 +371,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } // Fire start event (cancelable) - if (firePlayerStartEvent(player, ability)) { + if (EventHooks.onAbilityStart(ability, player, null)) { return false; // Cancelled } @@ -491,29 +439,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA protected void onToggleStateChanged(String key, boolean active, int state) { } - @Override - protected boolean fireToggleEvent(Ability ability, int oldState, int newState) { - EntityPlayer player = playerData.player; - if (ScriptController.Instance == null || player == null) return false; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return false; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.ToggleEvent event = new PlayerAbilityEvent.ToggleEvent(iPlayer, ability, oldState, newState); - return EventHooks.onPlayerAbilityToggle(handler, event); - } - - @Override - protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) { - EntityPlayer player = playerData.player; - if (ScriptController.Instance == null || player == null) return true; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return true; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.ToggleUpdateEvent event = new PlayerAbilityEvent.ToggleUpdateEvent(iPlayer, ability, tick, state); - EventHooks.onPlayerAbilityToggleUpdate(handler, event); - return event.isEnabled(); - } - // ═══════════════════════════════════════════════════════════════════ // SELECTION // ═══════════════════════════════════════════════════════════════════ @@ -861,32 +786,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA return 0; } - net.minecraft.entity.Entity sourceEntity = source.getEntity(); - EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null; - - // Track counter state before calling onDamageTaken - boolean wasCounterTriggered = false; - if (currentAbility instanceof AbilityGuard) { - wasCounterTriggered = ((AbilityGuard) currentAbility).isCounterTriggered(); - } - - currentAbility.onDamageTaken(playerData.player, attacker, source, amount); - - // Guard: handle damage reduction and counter absorption - if (currentAbility instanceof AbilityGuard) { - AbilityGuard guard = (AbilityGuard) currentAbility; - if (guard.isGuarding()) { - // Counter just triggered — absorb full damage - if (!wasCounterTriggered && guard.isCounterTriggered()) { - return 0; - } - // Normal guard — apply flat damage reduction - float reduction = guard.getDamageReductionFactor(); - return Math.max(0, amount - reduction); - } - } - - // Check for ability interruption if (currentAbility != null && currentAbility.canInterrupt(source)) { interruptCurrentAbility(source, amount); } @@ -1035,22 +934,6 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } } - // ═══════════════════════════════════════════════════════════════════ - // SCRIPT EVENTS (Player-specific: start event only, others via abstract) - // ═══════════════════════════════════════════════════════════════════ - - /** - * Fire the ability start event. Returns true if cancelled. - */ - private boolean firePlayerStartEvent(EntityPlayer player, Ability ability) { - if (ScriptController.Instance == null) return false; - PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); - if (handler == null) return false; - IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); - PlayerAbilityEvent.StartEvent event = new PlayerAbilityEvent.StartEvent(iPlayer, ability, null); - return EventHooks.onPlayerAbilityStart(handler, event); - } - // ═══════════════════════════════════════════════════════════════════ // NBT SERIALIZATION // ═══════════════════════════════════════════════════════════════════ @@ -1096,7 +979,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA } playingAbilityAnimation = compound.getBoolean("AbilityAnimating"); - // Active toggles - restore state directly (no onToggleOn callback during load) + // Active toggles - restore state directly (no onToggle callback during load) activeToggles.clear(); if (compound.hasKey("ActiveToggles")) { NBTTagList toggleNbt = compound.getTagList("ActiveToggles", 10); // 10 = TAG_COMPOUND @@ -1117,9 +1000,6 @@ 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 it = unlockedAbilities.iterator(); diff --git a/src/main/java/noppes/npcs/controllers/data/Quest.java b/src/main/java/noppes/npcs/controllers/data/Quest.java index 1f9097d8a..c2b9ac397 100644 --- a/src/main/java/noppes/npcs/controllers/data/Quest.java +++ b/src/main/java/noppes/npcs/controllers/data/Quest.java @@ -178,19 +178,50 @@ public class Quest implements ICompatibilty, IQuest { public long getTimeUntilRepeat(EntityPlayer player) { if (ConfigMain.ProfilesEnabled && profileOptions.enableOptions && profileOptions.cooldownControl == EnumProfileSync.Shared) { Profile profile = ProfileController.Instance.getProfile(player); - IPlayer iPlayer = NoppesUtilServer.getIPlayer(player); - long timeRemaining = 0L; - for (ISlot slot : profile.getSlots().values()) { - IPlayerData playerData = ProfileController.Instance.getSlotPlayerData(iPlayer, slot.getId()); - IPlayerQuestData iPlayerQuestData = playerData.getQuestData(); - timeRemaining = Math.max(timeRemaining, getTimeUntilRepeatQuestData(player, iPlayerQuestData)); + if (profile != null) { + Long questTime = profile.sharedQuestTimestamps.get(this.id); + if (questTime == null) return 0L; + return calculateRemainingCooldown(player, questTime); } - return timeRemaining; } IPlayerQuestData questData = PlayerData.get(player).getQuestData(); return getTimeUntilRepeatQuestData(player, questData); } + public long calculateRemainingCooldown(EntityPlayer player, long questTime) { + switch (repeat) { + case MCDAILY: { + long now = player.worldObj.getTotalWorldTime(); + long remainingTicks = questTime + 24000 - now; + return Math.max(0, remainingTicks * 50); + } + case MCWEEKLY: { + long now = player.worldObj.getTotalWorldTime(); + long remainingTicks = questTime + 168000 - now; + return Math.max(0, remainingTicks * 50); + } + case MCCUSTOM: { + long now = player.worldObj.getTotalWorldTime(); + long remainingTicks = questTime + this.customCooldown - now; + return Math.max(0, remainingTicks * 50); + } + case RLDAILY: { + long remainingMillis = questTime + 86400000 - System.currentTimeMillis(); + return Math.max(0, remainingMillis); + } + case RLWEEKLY: { + long remainingMillis = questTime + 604800000 - System.currentTimeMillis(); + return Math.max(0, remainingMillis); + } + case RLCUSTOM: { + long remainingMillis = questTime + this.customCooldown - System.currentTimeMillis(); + return Math.max(0, remainingMillis); + } + default: + return 0L; + } + } + public long getTimeUntilRepeatQuestData(EntityPlayer player, IPlayerQuestData questData) { long questTime = questData.getLastCompletedTime(this.id); diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index a3dcfb84c..6045317d8 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -6,6 +6,9 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import kamkeel.npcs.addon.DBCAddon; +import kamkeel.npcs.controllers.data.ability.type.AbilityCounter; +import kamkeel.npcs.controllers.data.ability.type.AbilityDefend; +import kamkeel.npcs.controllers.data.ability.type.AbilityDodge; import kamkeel.npcs.addon.client.DBCClient; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumSoundOperation; @@ -709,6 +712,21 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti // Resistances i = stats.resistances.applyResistance(damagesource, i); + // Defend abilities + AbilityDefend defend = this.abilities != null ? this.abilities.getActiveDefend() : null; + if (defend != null) { + // Dodge & Counter: cancel attack entirely + if (defend instanceof AbilityDodge || defend instanceof AbilityCounter) { + float result = defend.onDefend(attackingEntity, damagesource, i); + if (result != i) { + return false; + } + } else { + // Guard: reduce damage + i = defend.onDefend(attackingEntity, damagesource, i); + } + } + NpcEvent.DamagedEvent event = new NpcEvent.DamagedEvent(this.wrappedNPC, attackingEntity, i, damagesource); if (EventHooks.onNPCDamaged(this, event) || isKilled()) return false; diff --git a/src/main/java/noppes/npcs/items/ItemStaff.java b/src/main/java/noppes/npcs/items/ItemStaff.java index 5ce50d011..5dc674b30 100644 --- a/src/main/java/noppes/npcs/items/ItemStaff.java +++ b/src/main/java/noppes/npcs/items/ItemStaff.java @@ -91,6 +91,19 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { int chargeTime = 20 + material.getHarvestLevel() * 8; + // Keep a fully-charged orb alive while the player is still holding + if (tick > chargeTime && stack.stackTagCompound != null) { + Entity existing = ((WorldServer) player.worldObj) + .getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); + if (existing instanceof EntityAbilityOrb) { + EntityAbilityOrb orb = (EntityAbilityOrb) existing; + if (orb.isCharging()) { + orb.resetChargeTick(); + } + } + return; + } + if (tick == chargeTime) { if (!player.capabilities.isCreativeMode && !hasInfinite(stack)) { diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index 09c294e2f..0864e16ec 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -9,11 +9,11 @@ import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityDisc; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyDome; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.entity.EntityAbilityPanel; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergyPanel; +import kamkeel.npcs.entity.EntityEnergySweeper; import kamkeel.npcs.entity.EntityEnergyProjectile; import kamkeel.npcs.entity.EntityEnergySlicer; import net.minecraft.block.Block; @@ -456,12 +456,12 @@ public class NpcAPI extends AbstractNpcAPI { data = new ScriptEntityData(new ScriptEnergySlicer<>((EntityEnergySlicer) entity)); else if (entity instanceof EntityEnergyProjectile) data = new ScriptEntityData(new ScriptEnergyProjectile((EntityEnergyProjectile) entity)); - else if (entity instanceof EntityAbilityDome) - data = new ScriptEntityData(new ScriptEnergyDome<>((EntityAbilityDome) entity)); - else if (entity instanceof EntityAbilityPanel) - data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityAbilityPanel) entity)); - else if (entity instanceof EntityAbilitySweeper) - data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityAbilitySweeper) entity)); + else if (entity instanceof EntityEnergyDome) + data = new ScriptEntityData(new ScriptEnergyDome<>((EntityEnergyDome) entity)); + else if (entity instanceof EntityEnergyPanel) + data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityEnergyPanel) entity)); + else if (entity instanceof EntityEnergySweeper) + data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityEnergySweeper) entity)); else data = new ScriptEntityData(new ScriptEntity<>(entity)); entity.registerExtendedProperties("ScriptedObject", data); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java index fe02608e1..b7f5291bd 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBarrier.java @@ -1,15 +1,15 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityAbilityBarrier; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyBarrier; +import kamkeel.npcs.entity.EntityEnergyDome; import noppes.npcs.api.entity.IEnergyBarrier; import noppes.npcs.scripted.constants.EntityType; /** * Base script wrapper for energy barrier entities (Dome, Panel). - * All shared methods delegate directly to EntityAbilityBarrier base. + * All shared methods delegate directly to EntityEnergyBarrier base. */ -public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { +public class ScriptEnergyBarrier extends ScriptEnergyAbility implements IEnergyBarrier { public ScriptEnergyBarrier(T entity) { super(entity); @@ -138,6 +138,6 @@ public class ScriptEnergyBarrier extends ScriptE } public int getBarrierType() { - return entity instanceof EntityAbilityDome ? 0 : 1; + return entity instanceof EntityEnergyDome ? 0 : 1; } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java index 9bcceefbc..e022118f7 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDome.java @@ -1,10 +1,10 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityAbilityDome; +import kamkeel.npcs.entity.EntityEnergyDome; import noppes.npcs.api.entity.IEnergyDome; import noppes.npcs.scripted.constants.EntityType; -public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { +public class ScriptEnergyDome extends ScriptEnergyBarrier implements IEnergyDome { public ScriptEnergyDome(T entity) { super(entity); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java index fa929b4a8..04c730fad 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyPanel.java @@ -1,10 +1,10 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityAbilityPanel; +import kamkeel.npcs.entity.EntityEnergyPanel; import noppes.npcs.api.entity.IEnergyPanel; import noppes.npcs.scripted.constants.EntityType; -public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { +public class ScriptEnergyPanel extends ScriptEnergyBarrier implements IEnergyPanel { public ScriptEnergyPanel(T entity) { super(entity); @@ -52,6 +52,6 @@ public class ScriptEnergyPanel extends ScriptEnerg } public boolean isLaunched() { - return entity.getMode() == EntityAbilityPanel.PanelMode.LAUNCHED; + return entity.getMode() == EntityEnergyPanel.PanelMode.LAUNCHED; } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java index cf957c062..52207238d 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergySweeper.java @@ -1,8 +1,8 @@ package noppes.npcs.scripted.entity; -import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityEnergySweeper; -public class ScriptEnergySweeper extends ScriptEnergyAbility { +public class ScriptEnergySweeper extends ScriptEnergyAbility { public ScriptEnergySweeper(T entity) { super(entity); } diff --git a/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java b/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java index 769add405..a5d5c5bf4 100644 --- a/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java +++ b/src/main/java/noppes/npcs/scripted/event/AbilityEvent.java @@ -8,22 +8,48 @@ import noppes.npcs.api.IDamageSource; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.scripted.NpcAPI; /** - * Events fired during NPC ability execution lifecycle. + * Unified ability events for both NPCs and Players. */ -public class AbilityEvent extends NpcEvent implements IAbilityEvent { +public class AbilityEvent extends CustomNPCsEvent implements IAbilityEvent { + protected final IEntityLivingBase entity; + public final IPlayer player; + public final ICustomNpc npc; protected final Ability ability; protected final IEntityLivingBase target; private transient IAbility abilityCopy; - public AbilityEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc); + public AbilityEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + this.entity = entity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(entity) : null; this.ability = ability; this.target = target != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(target) : null; + this.player = (this.entity instanceof IPlayer) ? (IPlayer) this.entity : null; + this.npc = (this.entity instanceof ICustomNpc) ? (ICustomNpc) this.entity : null; + } + + @Override + public IEntityLivingBase getEntity() { + return entity; + } + + @Override + public IPlayer getPlayer() { + return player; + } + + @Override + public ICustomNpc getNpc() { + return npc; + } + + @Override + public boolean isNPC() { + return entity instanceof ICustomNpc; } @Override @@ -44,13 +70,10 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { return "abilityEvent"; } - /** - * Fired when an ability starts executing (enters WINDUP phase). - */ @Cancelable public static class StartEvent extends AbilityEvent implements IAbilityEvent.StartEvent { - public StartEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc, ability, target); + public StartEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); } @Override @@ -59,13 +82,10 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability enters the ACTIVE phase and performs its effect. - */ @Cancelable public static class ExecuteEvent extends AbilityEvent implements IAbilityEvent.ExecuteEvent { - public ExecuteEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc, ability, target); + public ExecuteEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); } @Override @@ -74,16 +94,13 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability is interrupted by damage. - */ public static class InterruptEvent extends AbilityEvent implements IAbilityEvent.InterruptEvent { private final IDamageSource damageSource; private final float damage; - public InterruptEvent(ICustomNpc npc, Ability ability, EntityLivingBase target, DamageSource source, float damage) { - super(npc, ability, target); - this.damageSource = NpcAPI.Instance().getIDamageSource(source); + public InterruptEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, DamageSource source, float damage) { + super(entity, ability, target); + this.damageSource = source != null ? NpcAPI.Instance().getIDamageSource(source) : null; this.damage = damage; } @@ -103,12 +120,9 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability completes its full execution cycle. - */ public static class CompleteEvent extends AbilityEvent implements IAbilityEvent.CompleteEvent { - public CompleteEvent(ICustomNpc npc, Ability ability, EntityLivingBase target) { - super(npc, ability, target); + public CompleteEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target) { + super(entity, ability, target); } @Override @@ -117,10 +131,6 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when an ability hits an entity with damage. - * This is a cancelable event - canceling prevents the damage from being applied. - */ @Cancelable public static class HitEvent extends AbilityEvent implements IAbilityEvent.HitEvent { private final IEntityLivingBase hitEntity; @@ -128,9 +138,9 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { private float knockback; private float knockbackUp; - public HitEvent(ICustomNpc npc, Ability ability, EntityLivingBase target, + public HitEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp) { - super(npc, ability, target); + super(entity, ability, target); this.hitEntity = hitEntity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(hitEntity) : null; this.damage = damage; this.knockback = knockback; @@ -178,16 +188,12 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired every tick while an ability is executing. - * Provides information about the current phase and tick. - */ public static class TickEvent extends AbilityEvent implements IAbilityEvent.TickEvent { private final int abilityPhase; private final int tick; - public TickEvent(ICustomNpc npc, Ability ability, EntityLivingBase target, int phase, int tick) { - super(npc, ability, target); + public TickEvent(EntityLivingBase entity, Ability ability, EntityLivingBase target, int phase, int tick) { + super(entity, ability, target); this.abilityPhase = phase; this.tick = tick; } @@ -208,17 +214,13 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired when a toggle ability changes state. - * Canceling prevents the toggle from changing state. - */ @Cancelable public static class ToggleEvent extends AbilityEvent implements IAbilityEvent.ToggleEvent { private final int oldState; private final int newState; - public ToggleEvent(ICustomNpc npc, Ability ability, int oldState, int newState) { - super(npc, ability, null); + public ToggleEvent(EntityLivingBase entity, Ability ability, int oldState, int newState) { + super(entity, ability, null); this.oldState = oldState; this.newState = newState; } @@ -244,17 +246,13 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { } } - /** - * Fired every 10 ticks for each active toggle ability. - * Scripts can set enabled to false to force-deactivate. - */ public static class ToggleUpdateEvent extends AbilityEvent implements IAbilityEvent.ToggleUpdateEvent { private final int tick; private final int state; private boolean enabled = true; - public ToggleUpdateEvent(ICustomNpc npc, Ability ability, int tick, int state) { - super(npc, ability, null); + public ToggleUpdateEvent(EntityLivingBase entity, Ability ability, int tick, int state) { + super(entity, ability, null); this.tick = tick; this.state = state; } @@ -281,7 +279,7 @@ public class AbilityEvent extends NpcEvent implements IAbilityEvent { @Override public String getHookName() { - return EnumScriptType.ABILITY_TOGGLE_UPDATE.function; + return EnumScriptType.ABILITY_TOGGLE_TICK.function; } } } diff --git a/src/main/java/noppes/npcs/scripted/event/ChainEvent.java b/src/main/java/noppes/npcs/scripted/event/ChainEvent.java new file mode 100644 index 000000000..2c0852e6c --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/ChainEvent.java @@ -0,0 +1,134 @@ +package noppes.npcs.scripted.event; + +import kamkeel.npcs.controllers.data.ability.data.ChainedAbility; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.IDamageSource; +import noppes.npcs.api.ability.IChainedAbility; +import noppes.npcs.api.entity.ICustomNpc; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.api.entity.IPlayer; +import noppes.npcs.api.event.IChainEvent; +import noppes.npcs.constants.EnumScriptType; +import noppes.npcs.scripted.NpcAPI; + +/** + * Unified chain events for both NPCs and Players. + */ +public class ChainEvent extends CustomNPCsEvent implements IChainEvent { + protected final IEntityLivingBase entity; + public final IPlayer player; + public final ICustomNpc npc; + protected final ChainedAbility chain; + protected final IEntityLivingBase target; + protected final int entryIndex; + + public ChainEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + this.entity = entity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(entity) : null; + this.chain = chain; + this.entryIndex = entryIndex; + this.target = target != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(target) : null; + this.player = (this.entity instanceof IPlayer) ? (IPlayer) this.entity : null; + this.npc = (this.entity instanceof ICustomNpc) ? (ICustomNpc) this.entity : null; + } + + @Override + public IEntityLivingBase getEntity() { + return entity; + } + + @Override + public IPlayer getPlayer() { + return player; + } + + @Override + public ICustomNpc getNpc() { + return npc; + } + + @Override + public boolean isNPC() { + return entity instanceof ICustomNpc; + } + + @Override + public IChainedAbility getChain() { + return chain; + } + + @Override + public IEntityLivingBase getTarget() { + return target; + } + + @Override + public int getEntryIndex() { + return entryIndex; + } + + @Override + public String getHookName() { + return "chainEvent"; + } + + public static class StartEvent extends ChainEvent implements IChainEvent.StartEvent { + public StartEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + super(entity, chain, entryIndex, target); + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_START.function; + } + } + + public static class NextEvent extends ChainEvent implements IChainEvent.NextEvent { + public NextEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + super(entity, chain, entryIndex, target); + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_NEXT.function; + } + } + + public static class CompleteEvent extends ChainEvent implements IChainEvent.CompleteEvent { + public CompleteEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target) { + super(entity, chain, entryIndex, target); + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_COMPLETE.function; + } + } + + public static class InterruptEvent extends ChainEvent implements IChainEvent.InterruptEvent { + private final IDamageSource damageSource; + private final float damage; + + public InterruptEvent(EntityLivingBase entity, ChainedAbility chain, int entryIndex, EntityLivingBase target, + DamageSource source, float damage) { + super(entity, chain, entryIndex, target); + this.damageSource = source != null ? NpcAPI.Instance().getIDamageSource(source) : null; + this.damage = damage; + } + + @Override + public IDamageSource getDamageSource() { + return damageSource; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public String getHookName() { + return EnumScriptType.CHAIN_INTERRUPT.function; + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java b/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java deleted file mode 100644 index 95bda90e6..000000000 --- a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java +++ /dev/null @@ -1,286 +0,0 @@ -package noppes.npcs.scripted.event.player; - -import cpw.mods.fml.common.eventhandler.Cancelable; -import kamkeel.npcs.controllers.data.ability.Ability; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.util.DamageSource; -import noppes.npcs.api.IDamageSource; -import noppes.npcs.api.ability.IAbility; -import noppes.npcs.api.entity.IEntityLivingBase; -import noppes.npcs.api.entity.IPlayer; -import noppes.npcs.api.event.IPlayerAbilityEvent; -import noppes.npcs.constants.EnumScriptType; -import noppes.npcs.scripted.NpcAPI; - -/** - * Events fired during player ability execution lifecycle. - */ -public class PlayerAbilityEvent extends PlayerEvent implements IPlayerAbilityEvent { - protected final Ability ability; - protected final IEntityLivingBase target; - private transient IAbility abilityCopy; - - public PlayerAbilityEvent(IPlayer player, Ability ability, EntityLivingBase target) { - super(player); - this.ability = ability; - this.target = target != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(target) : null; - } - - @Override - public IAbility getAbility() { - if (abilityCopy == null && ability != null) { - abilityCopy = ability.deepCopy(); - } - return abilityCopy; - } - - @Override - public IEntityLivingBase getTarget() { - return target; - } - - @Override - public String getHookName() { - return "playerAbilityEvent"; - } - - /** - * Fired when a player's ability starts executing (enters WINDUP phase). - */ - @Cancelable - public static class StartEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.StartEvent { - public StartEvent(IPlayer player, Ability ability, EntityLivingBase target) { - super(player, ability, target); - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_START.function; - } - } - - /** - * Fired when a player's ability enters the ACTIVE phase and performs its effect. - */ - @Cancelable - public static class ExecuteEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.ExecuteEvent { - public ExecuteEvent(IPlayer player, Ability ability, EntityLivingBase target) { - super(player, ability, target); - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_EXECUTE.function; - } - } - - /** - * Fired when a player's ability is interrupted by damage. - */ - public static class InterruptEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.InterruptEvent { - private final IDamageSource damageSource; - private final float damage; - - public InterruptEvent(IPlayer player, Ability ability, EntityLivingBase target, DamageSource source, float damage) { - super(player, ability, target); - this.damageSource = source != null ? NpcAPI.Instance().getIDamageSource(source) : null; - this.damage = damage; - } - - @Override - public IDamageSource getDamageSource() { - return damageSource; - } - - @Override - public float getDamage() { - return damage; - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_INTERRUPT.function; - } - } - - /** - * Fired when a player's ability completes its full execution cycle. - */ - public static class CompleteEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.CompleteEvent { - public CompleteEvent(IPlayer player, Ability ability, EntityLivingBase target) { - super(player, ability, target); - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_COMPLETE.function; - } - } - - /** - * Fired every tick while a player's ability is executing. - */ - public static class TickEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.TickEvent { - private final int abilityPhase; - private final int tick; - - public TickEvent(IPlayer player, Ability ability, EntityLivingBase target, int phase, int tick) { - super(player, ability, target); - this.abilityPhase = phase; - this.tick = tick; - } - - @Override - public int getAbilityPhase() { - return abilityPhase; - } - - @Override - public int getTick() { - return tick; - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_TICK.function; - } - } - - /** - * Fired when a player's ability hits an entity with damage. - * Canceling prevents the damage from being applied. - */ - @Cancelable - public static class HitEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.HitEvent { - private final IEntityLivingBase hitEntity; - private float damage; - private float knockback; - private float knockbackUp; - - public HitEvent(IPlayer player, Ability ability, EntityLivingBase target, - EntityLivingBase hitEntity, float damage, float knockback, float knockbackUp) { - super(player, ability, target); - this.hitEntity = hitEntity != null ? (IEntityLivingBase) NpcAPI.Instance().getIEntity(hitEntity) : null; - this.damage = damage; - this.knockback = knockback; - this.knockbackUp = knockbackUp; - } - - @Override - public IEntityLivingBase getHitEntity() { - return hitEntity; - } - - @Override - public float getDamage() { - return damage; - } - - @Override - public void setDamage(float damage) { - this.damage = damage; - } - - @Override - public float getKnockback() { - return knockback; - } - - @Override - public void setKnockback(float knockback) { - this.knockback = knockback; - } - - @Override - public float getKnockbackUp() { - return knockbackUp; - } - - @Override - public void setKnockbackUp(float knockbackUp) { - this.knockbackUp = knockbackUp; - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_HIT.function; - } - } - - /** - * Fired when a toggle ability changes state. - * Canceling prevents the toggle from changing state. - */ - @Cancelable - public static class ToggleEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.ToggleEvent { - private final int oldState; - private final int newState; - - public ToggleEvent(IPlayer player, Ability ability, int oldState, int newState) { - super(player, ability, null); - this.oldState = oldState; - this.newState = newState; - } - - @Override - public boolean isTogglingOn() { - return newState > 0; - } - - @Override - public int getOldState() { - return oldState; - } - - @Override - public int getNewState() { - return newState; - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_TOGGLE.function; - } - } - - /** - * Fired every 10 ticks for each active toggle ability. - * Scripts can set enabled to false to force-deactivate. - */ - public static class ToggleUpdateEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.ToggleUpdateEvent { - private final int tick; - private final int state; - private boolean enabled = true; - - public ToggleUpdateEvent(IPlayer player, Ability ability, int tick, int state) { - super(player, ability, null); - this.tick = tick; - this.state = state; - } - - @Override - public int getTick() { - return tick; - } - - @Override - public int getState() { - return state; - } - - @Override - public boolean isEnabled() { - return enabled; - } - - @Override - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - @Override - public String getHookName() { - return EnumScriptType.ABILITY_TOGGLE_UPDATE.function; - } - } -} diff --git a/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java b/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java index 4b9ead83e..05da1d779 100644 --- a/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java +++ b/src/main/java/noppes/npcs/scripted/gui/ScriptGuiTexturedRect.java @@ -11,6 +11,11 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur float scale; String texture; + // Animation + boolean animated = false; + int frameCount = 1; + int frametime = 2; + public ScriptGuiTexturedRect() { this.textureY = -1; this.scale = 1.0F; @@ -76,6 +81,25 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur return this; } + public boolean isAnimated() { + return this.animated && this.frameCount > 1; + } + + public int getFrameCount() { + return this.frameCount; + } + + public int getFrameTime() { + return this.frametime; + } + + public ITexturedRect setAnimation(int frameCount, int frametime) { + this.animated = frameCount > 1; + this.frameCount = Math.max(1, frameCount); + this.frametime = Math.max(1, frametime); + return this; + } + public int getType() { return 2; } @@ -89,6 +113,12 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur nbt.setIntArray("texPos", new int[]{this.textureX, this.textureY}); } + if (this.animated) { + nbt.setBoolean("animated", true); + nbt.setInteger("frameCount", this.frameCount); + nbt.setInteger("frameTime", this.frametime); + } + return nbt; } @@ -101,6 +131,13 @@ public class ScriptGuiTexturedRect extends ScriptGuiComponent implements ITextur this.setTextureOffset(nbt.getIntArray("texPos")[0], nbt.getIntArray("texPos")[1]); } + if (nbt.hasKey("animated") && nbt.getBoolean("animated")) { + this.setAnimation( + nbt.hasKey("frameCount") ? Math.max(1, nbt.getInteger("frameCount")) : 1, + nbt.hasKey("frameTime") ? Math.max(1, nbt.getInteger("frameTime")) : 2 + ); + } + return this; } } diff --git a/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java b/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java index 77e51df2c..a029b4ba4 100644 --- a/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java +++ b/src/main/java/noppes/npcs/scripted/item/ScriptCustomizableItem.java @@ -147,6 +147,33 @@ public abstract class ScriptCustomizableItem extends ScriptItemStack implements return this.itemDisplay.translateZ != null ? this.itemDisplay.translateZ : 0; } + public Boolean isTextureAnimated() { + return this.itemDisplay.animated != null ? this.itemDisplay.animated : false; + } + + public void setTextureAnimated(Boolean animated) { + this.itemDisplay.animated = animated; + saveItemData(); + } + + public Integer getFrameCount() { + return this.itemDisplay.frameCount != null ? this.itemDisplay.frameCount : 1; + } + + public void setFrameCount(Integer frameCount) { + this.itemDisplay.frameCount = frameCount != null ? Math.max(1, frameCount) : 1; + saveItemData(); + } + + public Integer getFrameTime() { + return this.itemDisplay.frametime != null ? this.itemDisplay.frametime : 2; + } + + public void setFrameTime(Integer frametime) { + this.itemDisplay.frametime = frametime != null ? Math.max(1, frametime) : 2; + saveItemData(); + } + public NBTTagCompound getMCNbt() { NBTTagCompound compound = super.getMCNbt(); compound.setTag("ItemData", this.getItemNBT(new NBTTagCompound())); diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java index d475c40ef..9fb509761 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java @@ -58,8 +58,8 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public void addAbilityReference(String key) { - // Validate ability exists and allows NPCs - Ability ability = AbilityController.Instance.resolveAbility(key); + // Validate ability exists and allows NPCs (peek avoids deep copy) + Ability ability = AbilityController.Instance.peekAbility(key); if (ability == null) { return; // Ability doesn't exist } @@ -145,6 +145,11 @@ public class ScriptDataAbilities implements IDataAbilities { data.interruptCurrentAbility(null, 0); } + @Override + public void completeCurrentAbility() { + data.completeCurrentAbility(); + } + @Override public int getGlobalCooldown() { return (int) data.getRemainingCooldown(); @@ -191,8 +196,8 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public boolean executeAbility(String key, Object target) { - // Validate ability exists and allows NPCs - Ability ability = AbilityController.Instance.resolveAbility(key); + // Validate ability exists and allows NPCs (peek avoids deep copy) + Ability ability = AbilityController.Instance.peekAbility(key); if (ability == null) { return false; // Ability doesn't exist } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java index 1860aa259..bb6b1b930 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java @@ -28,8 +28,8 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public void unlockAbility(String key) { - // Validate ability exists and allows players - Ability ability = AbilityController.Instance.resolveAbility(key); + // Validate ability exists and allows players (peek avoids deep copy) + Ability ability = AbilityController.Instance.peekAbility(key); if (ability == null) { return; // Ability doesn't exist } @@ -94,6 +94,11 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { data.interruptCurrentAbility(); } + @Override + public void completeCurrentAbility() { + data.completeCurrentAbility(); + } + @Override public boolean isOnCooldown() { return data.isOnCooldown(); @@ -162,7 +167,7 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { * Uses the same resolution as unlockAbility: registry key for built-in, UUID for custom. */ private String resolveCanonicalKey(String key) { - Ability ability = AbilityController.Instance.resolveAbility(key); + Ability ability = AbilityController.Instance.peekAbility(key); if (ability != null && ability.getId() != null) { return ability.getId(); } diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 9caf6027a..bdaa2abdc 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -182,6 +182,10 @@ gui.lineColor3=Lower line color gui.slotColour=Slots color gui.buttonAcceptColour=Accept button color gui.buttonRejectColour=Reject button color +gui.animated=Animated +gui.animated.hover=Textures with a .mcmeta file animate automatically.\nEnable this for manual animation of sprite sheet textures. +gui.frameCount=Frame Count +gui.frameTime=Frame Time questgui.doyouaccept=Do you accept the quest? questgui.bringitems=Bring items questgui.readdialog=Read dialog @@ -1678,6 +1682,8 @@ telegraph.ring=Ring telegraph.line=Line telegraph.cone=Cone telegraph.point=Point +telegraph.square=Square +telegraph.none=None ability.tab.timing=Timing ability.tab.effects=Effects @@ -1688,6 +1694,13 @@ ability.telegraphSizeNote=Size is based on ability parameters # Ability Effects Tab +ability.cnpc.custom=Custom +ability.telegraphShape=Telegraph Shape +ability.toggleEnabled=Toggle +ability.toggleStates=Toggle States +ability.hasActiveToggle=Active Toggle Tick +ability.section.toggle=Toggle +ability.section.execution=Execution ability.cnpc.slam=Slam ability.cnpc.heavy_hit=Heavy Hit ability.cnpc.cutter=Cutter @@ -1700,6 +1713,8 @@ ability.cnpc.teleport=Teleport ability.cnpc.vortex=Vortex ability.cnpc.shockwave=Shockwave ability.cnpc.guard=Guard +ability.cnpc.counter=Counter +ability.cnpc.dodge=Dodge ability.cnpc.effect=Effect ability.cnpc.hazard=Hazard ability.cnpc.trap=Trap @@ -1718,6 +1733,8 @@ ability.cooldownTicks=Cooldown ability.perAbilityCooldown=Per-Ability ability.freeOnCast=Free on Cast ability.hover.freeOnCast=Ability enters cooldown immediately after entities are spawned, allowing the caster to use other abilities while summoned entities remain active +ability.freeAim=Free Aim +ability.hover.freeAim=Players Only. Allows the player to steer the beam direction with their mouse during the active phase. Requires: Lock Movement set to Active or Both, Rotation Mode set to Free, Free on Cast disabled. ability.lockMovement=Lock Movement ability.rotationMode=Rotation ability.rotationPhase=Phase @@ -1748,6 +1765,9 @@ ability.windUpAnimation=Wind Up Animation ability.activeAnimation=Active Animation ability.dazedAnimation=Dazed Animation ability.counterAnimation=Counter Animation +ability.dodgeAnimation1=Dodge Animation 1 +ability.dodgeAnimation2=Dodge Animation 2 +ability.dodgeAnimation3=Dodge Animation 3 ability.showTelegraph=Show Telegraph ability.windUpColor=Wind Up Color ability.activeColor=Active Color @@ -1770,6 +1790,7 @@ ability.section.explosive=Explosive ability.section.colors=Colors ability.section.effects=Effects ability.section.burst=Burst +ability.section.dodgeAnimations=Dodge Animations ability.section.visual=Visual ability.section.projectile1=Projectile 1 ability.section.projectile2=Projectile 2 @@ -1900,9 +1921,9 @@ ability.maxTargets=Max Targets # Shockwave ability.pushStrength=Push Strength -# Guard +# Defend (Guard / Counter / Dodge) +ability.maxHitAmount=Max Hit Amount ability.damageReduction=Damage Reduction -ability.counterWindow=Counter Ticks # Effect ability.instantHeal=Instant @@ -1915,6 +1936,7 @@ ability.targetFilter.all=All ability.includeSelf=Include Self ability.section.targeting=Targeting ability.concurrent=Concurrent +ability.customScriptInfo=This ability is for scripting purposes ability.concurrentInfo=This ability allows Concurrency in Chains ability.hover.concurrent=When enabled, this ability fires at the same time as the ability above it in the chain ability.customEffects=Custom Effects @@ -1961,7 +1983,6 @@ ability.lightningRadius=Radius # Projectile Count / Settings ability.projectileCount=Count -ability.dualFireDelay=Fire Delay ability.fireDelay=Fire Delay ability.colorOverride=Color Override @@ -2046,6 +2067,8 @@ ability.hover.multiHitDelay=Ticks between repeat hits on the same entity when Hi ability.hover.maxHits=Maximum total hits before projectile ends in Pierce/Multi modes. Lower values reduce repeated hit spam and improve performance. ability.hover.explosive=Creates explosion on impact ability.hover.explosionRad=Size of explosion radius +ability.hover.maxHitAmount=Maximum hits absorbed before defend ability ends (0 = unlimited) +ability.hover.counterType=Flat: fixed damage counter-attack. Percent: counter-attack deals a percentage of the absorbed damage. ability.hover.piercing=Hits multiple targets instead of stopping on first hit ability.hover.lightning=Add electrical effect to visuals ability.hover.outerGlow=Enable outer glow layer around projectile @@ -2085,14 +2108,22 @@ ability.section.properties=Properties ability.section.panel=Panel ability.section.launch=Launch ability.section.slicer=Slicer +ability.section.icon=Icon +ability.hasIcon=Custom Icon +ability.icon.tint=Tint Color ability.domeRadius=Dome Radius ability.useHealth=Use Health ability.maxHealth=Max Health ability.useDuration=Use Duration +ability.duration=Duration ability.defaultMultiplier=Default Multiplier ability.innerAlpha=Inner Alpha ability.heightOffset=Height Offset +ability.section.offset=Offset +ability.offsetX=X Offset +ability.offsetY=Y Offset +ability.offsetZ=Z Offset ability.solid=Solid ability.knockbackEnabled=Knockback @@ -2109,6 +2140,8 @@ ability.hover.solid=Entities cannot pass through the barrier boundary ability.hover.knockbackEnabled=Repulsion field pushing entities away from barrier surface ability.hover.absorbing=Damage dealt to the caster is redirected to the barrier's health ability.hover.reflect=Rebounds non-breaking projectiles and reduces their damage by Strength +ability.targetOwner=Target Owner +ability.hover.targetOwner=Sets the reflected projectile's target to the original caster. With homing enabled, the projectile will home toward its former caster. ability.hover.meleeEnabled=Barrier can be hit and damaged by melee attacks @@ -2134,6 +2167,8 @@ ability.userType.NONE=NO ONE! ability.icon.section.uv=UV Coordinates ability.icon.x=Icon X ability.icon.y=Icon Y +ability.icon.layers=Layers +ability.icon.layer=Layer gui.both=Both gui.players=Players @@ -2192,6 +2227,9 @@ condition.hover.hitCount=Activates after receiving X hits within the time window condition.hover.hits=Number of hits required to trigger condition condition.hover.within=Time window in ticks (20 ticks = 1 second) condition.hover.threshold=Health percentage threshold (1-99%) +condition.hover.armor_slots=Equipment in specific armor slots +condition.hover.item_name=Filter by item name or identifier +condition.hover.required_count=Number of matching items required # Effect Hover Tooltips effect.hover.type=Potion effect type to apply to targets diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/beam.png b/src/main/resources/assets/customnpcs/textures/gui/ability/beam.png new file mode 100644 index 000000000..066b1b0b9 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/beam.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/charge.png b/src/main/resources/assets/customnpcs/textures/gui/ability/charge.png new file mode 100644 index 000000000..078114fd9 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/charge.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/cutter.png b/src/main/resources/assets/customnpcs/textures/gui/ability/cutter.png new file mode 100644 index 000000000..1d3cee95d Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/cutter.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/dash.png b/src/main/resources/assets/customnpcs/textures/gui/ability/dash.png new file mode 100644 index 000000000..79604af4a Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/dash.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/disc.png b/src/main/resources/assets/customnpcs/textures/gui/ability/disc.png new file mode 100644 index 000000000..0b5b984b8 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/disc.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/disc_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/disc_overlay.png new file mode 100644 index 000000000..34e291089 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/disc_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/dome.png b/src/main/resources/assets/customnpcs/textures/gui/ability/dome.png new file mode 100644 index 000000000..e13fad24e Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/dome.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/effect.png b/src/main/resources/assets/customnpcs/textures/gui/ability/effect.png new file mode 100644 index 000000000..9e1a6022f Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/effect.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/effect_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/effect_overlay.png new file mode 100644 index 000000000..84c0306ff Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/effect_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/guard.png b/src/main/resources/assets/customnpcs/textures/gui/ability/guard.png new file mode 100644 index 000000000..6b5630d4a Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/guard.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/hazard.png b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard.png new file mode 100644 index 000000000..b14e3d0b3 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/hazard_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard_overlay.png new file mode 100644 index 000000000..a0181aeac Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/hazard_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit.png b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit.png new file mode 100644 index 000000000..250deaee6 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit_overlay.png new file mode 100644 index 000000000..15881f843 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/heavy_hit_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot.png b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot.png new file mode 100644 index 000000000..b9e4e930f Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot_overlay.png new file mode 100644 index 000000000..33a83327e Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/laser_shot_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/orb.png b/src/main/resources/assets/customnpcs/textures/gui/ability/orb.png new file mode 100644 index 000000000..c6bf9991d Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/orb.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/orb_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/orb_overlay.png new file mode 100644 index 000000000..d92a7361f Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/orb_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/shield.png b/src/main/resources/assets/customnpcs/textures/gui/ability/shield.png new file mode 100644 index 000000000..b2e229db5 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/shield.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave.png b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave.png new file mode 100644 index 000000000..e7df66d5c Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave_overlay.png new file mode 100644 index 000000000..dae4f2441 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/shockwave_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/slam.png b/src/main/resources/assets/customnpcs/textures/gui/ability/slam.png new file mode 100644 index 000000000..bfa581fb4 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/slam.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper.png b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper.png new file mode 100644 index 000000000..f91317535 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper_overlay.png new file mode 100644 index 000000000..23048a1b8 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/sweeper_overlay.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/teleport.png b/src/main/resources/assets/customnpcs/textures/gui/ability/teleport.png new file mode 100644 index 000000000..8ffa07c71 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/teleport.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/trap.png b/src/main/resources/assets/customnpcs/textures/gui/ability/trap.png new file mode 100644 index 000000000..f6ef614c0 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/trap.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/vortex.png b/src/main/resources/assets/customnpcs/textures/gui/ability/vortex.png new file mode 100644 index 000000000..968fcaee5 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/vortex.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/wall.png b/src/main/resources/assets/customnpcs/textures/gui/ability/wall.png new file mode 100644 index 000000000..83de77ef0 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/wall.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/ability/wall_overlay.png b/src/main/resources/assets/customnpcs/textures/gui/ability/wall_overlay.png new file mode 100644 index 000000000..1a661b7cf Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/ability/wall_overlay.png differ