Merge branch 'KAMKEEL:dev' into dev

This commit is contained in:
Kirill Epifanov authored and GitHub committed 2026-02-09 22:55:44 +03:00
commit 9b52c8088e
224 files changed
+17351 -8292

No files matched your search

@@ -43,7 +43,16 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
GL11.glPushMatrix();
GL11.glScalef(scale, scale, scale);
// Apply ONLY Y-axis rotation for flat spin
if (disc.isVertical()) {
// Vertical mode: thin edge faces direction of travel (like a saw blade)
// 1. Spin in local space (Y-axis)
// 2. Tilt 90° to stand up (X-axis)
// 3. Orient to face travel direction (Y-axis world yaw)
GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f);
GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
}
// Apply Y-axis rotation for spin
GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
// Inner scale defines the core size
@@ -3,6 +3,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityLaser;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
@@ -20,11 +21,14 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilityLaser laser = (EntityAbilityLaser) entity;
// Don't render if length is 0
if (laser.getCurrentLength() <= 0) return;
setupRenderState();
if (laser.isCharging()) {
renderChargingOrb(laser, x, y, z, partialTicks);
restoreRenderState();
return;
}
// Get laser parameters
double startX = laser.getStartX();
double startY = laser.getStartY();
@@ -123,6 +127,55 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
restoreRenderState();
}
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks) {
float headSize = laser.getLaserWidth() * 1.5f;
float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
if (size <= 0.01f) return;
int innerColor = laser.getInnerColor();
int outerColor = laser.getOuterColor();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Pulsing effect
float pulseTime = laser.ticksExisted + partialTicks;
float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f;
float scale = size * (1.0f + scaleModifier);
// Render lightning during charging if enabled
if (laser.hasLightningEffect()) {
renderAttachedLightning(laser, scale);
}
GL11.glPushMatrix();
GL11.glScalef(scale, scale, scale);
// Inner scale defines the core size
float innerScale = 0.6f;
// Render outer glow only if enabled
if (laser.isOuterColorEnabled()) {
float outerScale = innerScale + laser.getOuterColorWidth();
float outerAlpha = laser.getOuterColorAlpha();
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
renderCube(outerColor, outerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glDepthMask(true);
}
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
}
/**
* Render lightning effects along the laser beam at multiple points.
*/
@@ -161,6 +214,22 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
GL11.glPopMatrix();
}
private void renderAttachedLightning(EntityAbilityLaser laser, float headScale) {
AttachedLightningRenderer.LightningState state = getLightningState(laser);
float density = laser.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * headScale * 0.5f;
float radius = innerRadius + laser.getLightningRadius() * headScale;
int outerColor = laser.getOuterColor();
int innerColor = laser.getInnerColor();
int fadeTime = laser.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the main lightning state for the laser.
*/
@@ -56,7 +56,7 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
renderCube(orb.getOuterColor(), 0.5f, 0.5f);
renderCube(orb.getOuterColor(), orb.getOuterColorAlpha(), 0.5f);
GL11.glPopMatrix();
GL11.glDepthMask(true);
}
@@ -31,6 +31,7 @@ public abstract class RenderAbilityProjectile extends Render {
*/
protected void setupRenderState() {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_ALPHA_TEST);
@@ -48,9 +49,7 @@ public abstract class RenderAbilityProjectile extends Render {
* Restore GL state after rendering.
*/
protected void restoreRenderState() {
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
@@ -88,17 +88,14 @@ public class AttachedLightningRenderer {
/**
* Render all active arcs in local space.
* Call this after glTranslated to entity position.
* Note: Expects the caller to have already set up GL state (disabled textures,
* disabled lighting, disabled culling, enabled blending). This avoids nesting
* glPushAttrib calls which can overflow the GL attrib stack (depth 16) when
* other mods also push attribs during entity rendering.
*/
public void render() {
if (arcs.isEmpty()) return;
// Setup GL state
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDepthMask(false);
Tessellator tess = Tessellator.instance;
@@ -114,7 +111,6 @@ public class AttachedLightningRenderer {
}
GL11.glDepthMask(true);
GL11.glPopAttrib();
}
public int getArcCount() {
@@ -239,6 +235,8 @@ public class AttachedLightningRenderer {
/**
* Render a single instant lightning arc (no fading, drawn this frame only).
* Expects the caller to have already set up GL state (disabled textures,
* disabled lighting, disabled culling, enabled blending).
*/
public static void renderInstantArc(float radius, int outerColor, int innerColor) {
double theta = rand.nextDouble() * Math.PI * 2;
@@ -254,12 +252,6 @@ public class AttachedLightningRenderer {
List<double[]> points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement);
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDepthMask(false);
Tessellator tess = Tessellator.instance;
@@ -267,7 +259,6 @@ public class AttachedLightningRenderer {
renderBoltPath(tess, points, innerColor, 0.012f, 0.7f);
GL11.glDepthMask(true);
GL11.glPopAttrib();
}
/**
@@ -2,7 +2,12 @@ package kamkeel.npcs.command;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.UserType;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
import java.util.Collections;
@@ -122,5 +127,192 @@ public class AbilityCommand extends CommandKamkeelBase {
}
sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange());
sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No"));
sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name());
}
@SubCommand(
desc = "List all built-in abilities available for players"
)
public void prebuilts(ICommandSender sender, String[] args) {
Set<String> names = AbilityController.Instance.getAbilityNames();
if (names.isEmpty()) {
sendResult(sender, "No built-in abilities found.");
return;
}
List<String> playerAbilities = new ArrayList<>();
for (String name : names) {
Ability ability = AbilityController.Instance.getAbility(name);
if (ability != null && ability.getAllowedBy().allowsPlayer()) {
playerAbilities.add(name);
}
}
if (playerAbilities.isEmpty()) {
sendResult(sender, "No player-usable built-in abilities found.");
return;
}
Collections.sort(playerAbilities);
sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):");
for (String name : playerAbilities) {
Ability ability = AbilityController.Instance.getAbility(name);
String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]";
sendResult(sender, " - \u00A7b" + name + " " + userType);
}
}
@SubCommand(
desc = "Unlock an ability for a player",
usage = "<player> <ability>"
)
public void unlock(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability unlock <player> <ability>");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
// Resolve ability
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
return;
}
// Use the ability's canonical ID for storage (registry key for built-in, UUID for custom)
String canonicalKey = ability.getId();
if (canonicalKey == null || canonicalKey.isEmpty()) {
canonicalKey = abilityKey; // Fallback to user-provided key
}
String displayName = ability.getName() != null ? ability.getName() : canonicalKey;
// Check if ability allows players
if (!ability.getAllowedBy().allowsPlayer()) {
sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players.");
return;
}
// Get player data and unlock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player already has ability: " + displayName);
return;
}
data.abilityData.unlockAbility(canonicalKey);
sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName);
}
@SubCommand(
desc = "Lock (revoke) an ability from a player",
usage = "<player> <ability>"
)
public void lock(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability lock <player> <ability>");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
// Resolve ability to get canonical key
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
String canonicalKey = abilityKey;
String displayName = abilityKey;
if (ability != null) {
canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
displayName = ability.getName() != null ? ability.getName() : canonicalKey;
}
// Get player data and lock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player doesn't have ability: " + displayName);
return;
}
data.abilityData.lockAbility(canonicalKey);
sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
}
@SubCommand(
desc = "List abilities unlocked for a player",
usage = "<player>"
)
public void player(ICommandSender sender, String[] args) {
if (args.length < 1) {
sendError(sender, "Usage: /kam ability player <player>");
return;
}
String playerName = args[0];
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
String[] abilityKeys = data.abilityData.getUnlockedAbilities();
if (abilityKeys.length == 0) {
sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities.");
return;
}
sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):");
int selected = data.abilityData.getSelectedIndex();
for (int i = 0; i < abilityKeys.length; i++) {
String key = abilityKeys[i];
Ability ability = AbilityController.Instance.resolveAbility(key);
String displayName = ability != null && ability.getName() != null ? ability.getName() : key;
String prefix = (i == selected) ? "\u00A7e> " : " ";
// Show display name and key if different
if (!displayName.equals(key)) {
sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
} else {
sendResult(sender, prefix + "\u00A7b" + displayName);
}
}
}
private String joinArgs(String[] args, int startIndex) {
StringBuilder sb = new StringBuilder();
for (int i = startIndex; i < args.length; i++) {
if (i > startIndex) sb.append(" ");
sb.append(args[i]);
}
return sb.toString();
}
/**
* Get list of player-usable ability keys (for tab completion).
* Uses registry keys for built-in abilities (no spaces) and UUIDs for custom.
* Used by CommandKamkeel for <ability> usage token.
*/
public static List<String> getPlayerAbilityNames() {
List<String> keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys());
Collections.sort(keys);
return keys;
}
}
@@ -13,6 +13,7 @@ import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import noppes.npcs.controllers.ServerCloneController;
import noppes.npcs.controllers.data.CloneFolder;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.List;
@@ -35,20 +36,24 @@ public class CloneCommand extends CommandKamkeelBase {
@SubCommand(
desc = "Add NPC(s) to clone storage",
usage = "<npc> <tab> [clonedname]",
usage = "<npc> <tab|folder> [clonedname]",
permission = 4
)
public void add(ICommandSender sender, String[] args) {
int tab = 0;
int tab = -1;
String folder = null;
try {
tab = Integer.parseInt(args[1]);
if (tab < 0 || tab > 15) {
if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
sendError(sender, String.format("Tab is not a number: %s", args[1]));
return;
folder = args[1];
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
sendError(sender, String.format("Unknown folder: %s", folder));
return;
}
}
int x = sender.getPlayerCoordinates().posX;
@@ -64,32 +69,47 @@ public class CloneCommand extends CommandKamkeelBase {
NBTTagCompound compound = new NBTTagCompound();
if (!npc.writeToNBTOptional(compound))
return;
ServerCloneController.Instance.addClone(compound, name, tab);
sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab));
if (folder != null) {
ServerCloneController.Instance.addClone(compound, name, folder);
sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Folder \u00A7b%s\u00A77", name, folder));
} else {
ServerCloneController.Instance.addClone(compound, name, tab);
sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab));
}
}
}
}
@SubCommand(
desc = "List NPC from clone storage",
usage = "<tab>",
usage = "<tab|folder>",
permission = 2
)
public void list(ICommandSender sender, String[] args) {
sendMessage(sender, "--- Stored NPCs --- (server side)");
int tab = 0;
int tab = -1;
String folder = null;
try {
tab = Integer.parseInt(args[1]);
if (tab < 0 || tab > 15) {
if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
sendError(sender, String.format("Tab is not a number: %s", args[1]));
return;
folder = args[1];
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
sendError(sender, String.format("Unknown folder: %s", folder));
return;
}
}
for (String name : ServerCloneController.Instance.getClones(tab)) {
List<String> clones;
if (folder != null) {
clones = ServerCloneController.Instance.getClones(folder);
} else {
clones = ServerCloneController.Instance.getClones(tab);
}
for (String name : clones) {
sendMessage(sender, name);
}
sendMessage(sender, "------------------------------------");
@@ -97,59 +117,75 @@ public class CloneCommand extends CommandKamkeelBase {
@SubCommand(
desc = "Remove NPC from clone storage",
usage = "<name> <tab>",
usage = "<name> <tab|folder>",
permission = 4
)
public void del(ICommandSender sender, String[] args) throws CommandException {
String nametodel = args[0];
int tab = 0;
int tab = -1;
String folder = null;
try {
tab = Integer.parseInt(args[1]);
if (tab < 0 || tab > 15) {
sendError(sender, String.format("Tab must be within 1-15"));
if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
sendError(sender, String.format("Tab is not a number: %s", args[1]));
return;
}
boolean deleted = false;
for (String name : ServerCloneController.Instance.getClones(tab)) {
if (nametodel.equalsIgnoreCase(name)) {
ServerCloneController.Instance.removeClone(name, tab);
deleted = true;
break;
folder = args[1];
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
sendError(sender, String.format("Unknown folder: %s", folder));
return;
}
}
if (!ServerCloneController.Instance.removeClone(nametodel, tab)) {
boolean success;
if (folder != null) {
success = ServerCloneController.Instance.removeClone(nametodel, folder);
} else {
success = ServerCloneController.Instance.removeClone(nametodel, tab);
}
if (!success) {
sendError(sender, String.format("NPC '%s' was not found", nametodel));
} else {
sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab));
if (folder != null) {
sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Folder \u00A7b%s\u00A77", nametodel, folder));
} else {
sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab));
}
}
}
@SubCommand(
desc = "Spawn cloned NPC",
usage = "<name> <tab> [[world:]x,y,z]] [newname]",
usage = "<name> <tab|folder> [[world:]x,y,z]] [newname]",
permission = 2
)
public void spawn(ICommandSender sender, String[] args) throws CommandException {
String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space
int tab = 0;
int tab = -1;
String folder = null;
try {
tab = Integer.parseInt(args[1]);
if (tab < 0 || tab > 15) {
sendError(sender, String.format("Tab must be within 1-15"));
if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
sendError(sender, String.format("Tab is not a number: %s", args[1]));
return;
folder = args[1];
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
sendError(sender, String.format("Unknown folder: %s", folder));
return;
}
}
String newname = null;
NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
NBTTagCompound compound;
if (folder != null) {
compound = ServerCloneController.Instance.getCloneData(sender, name, folder);
} else {
compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
}
if (compound == null) {
sendError(sender, "Unknown npc");
return;
@@ -211,22 +247,26 @@ public class CloneCommand extends CommandKamkeelBase {
}
@SubCommand(
desc = "Spawn cloned NPC",
usage = "<name> <tab> [[world:]x,y,z]] [newname]",
desc = "Spawn cloned NPC in a grid",
usage = "<name> <tab|folder> <width> <height> [[world:]x,y,z]] [newname]",
permission = 2
)
public void grid(ICommandSender sender, String[] args) throws CommandException {
String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space
int tab = 0;
int tab = -1;
String folder = null;
try {
tab = Integer.parseInt(args[1]);
if (tab < 0 || tab > 15) {
sendError(sender, String.format("Tab must be within 1-15"));
if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
sendError(sender, String.format("Tab is not a number: %s", args[1]));
return;
folder = args[1];
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
sendError(sender, String.format("Unknown folder: %s", folder));
return;
}
}
int width, height;
@@ -238,9 +278,13 @@ public class CloneCommand extends CommandKamkeelBase {
return;
}
String newname = null;
NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
NBTTagCompound compound;
if (folder != null) {
compound = ServerCloneController.Instance.getCloneData(sender, name, folder);
} else {
compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
}
if (compound == null) {
sendError(sender, "Unknown npc");
return;
@@ -317,6 +361,163 @@ public class CloneCommand extends CommandKamkeelBase {
return;
}
@SubCommand(
desc = "List all custom clone folders",
usage = "",
permission = 2
)
public void listfolders(ICommandSender sender, String[] args) {
if (ServerCloneController.Instance == null) {
sendError(sender, "Folder system not initialized");
return;
}
sendMessage(sender, "--- Clone Folders ---");
for (CloneFolder f : ServerCloneController.Instance.getFolderList()) {
sendMessage(sender, f.name);
}
sendMessage(sender, "------------------------------------");
}
@SubCommand(
desc = "Create a custom clone folder",
usage = "<name>",
permission = 4
)
public void createfolder(ICommandSender sender, String[] args) {
if (ServerCloneController.Instance == null) {
sendError(sender, "Folder system not initialized");
return;
}
String name = args[0];
if (!CloneFolder.isValidName(name)) {
sendError(sender, String.format("Invalid folder name: %s", name));
return;
}
if (ServerCloneController.Instance.hasFolder(name)) {
sendError(sender, String.format("Folder '%s' already exists", name));
return;
}
CloneFolder created = ServerCloneController.Instance.createFolder(name);
if (created != null) {
sendResult(sender, String.format("Created folder \u00A7b%s", name));
} else {
sendError(sender, String.format("Failed to create folder '%s'", name));
}
}
@SubCommand(
desc = "Rename a custom clone folder",
usage = "<oldname> <newname>",
permission = 4
)
public void renamefolder(ICommandSender sender, String[] args) {
if (ServerCloneController.Instance == null) {
sendError(sender, "Folder system not initialized");
return;
}
String oldName = args[0];
String newName = args[1];
if (!ServerCloneController.Instance.hasFolder(oldName)) {
sendError(sender, String.format("Unknown folder: %s", oldName));
return;
}
if (!CloneFolder.isValidName(newName)) {
sendError(sender, String.format("Invalid folder name: %s", newName));
return;
}
if (ServerCloneController.Instance.renameFolder(oldName, newName)) {
sendResult(sender, String.format("Renamed folder \u00A7b%s\u00A77 to \u00A7b%s", oldName, newName));
} else {
sendError(sender, String.format("Failed to rename folder '%s'", oldName));
}
}
@SubCommand(
desc = "Delete an empty custom clone folder",
usage = "<name>",
permission = 4
)
public void deletefolder(ICommandSender sender, String[] args) {
if (ServerCloneController.Instance == null) {
sendError(sender, "Folder system not initialized");
return;
}
String name = args[0];
if (!ServerCloneController.Instance.hasFolder(name)) {
sendError(sender, String.format("Unknown folder: %s", name));
return;
}
if (ServerCloneController.Instance.deleteFolder(name)) {
sendResult(sender, String.format("Deleted folder \u00A7b%s", name));
} else {
sendError(sender, String.format("Failed to delete folder '%s' (folder must be empty)", name));
}
}
@SubCommand(
desc = "Move a clone between tabs/folders",
usage = "<clonename> <from_tab|folder> <to_tab|folder>",
permission = 4
)
public void move(ICommandSender sender, String[] args) {
if (ServerCloneController.Instance == null) {
sendError(sender, "Folder system not initialized");
return;
}
String cloneName = args[0];
int fromTab = -1;
String fromFolder = null;
try {
fromTab = Integer.parseInt(args[1]);
if (fromTab < 1 || fromTab > 15) {
sendError(sender, "Source tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
fromFolder = args[1];
if (!ServerCloneController.Instance.hasFolder(fromFolder)) {
sendError(sender, String.format("Unknown source folder: %s", fromFolder));
return;
}
}
int toTab = -1;
String toFolder = null;
try {
toTab = Integer.parseInt(args[2]);
if (toTab < 1 || toTab > 15) {
sendError(sender, "Destination tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
toFolder = args[2];
if (!ServerCloneController.Instance.hasFolder(toFolder)) {
sendError(sender, String.format("Unknown destination folder: %s", toFolder));
return;
}
}
boolean success;
if (fromFolder != null && toFolder != null) {
success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder);
} else if (fromFolder != null) {
success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab);
} else if (toFolder != null) {
success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder);
} else {
success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab);
}
if (success) {
String from = fromFolder != null ? fromFolder : String.valueOf(fromTab);
String to = toFolder != null ? toFolder : String.valueOf(toTab);
sendResult(sender, String.format("Moved \u00A7e%s\u00A77 from \u00A7b%s\u00A77 to \u00A7b%s", cloneName, from, to));
} else {
sendError(sender, String.format("Failed to move '%s'", cloneName));
}
}
public World getWorld(String t) {
WorldServer[] ws = MinecraftServer.getServer().worldServers;
for (WorldServer w : ws) {
@@ -20,6 +20,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames;
import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames;
public class CommandKamkeel extends CommandBase {
@@ -135,6 +136,9 @@ public class CommandKamkeel extends CommandBase {
} else if (usage.equals("<effectName>")) {
List<String> keys = getSortedEffectNames();
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<ability>")) {
List<String> keys = getPlayerAbilityNames();
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
}
}
}
@@ -20,6 +20,7 @@ import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.controllers.data.Frame;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.controllers.ScriptController;
@@ -28,7 +29,10 @@ import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.AbilityEvent;
import noppes.npcs.scripted.event.player.PlayerAbilityEvent;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.Entity;
@@ -56,6 +60,7 @@ public abstract class Ability implements IAbility {
// Timing (ticks)
protected int cooldownTicks = 0; // Added to global cooldown after ability completes
protected int windUpTicks = 20;
protected boolean syncWindupWithAnimation = true;
protected int dazedTicks = 80; // Only used when interrupted during WINDUP (if interruptible)
// Interruption
@@ -63,6 +68,8 @@ public abstract class Ability implements IAbility {
// Feedback
protected LockMovementType lockMovement = LockMovementType.WINDUP;
protected RotationMode rotationMode = RotationMode.FREE;
protected LockMovementType rotationPhase = LockMovementType.WINDUP_AND_ACTIVE;
protected int windUpColor = 0x80FF4400; // Telegraph color during wind up
protected int activeColor = 0xC0FF0000; // Telegraph warning/active color
@@ -95,6 +102,13 @@ public abstract class Ability implements IAbility {
// Configurable potion effects
protected List<AbilityEffect> effects = new ArrayList<>();
// Burst
protected boolean burstEnabled = false;
protected int burstAmount = 0; // number of EXTRA repetitions
protected int burstDelay = 0; // ticks between bursts
protected boolean burstReplayAnimations = true;
protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts
// ═══════════════════════════════════════════════════════════════════
// EXECUTION STATE (not saved, reset each combat)
// ═══════════════════════════════════════════════════════════════════
@@ -105,6 +119,17 @@ public abstract class Ability implements IAbility {
protected transient long executionStartTime;
protected transient TelegraphInstance telegraphInstance;
// Burst execution state
protected transient int burstIndex = 0;
protected transient List<Entity> burstEntities = new ArrayList<>();
// ═══════════════════════════════════════════════════════════════════
// PREVIEW STATE (client-side only, not saved)
// ═══════════════════════════════════════════════════════════════════
protected transient boolean previewMode = false;
protected transient PreviewEntityHandler previewEntityHandler;
// ═══════════════════════════════════════════════════════════════════
// ABSTRACT METHODS
// ═══════════════════════════════════════════════════════════════════
@@ -133,6 +158,60 @@ public abstract class Ability implements IAbility {
// OPTIONAL OVERRIDES
// ═══════════════════════════════════════════════════════════════════
/**
* Returns true if this ability type deals damage.
* Override in non-damaging subclasses to return false.
* Used by external mods to determine whether to show
* damage-related configuration (e.g., DBC stats tab).
*/
public boolean hasDamage() {
return true;
}
/**
* Override to provide variant templates for this ability type.
* When a user creates this ability type, they will be shown a selection dialog
* with the returned variants. If empty or single-entry, the dialog is skipped.
*/
public List<AbilityVariant> getVariants() {
return Collections.emptyList();
}
/**
* Whether this ability type supports the burst system.
* Override to return false for abilities that shouldn't repeat (Guard, Heal, Sweeper, etc.).
*/
public boolean allowBurst() {
return true;
}
/**
* Whether this ability supports overlap mode for burst (entities from previous bursts keep flying).
* Override to return true for entity-spawning projectile abilities (Orb, Beam, Disc, LaserShot).
*/
public boolean allowOverlap() {
return false;
}
/**
* Whether this ability is ready for auto-completion during burst overlap mode.
* Override to delay auto-completion until all staggered projectiles have been fired.
* @param activeTick the current tick within the ACTIVE phase
*/
public boolean isReadyForBurstCompletion(int activeTick) {
return true;
}
/**
* Called when burst re-fires without replay animations (burstReplayAnimations=false).
* Entity-spawning abilities should override to spawn and fire entities in one step,
* since onWindUpTick was not called (windup was skipped).
* Default: does nothing (ability goes directly to onExecute with existing state).
*/
public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) {
// Override in entity-spawning abilities (Orb, Beam, Disc, LaserShot)
}
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
}
@@ -142,6 +221,9 @@ public abstract class Ability implements IAbility {
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
}
public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) {
}
/**
* Apply damage to an entity with ability hit event support.
* Fires the abilityHit script event, allowing scripts to modify or cancel the damage.
@@ -239,12 +321,22 @@ public abstract class Ability implements IAbility {
// Apply damage
if (damage > 0) {
if (caster instanceof EntityNPCInterface) {
hitEntity.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), damage);
} else if (caster instanceof EntityPlayer) {
hitEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) caster), damage);
} else {
hitEntity.attackEntityFrom(DamageSource.causeMobDamage(caster), damage);
// Check for external damage handler first (e.g., DBC Addon)
IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler();
boolean handled = false;
if (handler != null) {
handled = handler.handleDamage(this, caster, hitEntity, damage, knockback, knockbackUp,
knockbackDirX, knockbackDirZ);
}
if (!handled) {
// Default damage path
if (caster instanceof EntityNPCInterface) {
hitEntity.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), damage);
} else if (caster instanceof EntityPlayer) {
hitEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) caster), damage);
} else {
hitEntity.attackEntityFrom(DamageSource.causeMobDamage(caster), damage);
}
}
}
@@ -300,6 +392,18 @@ public abstract class Ability implements IAbility {
return 45.0f;
}
/**
* Returns true if the caster is a player (not an NPC).
* Use this instead of checking {@code target != null} to make NPC/Player
* code paths explicit and readable.
* <p>
* NPCs always have an aggro target passed to ability methods.
* Players never do — they use look direction for aiming instead.
*/
protected final boolean isPlayerCaster(EntityLivingBase caster) {
return caster instanceof EntityPlayer;
}
/**
* Returns true if this ability controls NPC movement during ACTIVE phase.
* When true, AI pathfinding will be blocked during ability execution.
@@ -335,19 +439,178 @@ public abstract class Ability implements IAbility {
}
/**
* Returns true if this ability type has custom settings that need a Type-specific tab.
* Override to return true if the ability has settings beyond the base Ability fields.
* Add field definitions for this ability's GUI.
* Override in subclasses to add type-specific fields. The list already contains
* the base fields (General, Target, Effects tabs), so subclasses can also
* modify, insert into, or remove base fields using {@link FieldDef#insertBefore},
* {@link FieldDef#insertAfter}, or direct list manipulation.
* <p>
* Fields added here without an explicit {@code .tab()} will default to the "Type" tab.
*
* @param defs The mutable list of field definitions to add to or modify
*/
public boolean hasTypeSettings() {
return false;
@SideOnly(Side.CLIENT)
public void getAbilityDefinitions(List<FieldDef> defs) {
}
/**
* Get the number of rows needed for type-specific settings in the GUI.
* Each row is approximately 24 pixels. Used for GUI layout.
* Builds and returns all field definitions for this ability's GUI.
* Base fields (General, Target, Effects) are added first, then
* {@link #getAbilityDefinitions(List)} is called so subclasses can add
* type-specific fields and modify any existing fields.
*/
public int getTypeSettingsRowCount() {
return 0;
@SideOnly(Side.CLIENT)
public final List<FieldDef> getAllDefinitions() {
List<FieldDef> defs = new ArrayList<>();
// ── General tab ──────────────────────────────────────────────
defs.add(FieldDef.stringField("gui.name", this::getName, this::setName)
.tab("General"));
defs.add(FieldDef.row(
FieldDef.intField("ability.weight", this::getWeight, this::setWeight).range(1, 1000),
FieldDef.boolField("gui.enabled", this::isEnabled, this::setEnabled)
).tab("General"));
defs.add(FieldDef.section("ability.section.timing").tab("General"));
defs.add(FieldDef.intField("ability.windUpTicks", this::getRawWindUpTicks, this::setWindUpTicks)
.tab("General").range(0, 1000)
.visibleWhen(() -> !hasWindUpAnimation()));
defs.add(FieldDef.row(
FieldDef.intField("ability.windUpTicks", this::getRawWindUpTicks, this::setWindUpTicks).range(0, 1000),
FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation)
.hover("ability.hover.sync")
).tab("General").visibleWhen(() -> hasWindUpAnimation() && !isSyncWindupWithAnimation()));
defs.add(FieldDef.row(
FieldDef.labelField("ability.windUpTicks", () -> getWindUpTicks() + "t"),
FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation)
.hover("ability.hover.sync")
).tab("General").visibleWhen(() -> hasWindUpAnimation() && isSyncWindupWithAnimation()));
defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks)
.tab("General").range(0, 10000));
defs.add(FieldDef.section("ability.section.movement").tab("General"));
defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(),
() -> this.getLockMovement().getDisplayKey(),
v -> {
for (LockMovementType t : LockMovementType.values()) {
if (t.getDisplayKey().equals(v)) { this.setLockMovement(t); break; }
}
})
.hover("ability.hover.lockMovement")
.tab("General"));
defs.add(FieldDef.row(
FieldDef.stringEnumField("ability.rotationMode", RotationMode.getDisplayKeys(),
() -> this.getRotationMode().getDisplayKey(),
v -> {
for (RotationMode m : RotationMode.values()) {
if (m.getDisplayKey().equals(v)) { this.setRotationMode(m); break; }
}
})
.hover("ability.hover.rotationMode"),
FieldDef.stringEnumField("ability.rotationPhase", getRotationPhaseKeys(),
() -> this.getRotationPhase().getDisplayKey(),
v -> {
for (LockMovementType t : LockMovementType.values()) {
if (t.getDisplayKey().equals(v)) { this.setRotationPhase(t); break; }
}
})
.hover("ability.hover.rotationPhase")
.visibleWhen(() -> this.rotationMode != RotationMode.FREE)
).tab("General"));
defs.add(FieldDef.row(
FieldDef.boolField("ability.interruptible", this::isInterruptible, this::setInterruptible)
.hover("ability.hover.interruptible"),
FieldDef.intField("ability.dazedTicks", this::getDazedTicks, this::setDazedTicks)
.range(0, 1000).visibleWhen(this::isInterruptible)
).tab("General"));
// ── Burst section ────────────────────────────────────────────
if (allowBurst()) {
defs.add(FieldDef.section("ability.section.burst").tab("General"));
defs.add(FieldDef.boolField("ability.burstEnabled", this::isBurstEnabled, this::setBurstEnabled)
.tab("General"));
defs.add(FieldDef.row(
FieldDef.intField("ability.burstAmount", this::getBurstAmount, this::setBurstAmount).range(1, 100),
FieldDef.intField("ability.burstDelay", this::getBurstDelay, this::setBurstDelay).range(0, 1000)
).tab("General").visibleWhen(this::isBurstEnabled));
defs.add(FieldDef.boolField("ability.burstReplayAnimations", this::isBurstReplayAnimations, this::setBurstReplayAnimations)
.tab("General").visibleWhen(this::isBurstEnabled)
.hover("ability.hover.burstReplay"));
if (allowOverlap()) {
defs.add(FieldDef.boolField("ability.burstOverlap", this::isBurstOverlap, this::setBurstOverlap)
.tab("General").visibleWhen(this::isBurstEnabled)
.hover("ability.hover.burstOverlap"));
}
}
// ── Target tab ───────────────────────────────────────────────
defs.add(FieldDef.row(
FieldDef.intField("ability.minRange", () -> (int) getMinRange(), v -> setMinRange(v)).range(0, 100),
FieldDef.intField("ability.maxRange", () -> (int) getMaxRange(), v -> setMaxRange(v)).range(1, 100)
).tab("Target"));
if (!isTargetingModeLocked()) {
TargetingMode[] allowed = getAllowedTargetingModes();
if (allowed != null && allowed.length > 0) {
String[] allowedKeys = new String[allowed.length];
for (int i = 0; i < allowed.length; i++) {
allowedKeys[i] = allowed[i].name();
}
defs.add(FieldDef.stringEnumField("ability.targetingMode", allowedKeys,
() -> this.getTargetingMode().name(),
v -> {
try { this.setTargetingMode(TargetingMode.valueOf(v)); }
catch (Exception ignored) {}
})
.tab("Target").hover("ability.hover.targeting"));
} else {
defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class,
this::getTargetingMode, this::setTargetingMode)
.tab("Target").hover("ability.hover.targeting"));
}
}
// ── Effects tab ──────────────────────────────────────────────
defs.add(FieldDef.section("ability.section.sounds").tab("Effects"));
defs.add(FieldDef.soundSubGui("ability.windUpSound", this::getWindUpSound, this::setWindUpSound)
.tab("Effects"));
defs.add(FieldDef.soundSubGui("ability.activeSound", this::getActiveSound, this::setActiveSound)
.tab("Effects"));
defs.add(FieldDef.section("ability.section.animations").tab("Effects"));
defs.add(FieldDef.animSubGui("ability.windUpAnimation",
this::getWindUpAnimationId, this::setWindUpAnimationId,
this::getWindUpAnimationName, this::setWindUpAnimationName)
.tab("Effects"));
defs.add(FieldDef.animSubGui("ability.activeAnimation",
this::getActiveAnimationId, this::setActiveAnimationId,
this::getActiveAnimationName, this::setActiveAnimationName)
.tab("Effects"));
TelegraphType tType = getTelegraphType();
if (tType != null && tType != TelegraphType.NONE) {
defs.add(FieldDef.section("ability.section.telegraph").tab("Effects")
.hover("telegraph." + tType.name().toLowerCase()));
defs.add(FieldDef.boolField("ability.showTelegraph", this::isShowTelegraph, this::setShowTelegraph)
.tab("Effects").hover("ability.hover.showTelegraph"));
defs.add(FieldDef.colorSubGui("ability.windUpColor", this::getWindUpColor, this::setWindUpColor)
.tab("Effects").visibleWhen(this::isShowTelegraph));
defs.add(FieldDef.colorSubGui("ability.activeColor", this::getActiveColor, this::setActiveColor)
.tab("Effects").visibleWhen(this::isShowTelegraph));
}
// ── Type-specific fields ─────────────────────────────────────
int baseSize = defs.size();
getAbilityDefinitions(defs);
// Default tab for ability-added fields that don't specify one
for (int i = baseSize; i < defs.size(); i++) {
if (defs.get(i).getTab() == null) {
defs.get(i).tab("Type");
}
}
// External field providers (e.g., DBC Addon injecting a "DBC" tab)
for (IAbilityFieldProvider provider : AbilityController.Instance.getFieldProviders()) {
provider.addFieldDefinitions(this, defs);
}
return defs;
}
/**
@@ -438,8 +701,12 @@ public abstract class Ability implements IAbility {
instance.setEntityIdToFollow(caster.getEntityId());
// For LINE/CONE telegraphs: track target direction during windup
// Only track if rotation is NOT locked during windup (NPC can still turn)
if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) {
instance.setTargetEntityId(target.getEntityId());
if (!isRotationLockedDuringWindup()) {
instance.setTargetEntityId(target.getEntityId());
}
// If rotation is locked, yaw stays fixed at creation time
}
} else if (target != null) {
// AOE_TARGET abilities: telegraph follows target during windup
@@ -535,13 +802,21 @@ public abstract class Ability implements IAbility {
// ═══════════════════════════════════════════════════════════════════
/**
* Start executing this ability
* Start executing this ability.
* If windUpTicks is 0, skips WINDUP and goes directly to ACTIVE.
*/
public void start(EntityLivingBase target) {
this.phase = AbilityPhase.WINDUP;
this.currentTick = 0;
this.currentTarget = target;
this.executionStartTime = System.currentTimeMillis();
this.burstIndex = 0;
this.burstEntities.clear();
if (windUpTicks <= 0) {
this.phase = AbilityPhase.ACTIVE;
} else {
this.phase = AbilityPhase.WINDUP;
}
}
/**
@@ -578,6 +853,19 @@ public abstract class Ability implements IAbility {
return true;
}
break;
case BURST_DELAY:
// Waiting between burst repetitions - free movement/rotation
if (currentTick >= burstDelay) {
if (burstReplayAnimations && getWindUpTicks() > 0) {
phase = AbilityPhase.WINDUP;
} else {
phase = AbilityPhase.ACTIVE;
}
currentTick = 0;
return true;
}
break;
}
return false;
}
@@ -591,6 +879,19 @@ public abstract class Ability implements IAbility {
*/
public boolean signalCompletion() {
if (phase == AbilityPhase.ACTIVE) {
// Check if more burst iterations remain
if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) {
if (!burstOverlap) {
cleanup();
}
burstIndex++;
phase = AbilityPhase.BURST_DELAY;
currentTick = 0;
return true;
}
// Final completion - let burst entities die naturally (don't force-kill)
burstEntities.clear();
cleanup();
phase = AbilityPhase.IDLE;
currentTick = 0;
@@ -604,9 +905,10 @@ public abstract class Ability implements IAbility {
* Called when NPC takes direct damage during WINDUP.
*/
public void interrupt() {
cleanupBurstEntities();
cleanup();
if (interruptible && phase == AbilityPhase.WINDUP) {
// Interrupted during windup - go to dazed state
if (interruptible && (phase == AbilityPhase.WINDUP || phase == AbilityPhase.BURST_DELAY)) {
// Interrupted during windup or burst delay - go to dazed state
phase = AbilityPhase.DAZED;
currentTick = 0;
} else {
@@ -614,6 +916,7 @@ public abstract class Ability implements IAbility {
phase = AbilityPhase.IDLE;
currentTick = 0;
}
burstIndex = 0;
currentTarget = null;
telegraphInstance = null;
}
@@ -634,7 +937,7 @@ public abstract class Ability implements IAbility {
* @return true if the ability should be interrupted
*/
public boolean canInterrupt(DamageSource source) {
if (!interruptible || phase != AbilityPhase.WINDUP) {
if (!interruptible || (phase != AbilityPhase.WINDUP && phase != AbilityPhase.BURST_DELAY)) {
return false;
}
@@ -661,11 +964,15 @@ public abstract class Ability implements IAbility {
* Reset all execution state (called on combat end, NPC death, target lost, etc.)
*/
public void reset() {
cleanupBurstEntities();
cleanup();
phase = AbilityPhase.IDLE;
currentTick = 0;
burstIndex = 0;
currentTarget = null;
telegraphInstance = null;
previewMode = false;
previewEntityHandler = null;
}
/**
@@ -677,91 +984,73 @@ public abstract class Ability implements IAbility {
// Override in subclasses to clean up spawned entities, etc.
}
/**
* Kill all entities tracked during burst overlap and clear the list.
*/
protected void cleanupBurstEntities() {
for (Entity e : burstEntities) {
if (e != null && !e.isDead) {
killAbilityEntity(e);
}
}
burstEntities.clear();
}
// ═══════════════════════════════════════════════════════════════════
// CLIENT-SIDE PREVIEW METHODS
// PREVIEW MODE SUPPORT
// ═══════════════════════════════════════════════════════════════════
/**
* Get total active phase duration for preview (in ticks).
* Override in subclasses to provide accurate preview duration.
*
* @return Duration of active phase in ticks (default: 40 = 2 seconds)
* Whether this ability is running in preview mode (GUI preview).
* When true, abilities should skip damage, effects, sounds, and particles
* but still run their core logic (entity spawning, movement, timing).
*/
public int getPreviewActiveDuration() {
return 40;
public boolean isPreview() {
return previewMode;
}
public void setPreviewMode(boolean preview) {
this.previewMode = preview;
}
public void setPreviewEntityHandler(PreviewEntityHandler handler) {
this.previewEntityHandler = handler;
}
/**
* Called during preview windup tick (client-side only).
* Override for visual updates during windup preview.
* Do NOT apply damage or world effects here.
*
* @param npc The preview NPC
* @param tick Current tick within windup phase
* Spawn an entity during ability execution.
* In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld().
*/
@SideOnly(Side.CLIENT)
public void onPreviewWindUpTick(EntityNPCInterface npc, int tick) {
// Default: no-op. Override in subclasses for visual effects.
protected void spawnAbilityEntity(World world, Entity entity) {
if (previewMode && previewEntityHandler != null) {
previewEntityHandler.onEntitySpawned(entity);
} else {
world.spawnEntityInWorld(entity);
}
if (burstEnabled && burstOverlap) {
burstEntities.add(entity);
}
}
/**
* Called during preview active tick (client-side only).
* Override for visual updates during active preview.
* Do NOT apply damage or world effects here.
*
* @param npc The preview NPC
* @param tick Current tick within active phase
* Kill an entity spawned by this ability.
* In preview mode, notifies PreviewEntityHandler of removal.
*/
@SideOnly(Side.CLIENT)
public void onPreviewActiveTick(EntityNPCInterface npc, int tick) {
// Default: no-op. Override in subclasses for visual effects.
protected void killAbilityEntity(Entity entity) {
if (entity == null) return;
entity.setDead();
if (previewMode && previewEntityHandler != null) {
previewEntityHandler.onEntityRemoved(entity);
}
}
/**
* Create a preview entity for GUI display (client-side only).
* The entity should be in preview mode and not apply damage.
* Override in abilities that spawn entities (Beam, Orb, Disc, etc.)
*
* @param npc The preview NPC
* @return Preview entity, or null if ability doesn't spawn entities
* Maximum duration (in ticks) for preview before auto-stopping.
* Override in movement abilities that have variable duration.
* Default: 200 ticks (10 seconds).
*/
@SideOnly(Side.CLIENT)
public Entity createPreviewEntity(EntityNPCInterface npc) {
return null; // Override in entity-spawning abilities
}
/**
* Whether to spawn preview entity during WINDUP phase (true) or ACTIVE phase (false).
* Most abilities (Orb, Beam, Disc) spawn during windup for charging effect.
* Laser spawns at active phase since it has no charging state.
*/
public boolean spawnPreviewDuringWindup() {
return true; // Default: spawn during windup for charging
}
// ── Preview target (set by executor for abilities that need targeting) ──
protected transient EntityLivingBase previewTarget;
/**
* Set the fake target entity for preview mode.
* Called by AbilityPreviewExecutor before starting preview.
*/
public void setPreviewTarget(EntityLivingBase target) {
this.previewTarget = target;
}
public EntityLivingBase getPreviewTarget() {
return previewTarget;
}
/**
* Called once when transitioning from WINDUP to ACTIVE in preview mode.
* Override in movement-based abilities to initiate movement.
*/
@SideOnly(Side.CLIENT)
public void onPreviewExecute(EntityNPCInterface npc) {
// Default: no-op. Override in movement abilities.
public int getMaxPreviewDuration() {
return 200;
}
// ═══════════════════════════════════════════════════════════════════
@@ -803,9 +1092,12 @@ public abstract class Ability implements IAbility {
nbt.setFloat("maxRange", maxRange);
nbt.setInteger("cooldown", cooldownTicks);
nbt.setInteger("windUp", windUpTicks);
nbt.setBoolean("syncWindup", syncWindupWithAnimation);
nbt.setInteger("recovery", dazedTicks);
nbt.setBoolean("interruptible", interruptible);
nbt.setInteger("lockMovement", lockMovement.ordinal());
nbt.setInteger("rotationMode", rotationMode.ordinal());
nbt.setInteger("rotationPhase", rotationPhase.ordinal());
nbt.setInteger("windUpColor", windUpColor);
nbt.setInteger("activeColor", activeColor);
nbt.setString("windUpSound", windUpSound);
@@ -821,6 +1113,13 @@ public abstract class Ability implements IAbility {
nbt.setInteger("allowedBy", allowedBy.ordinal());
nbt.setBoolean("ignoreCooldown", ignoreCooldown);
// Burst
nbt.setBoolean("burstEnabled", burstEnabled);
nbt.setInteger("burstAmount", burstAmount);
nbt.setInteger("burstDelay", burstDelay);
nbt.setBoolean("burstReplayAnimations", burstReplayAnimations);
nbt.setBoolean("burstOverlap", burstOverlap);
// Conditions
NBTTagList condList = new NBTTagList();
for (Condition c : conditions) condList.appendTag(c.writeNBT());
@@ -852,9 +1151,34 @@ public abstract class Ability implements IAbility {
maxRange = nbt.getFloat("maxRange");
cooldownTicks = nbt.getInteger("cooldown");
windUpTicks = nbt.getInteger("windUp");
syncWindupWithAnimation = !nbt.hasKey("syncWindup") || nbt.getBoolean("syncWindup");
dazedTicks = nbt.getInteger("recovery");
interruptible = nbt.getBoolean("interruptible");
lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement"));
if (nbt.hasKey("rotationMode")) {
// Current format
rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode"));
rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase"));
} else if (nbt.hasKey("lockType")) {
// Legacy format migration: lockType was LockType enum (0=MOVEMENT, 1=ROTATION, 2=BOTH)
int oldLockType = nbt.getInteger("lockType");
if (oldLockType == 0) {
// MOVEMENT only: movement locked, rotation was free
rotationMode = RotationMode.FREE;
} else if (oldLockType == 1) {
// ROTATION only: rotation locked same timing as old lockMovement, movement was free
rotationMode = RotationMode.LOCKED;
rotationPhase = lockMovement;
lockMovement = LockMovementType.NO;
} else {
// BOTH: both locked same timing
rotationMode = RotationMode.LOCKED;
rotationPhase = lockMovement;
}
} else {
rotationMode = RotationMode.FREE;
rotationPhase = LockMovementType.WINDUP_AND_ACTIVE;
}
windUpColor = nbt.getInteger("windUpColor");
activeColor = nbt.getInteger("activeColor");
windUpSound = nbt.getString("windUpSound");
@@ -876,6 +1200,13 @@ public abstract class Ability implements IAbility {
allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH;
ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown");
// Burst
burstEnabled = nbt.hasKey("burstEnabled") && nbt.getBoolean("burstEnabled");
burstAmount = nbt.hasKey("burstAmount") ? nbt.getInteger("burstAmount") : 0;
burstDelay = nbt.hasKey("burstDelay") ? nbt.getInteger("burstDelay") : 0;
burstReplayAnimations = !nbt.hasKey("burstReplayAnimations") || nbt.getBoolean("burstReplayAnimations");
burstOverlap = nbt.hasKey("burstOverlap") && nbt.getBoolean("burstOverlap");
// Conditions
conditions.clear();
NBTTagList condList = nbt.getTagList("conditions", 10);
@@ -972,6 +1303,10 @@ public abstract class Ability implements IAbility {
}
public int getWindUpTicks() {
return calculateWindupFromAnimation();
}
public int getRawWindUpTicks() {
return windUpTicks;
}
@@ -979,6 +1314,18 @@ public abstract class Ability implements IAbility {
this.windUpTicks = Math.max(0, windUpTicks);
}
public boolean isSyncWindupWithAnimation() {
return syncWindupWithAnimation;
}
public boolean hasWindUpAnimation() {
return (windUpAnimationName != null && !windUpAnimationName.isEmpty()) || windUpAnimationId >= 0;
}
public void setSyncWindupWithAnimation(boolean syncWindupWithAnimation) {
this.syncWindupWithAnimation = syncWindupWithAnimation;
}
public int getDazedTicks() {
return dazedTicks;
}
@@ -1003,6 +1350,22 @@ public abstract class Ability implements IAbility {
this.lockMovement = lockMovement;
}
public RotationMode getRotationMode() {
return rotationMode;
}
public void setRotationMode(RotationMode rotationMode) {
this.rotationMode = rotationMode;
}
public LockMovementType getRotationPhase() {
return rotationPhase;
}
public void setRotationPhase(LockMovementType rotationPhase) {
this.rotationPhase = rotationPhase;
}
/**
* API method: Get lock movement type as integer.
* @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE
@@ -1022,7 +1385,43 @@ public abstract class Ability implements IAbility {
}
/**
* Check if movement should be locked during WINDUP phase.
* API method: Get rotation mode as integer.
* @return 0=FREE, 1=LOCKED, 2=TRACK
*/
@Override
public int getRotationModeType() {
return rotationMode.ordinal();
}
/**
* API method: Set rotation mode from integer.
* @param type 0=FREE, 1=LOCKED, 2=TRACK
*/
@Override
public void setRotationModeType(int type) {
this.rotationMode = RotationMode.fromOrdinal(type);
}
/**
* API method: Get rotation phase as integer.
* @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE
*/
@Override
public int getRotationPhaseType() {
return rotationPhase.ordinal();
}
/**
* API method: Set rotation phase from integer.
* @param type 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE
*/
@Override
public void setRotationPhaseType(int type) {
this.rotationPhase = LockMovementType.fromOrdinal(type);
}
/**
* Check if movement (pathfinding/motion) should be locked during WINDUP phase.
*/
@Override
public boolean isMovementLockedDuringWindup() {
@@ -1030,22 +1429,73 @@ public abstract class Ability implements IAbility {
}
/**
* Check if movement should be locked during ACTIVE phase.
* Check if movement (pathfinding/motion) should be locked during ACTIVE phase.
*/
@Override
public boolean isMovementLockedDuringActive() {
return lockMovement.locksActive();
}
/**
* Check if rotation (yaw/pitch) should be locked during WINDUP phase.
*/
@Override
public boolean isRotationLockedDuringWindup() {
return rotationMode == RotationMode.LOCKED && rotationPhase.locksWindup();
}
/**
* Check if rotation (yaw/pitch) should be locked during ACTIVE phase.
*/
@Override
public boolean isRotationLockedDuringActive() {
return rotationMode == RotationMode.LOCKED && rotationPhase.locksActive();
}
/**
* Check if movement should be locked during the current phase.
*/
public boolean isMovementLockedForCurrentPhase() {
switch (phase) {
case WINDUP:
return lockMovement.locksWindup();
return isMovementLockedDuringWindup();
case ACTIVE:
return lockMovement.locksActive();
return isMovementLockedDuringActive();
case BURST_DELAY:
return false; // Free movement during burst delay
default:
return false;
}
}
/**
* Check if rotation should be locked during the current phase.
*/
public boolean isRotationLockedForCurrentPhase() {
switch (phase) {
case WINDUP:
return isRotationLockedDuringWindup();
case ACTIVE:
return isRotationLockedDuringActive();
case BURST_DELAY:
return false; // Free rotation during burst delay
default:
return false;
}
}
/**
* Check if hit scan (force face target) is active during the current phase.
*/
public boolean isHitScanForCurrentPhase() {
if (rotationMode != RotationMode.TRACK) return false;
switch (phase) {
case WINDUP:
return rotationPhase.locksWindup();
case ACTIVE:
return rotationPhase.locksActive();
case BURST_DELAY:
return false; // Free rotation during burst delay
default:
return false;
}
@@ -1088,7 +1538,7 @@ public abstract class Ability implements IAbility {
// Built-in animation by name takes priority
if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(windUpAnimationName);
return (Animation) AnimationController.Instance.get(windUpAnimationName, true);
}
// Fall back to user animation by ID
if (windUpAnimationId >= 0) {
@@ -1118,7 +1568,7 @@ public abstract class Ability implements IAbility {
// Built-in animation by name takes priority
if (activeAnimationName != null && !activeAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(activeAnimationName);
return (Animation) AnimationController.Instance.get(activeAnimationName, true);
}
// Fall back to user animation by ID
if (activeAnimationId >= 0) {
@@ -1234,6 +1684,100 @@ public abstract class Ability implements IAbility {
effects.clear();
}
// Burst getters/setters
public boolean isBurstEnabled() {
return burstEnabled;
}
public void setBurstEnabled(boolean burstEnabled) {
this.burstEnabled = burstEnabled;
}
public int getBurstAmount() {
return burstAmount;
}
public void setBurstAmount(int burstAmount) {
this.burstAmount = Math.max(0, burstAmount);
}
public int getBurstDelay() {
return burstDelay;
}
public void setBurstDelay(int burstDelay) {
this.burstDelay = Math.max(0, burstDelay);
}
public boolean isBurstReplayAnimations() {
return burstReplayAnimations;
}
public void setBurstReplayAnimations(boolean burstReplayAnimations) {
this.burstReplayAnimations = burstReplayAnimations;
}
public boolean isBurstOverlap() {
return burstOverlap;
}
public void setBurstOverlap(boolean burstOverlap) {
this.burstOverlap = burstOverlap;
}
public int getBurstIndex() {
return burstIndex;
}
/**
* Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that).
*/
private static String[] getRotationPhaseKeys() {
return new String[]{
"ability.lockMove.windup",
"ability.lockMove.active",
"ability.lockMove.both"
};
}
// ═══════════════════════════════════════════════════════════════════
// SHIT FROM THE ASS
// ═══════════════════════════════════════════════════════════════════
private int calculateWindupFromAnimation() {
if (!syncWindupWithAnimation) {
return windUpTicks;
}
if (AnimationController.Instance == null) {
return this.windUpTicks;
}
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) {
animation = (Animation) AnimationController.Instance.get(windUpAnimationId);
}
if (animation == null || animation.frames.isEmpty()) {
return this.windUpTicks;
}
// Calculate total duration by summing all frame durations
int totalDuration = 0;
for (Frame frame : animation.frames) {
totalDuration += frame.getDuration();
}
// Return total duration
return totalDuration;
}
// ═══════════════════════════════════════════════════════════════════
// IAbility API METHODS
// ═══════════════════════════════════════════════════════════════════
@@ -1,23 +1,6 @@
package kamkeel.npcs.controllers.data.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilitySweeper;
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.AbilityGuard;
import kamkeel.npcs.controllers.data.ability.type.AbilityHazard;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeal;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit;
import kamkeel.npcs.controllers.data.ability.type.AbilityOrb;
import kamkeel.npcs.controllers.data.ability.type.AbilityDisc;
import kamkeel.npcs.controllers.data.ability.type.AbilityLaserShot;
import kamkeel.npcs.controllers.data.ability.type.AbilityEnergyBeam;
import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile;
import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave;
import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
import kamkeel.npcs.controllers.data.ability.type.*;
import kamkeel.npcs.controllers.SyncController;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
@@ -56,6 +39,15 @@ public class AbilityController implements IAbilityHandler {
* Used by AbilitySlot for cache invalidation. */
private int version = 0;
/** External damage handler (e.g., DBC Addon). */
private IAbilityDamageHandler damageHandler = null;
/** External field providers for ability GUI (e.g., DBC Addon). Client-side only. */
private final List<IAbilityFieldProvider> fieldProviders = new ArrayList<>();
/** External variant definitions registered by addons, keyed by typeId. */
private final Map<String, List<AbilityVariant>> externalVariants = new LinkedHashMap<>();
public AbilityController() {
registerBuiltinTypes();
}
@@ -191,30 +183,93 @@ public class AbilityController implements IAbilityHandler {
// ═══════════════════════════════════════════════════════════════════════════
/**
* Resolve an ability by key. Checks built-in abilities first (by name),
* then custom abilities (by UUID). Returns a copy safe to modify.
* Resolve an ability by key. Checks built-in abilities first (by name or registry key),
* then custom abilities (by UUID or name). Returns a copy safe to modify for
* custom abilities, or the singleton instance for built-in abilities.
*
* @param key The ability name (built-in) or UUID (custom)
* @return A copy of the resolved ability, or null if not found
* @param key The ability name, registry key (built-in) or UUID (custom)
* @return The resolved ability, or null if not found
*/
public Ability resolveAbility(String key) {
if (key == null || key.isEmpty()) return null;
// Check built-in abilities first
// Check built-in abilities first (exact match by name)
Ability builtIn = abilities.get(key);
if (builtIn != null) {
return fromNBT(builtIn.writeNBT());
return builtIn;
}
// Check custom abilities
// Check built-in abilities by name (case-insensitive)
for (Map.Entry<String, Ability> entry : abilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
// Check built-in abilities by registry key / ID
for (Ability ability : abilities.values()) {
if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) {
return ability;
}
}
// Check custom abilities (exact UUID match)
Ability custom = customAbilities.get(key);
if (custom != null) {
return fromNBT(custom.writeNBT());
}
// Check custom abilities by name (case-insensitive)
for (Ability ability : customAbilities.values()) {
if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) {
return fromNBT(ability.writeNBT());
}
}
return null;
}
/**
* Get all keys that can be used to look up abilities (for tab completion).
* Returns registry keys for built-in abilities (no spaces) and UUIDs for custom.
*/
public Set<String> getAbilityKeys() {
Set<String> keys = new LinkedHashSet<>();
// Built-in abilities - use the ID (registry key for BuiltInAbility)
for (Ability ability : abilities.values()) {
String id = ability.getId();
if (id != null && !id.isEmpty()) {
keys.add(id);
}
}
// Custom abilities - use UUID
keys.addAll(customAbilities.keySet());
return keys;
}
/**
* Get keys for player-usable abilities only (for tab completion).
*/
public Set<String> getPlayerAbilityKeys() {
Set<String> keys = new LinkedHashSet<>();
// Built-in abilities - use the ID (registry key for BuiltInAbility)
for (Ability ability : abilities.values()) {
if (ability.getAllowedBy().allowsPlayer()) {
String id = ability.getId();
if (id != null && !id.isEmpty()) {
keys.add(id);
}
}
}
// Custom abilities - use UUID (if player-usable)
for (Map.Entry<String, Ability> entry : customAbilities.entrySet()) {
if (entry.getValue().getAllowedBy().allowsPlayer()) {
keys.add(entry.getKey());
}
}
return keys;
}
/**
* Check if an ability key exists (either built-in or custom).
*/
@@ -382,7 +437,7 @@ public class AbilityController implements IAbilityHandler {
registerType("cnpc:orb", AbilityOrb::new);
registerType("cnpc:disc", AbilityDisc::new);
registerType("cnpc:laser_shot", AbilityLaserShot::new);
registerType("cnpc:beam", AbilityEnergyBeam::new);
registerType("cnpc:beam", AbilityBeam::new);
// Movement abilities
registerType("cnpc:charge", AbilityCharge::new);
@@ -399,4 +454,76 @@ public class AbilityController implements IAbilityHandler {
registerType("cnpc:hazard", AbilityHazard::new);
registerType("cnpc:trap", AbilityTrap::new);
}
// ═══════════════════════════════════════════════════════════════════════════
// EXTERNAL DAMAGE HANDLER
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register an external damage handler for abilities.
* When set, the handler is called before default damage application.
* If the handler returns true, default damage is skipped.
*/
public void registerDamageHandler(IAbilityDamageHandler handler) {
this.damageHandler = handler;
}
/** Get the registered damage handler, or null if none. */
public IAbilityDamageHandler getDamageHandler() {
return damageHandler;
}
// ═══════════════════════════════════════════════════════════════════════════
// EXTERNAL FIELD PROVIDERS
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register an external field provider for ability GUIs.
* Providers are called during getAllDefinitions() to inject custom tabs/fields.
*/
public void registerFieldProvider(IAbilityFieldProvider provider) {
fieldProviders.add(provider);
}
/** Get all registered field providers. */
public List<IAbilityFieldProvider> getFieldProviders() {
return fieldProviders;
}
// ═══════════════════════════════════════════════════════════════════════════
// EXTERNAL VARIANT REGISTRY
// ═══════════════════════════════════════════════════════════════════════════
/**
* Register an external variant for an ability type.
* External mods can call this to add variant presets that appear
* alongside built-in variants in the variant selection SubGui.
*
* @param typeId The ability typeId (e.g., "ability.cnpc.beam")
* @param variant The variant to register
*/
public void registerVariant(String typeId, AbilityVariant variant) {
externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant);
}
/**
* Get all variants for a given ability type (built-in + external).
* Returns the combined list of variants from the ability's getVariants()
* and any externally registered variants.
*
* @param typeId The ability typeId
* @return Combined list of variants, empty if none
*/
public List<AbilityVariant> getVariantsForType(String typeId) {
List<AbilityVariant> result = new ArrayList<>();
Ability temp = create(typeId);
if (temp != null) {
result.addAll(temp.getVariants());
}
List<AbilityVariant> ext = externalVariants.get(typeId);
if (ext != null) {
result.addAll(ext);
}
return result;
}
}
@@ -38,6 +38,13 @@ public class AbilityEffect {
return potionId;
}
public static String[] getLangKeys() {
EffectType[] types = values();
String[] keys = new String[types.length];
for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey;
return keys;
}
public static EffectType fromOrdinal(int ordinal) {
EffectType[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
@@ -4,5 +4,6 @@ public enum AbilityPhase {
IDLE, // Not executing
WINDUP, // Charging up (telegraph visible)
ACTIVE, // Executing (damage happens)
DAZED // Stunned after interrupt during WINDUP (cannot attack)
DAZED, // Stunned after interrupt during WINDUP (cannot attack)
BURST_DELAY // Waiting between burst repetitions (free movement/rotation)
}
@@ -0,0 +1,54 @@
package kamkeel.npcs.controllers.data.ability;
import java.util.function.Consumer;
/**
* Represents a variant/template for an ability type.
* When a user creates an ability that has registered variants,
* they are presented with a selection dialog before the ability is created.
*
* Each variant has a display name (lang key) and a configurator that
* applies preset values to the newly created ability.
*/
public class AbilityVariant {
private final String displayKey;
private final String group;
private final Consumer<Ability> configurator;
/**
* @param displayKey Lang key for the variant display name (e.g., "ability.variant.dual")
* @param configurator Lambda that configures the ability with preset values
*/
public AbilityVariant(String displayKey, Consumer<Ability> configurator) {
this(displayKey, null, configurator);
}
/**
* @param displayKey Lang key for the variant display name
* @param group Optional group header shown in the variant selection GUI (e.g., "DBC Addon")
* @param configurator Lambda that configures the ability with preset values
*/
public AbilityVariant(String displayKey, String group, Consumer<Ability> configurator) {
this.displayKey = displayKey;
this.group = group;
this.configurator = configurator;
}
public String getDisplayKey() {
return displayKey;
}
public String getGroup() {
return group;
}
/**
* Apply this variant's preset configuration to the given ability.
*/
public void apply(Ability ability) {
if (configurator != null) {
configurator.accept(ability);
}
}
}
@@ -45,4 +45,17 @@ public enum AnchorPoint {
}
return names;
}
@Override
public String toString() {
switch (this) {
case FRONT: return "ability.anchor.front";
case CENTER: return "ability.anchor.center";
case RIGHT_HAND: return "ability.anchor.rightHand";
case LEFT_HAND: return "ability.anchor.leftHand";
case ABOVE_HEAD: return "ability.anchor.aboveHead";
case CHEST: return "ability.anchor.chest";
default: return name();
}
}
}
@@ -31,14 +31,6 @@ public abstract class BuiltInAbility extends Ability {
return registryKey;
}
/**
* Built-in abilities are not customizable.
*/
@Override
public boolean isCustomizable() {
return false;
}
/**
* Built-in abilities do not write type-specific NBT (they have fixed configs).
*/
@@ -0,0 +1,27 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.entity.EntityLivingBase;
/**
* External damage handler for abilities.
* When registered, called AFTER script events but BEFORE default attackEntityFrom.
* If handleDamage returns true, default damage is skipped.
*/
public interface IAbilityDamageHandler {
/**
* Handle damage from an ability.
*
* @param ability The ability dealing damage
* @param caster The entity executing the ability
* @param target The entity being hit
* @param damage The damage amount (after script event modifications)
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback
* @param knockbackDirX The X component of knockback direction
* @param knockbackDirZ The Z component of knockback direction
* @return true if damage was handled (skip default), false to use default damage
*/
boolean handleDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target,
float damage, float knockback, float knockbackUp,
double knockbackDirX, double knockbackDirZ);
}
@@ -0,0 +1,25 @@
package kamkeel.npcs.controllers.data.ability;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
/**
* External field definition provider for abilities.
* Called during getAllDefinitions() to allow mods to inject custom tabs/fields
* into the ability configuration GUI.
* <p>
* Note: Although this interface references FieldDef (client-only), it is safe to
* register on both sides because the generic type is erased at bytecode level.
* The addFieldDefinitions method is only ever called from client-side GUI code.
*/
public interface IAbilityFieldProvider {
/**
* Add field definitions to the ability's GUI.
* Fields added here should use .tab() to assign them to a custom tab.
*
* @param ability The ability being configured
* @param defs The mutable list of field definitions to add to
*/
void addFieldDefinitions(Ability ability, List<FieldDef> defs);
}
@@ -0,0 +1,47 @@
package kamkeel.npcs.controllers.data.ability;
/**
* Defines what an ability locks when Lock Position is enabled.
*/
public enum LockType {
MOVEMENT,
ROTATION,
BOTH;
public boolean locksMovement() {
return this == MOVEMENT || this == BOTH;
}
public boolean locksRotation() {
return this == ROTATION || this == BOTH;
}
public String getDisplayKey() {
switch (this) {
case MOVEMENT:
return "ability.lockType.movement";
case ROTATION:
return "ability.lockType.rotation";
case BOTH:
return "ability.lockType.both";
default:
return "ability.lockType.both";
}
}
public static String[] getDisplayKeys() {
return new String[]{
"ability.lockType.movement",
"ability.lockType.rotation",
"ability.lockType.both"
};
}
public static LockType fromOrdinal(int ordinal) {
LockType[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return BOTH;
}
}
@@ -0,0 +1,13 @@
package kamkeel.npcs.controllers.data.ability;
import net.minecraft.entity.Entity;
/**
* Interface for routing entity spawn/kill calls during preview mode.
* In preview mode, entities are not added to the world but instead
* tracked by the GUI for rendering in the 3D viewport.
*/
public interface PreviewEntityHandler {
void onEntitySpawned(Entity entity);
void onEntityRemoved(Entity entity);
}
@@ -0,0 +1,53 @@
package kamkeel.npcs.controllers.data.ability;
/**
* Defines what happens to NPC rotation during ability phases.
* Used with a LockMovementType to control WHEN it applies.
*/
public enum RotationMode {
/**
* NPC rotates normally via AI look helper.
*/
FREE,
/**
* Freeze rotation at the moment the phase starts.
* NPC stays facing the direction it was looking when the phase began.
*/
LOCKED,
/**
* Force NPC to continuously face its target (hit scan).
* Overrides AI look helper every tick for precise aiming.
*/
TRACK;
public String getDisplayKey() {
switch (this) {
case FREE:
return "ability.rotation.free";
case LOCKED:
return "ability.rotation.locked";
case TRACK:
return "ability.rotation.track";
default:
return "ability.rotation.free";
}
}
public static String[] getDisplayKeys() {
return new String[]{
"ability.rotation.free",
"ability.rotation.locked",
"ability.rotation.track"
};
}
public static RotationMode fromOrdinal(int ordinal) {
RotationMode[] values = values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
}
return FREE;
}
}
@@ -22,5 +22,16 @@ public enum TargetingMode {
/**
* AOE centered on target
*/
AOE_TARGET
AOE_TARGET;
@Override
public String toString() {
switch (this) {
case AGGRO_TARGET: return "ability.target.aggro_target";
case SELF: return "ability.target.self";
case AOE_SELF: return "ability.target.aoe_self";
case AOE_TARGET: return "ability.target.aoe_target";
default: return name();
}
}
}
@@ -2,8 +2,9 @@ package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyAnchorData;
public class EnergyAnchorData {
public class EnergyAnchorData implements IEnergyAnchorData {
public AnchorPoint anchorPoint = AnchorPoint.FRONT;
public float anchorOffsetX = 0;
public float anchorOffsetY = 0;
@@ -34,6 +35,54 @@ public class EnergyAnchorData {
this.anchorOffsetZ = anchorOffsetZ;
}
public AnchorPoint getAnchorPoint() {
return anchorPoint;
}
public void setAnchorPoint(AnchorPoint anchorPoint) {
this.anchorPoint = anchorPoint;
}
@Override
public int getAnchor() {
return anchorPoint.ordinal();
}
@Override
public void setAnchor(int anchor) {
this.anchorPoint = AnchorPoint.fromOrdinal(anchor);
}
@Override
public float getAnchorOffsetX() {
return anchorOffsetX;
}
@Override
public void setAnchorOffsetX(float anchorOffsetX) {
this.anchorOffsetX = anchorOffsetX;
}
@Override
public float getAnchorOffsetY() {
return anchorOffsetY;
}
@Override
public void setAnchorOffsetY(float anchorOffsetY) {
this.anchorOffsetY = anchorOffsetY;
}
@Override
public float getAnchorOffsetZ() {
return anchorOffsetZ;
}
@Override
public void setAnchorOffsetZ(float anchorOffsetZ) {
this.anchorOffsetZ = anchorOffsetZ;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("anchorPoint", anchorPoint.ordinal());
nbt.setFloat("anchorOffsetX", anchorOffsetX);
@@ -1,50 +0,0 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
/**
* Groups visual color properties shared by all energy abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyColorData {
public int innerColor = 0xFFFFFF;
public int outerColor = 0x8888FF;
public boolean outerColorEnabled = true;
public float outerColorWidth = 0.4f;
public float outerColorAlpha = 0.5f;
public float rotationSpeed = 4.0f;
public EnergyColorData() {}
public EnergyColorData(int innerColor, int outerColor, boolean outerColorEnabled,
float outerColorWidth, float outerColorAlpha, float rotationSpeed) {
this.innerColor = innerColor;
this.outerColor = outerColor;
this.outerColorEnabled = outerColorEnabled;
this.outerColorWidth = outerColorWidth;
this.outerColorAlpha = outerColorAlpha;
this.rotationSpeed = rotationSpeed;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("innerColor", innerColor);
nbt.setInteger("outerColor", outerColor);
nbt.setBoolean("outerColorEnabled", outerColorEnabled);
nbt.setFloat("outerColorWidth", outerColorWidth);
nbt.setFloat("outerColorAlpha", outerColorAlpha);
nbt.setFloat("rotationSpeed", rotationSpeed);
}
public void readNBT(NBTTagCompound nbt) {
innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF;
outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF;
outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled");
outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f;
outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f;
rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f;
}
public EnergyColorData copy() {
return new EnergyColorData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed);
}
}
@@ -1,12 +1,13 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyCombatData;
/**
* Groups combat properties shared by energy projectile abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyCombatData {
public class EnergyCombatData implements IEnergyCombatData {
public float damage = 7.0f;
public float knockback = 1.0f;
public float knockbackUp = 0.1f;
@@ -26,6 +27,66 @@ public class EnergyCombatData {
this.explosionDamageFalloff = explosionDamageFalloff;
}
@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 boolean isExplosive() {
return explosive;
}
@Override
public void setExplosive(boolean explosive) {
this.explosive = explosive;
}
@Override
public float getExplosionRadius() {
return explosionRadius;
}
@Override
public void setExplosionRadius(float explosionRadius) {
this.explosionRadius = explosionRadius;
}
@Override
public float getExplosionDamageFalloff() {
return explosionDamageFalloff;
}
@Override
public void setExplosionDamageFalloff(float explosionDamageFalloff) {
this.explosionDamageFalloff = explosionDamageFalloff;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("damage", damage);
nbt.setFloat("knockback", knockback);
@@ -0,0 +1,116 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyDisplayData;
/**
* Groups visual color properties shared by all energy abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyDisplayData implements IEnergyDisplayData {
public int innerColor = 0xFFFFFF;
public int outerColor = 0x8888FF;
public boolean outerColorEnabled = true;
public float outerColorWidth = 0.4f;
public float outerColorAlpha = 0.5f;
public float rotationSpeed = 4.0f;
public EnergyDisplayData() {}
public EnergyDisplayData(int innerColor, int outerColor) {
this.innerColor = innerColor;
this.outerColor = outerColor;
}
public EnergyDisplayData(int innerColor, int outerColor, boolean outerColorEnabled,
float outerColorWidth, float outerColorAlpha, float rotationSpeed) {
this.innerColor = innerColor;
this.outerColor = outerColor;
this.outerColorEnabled = outerColorEnabled;
this.outerColorWidth = outerColorWidth;
this.outerColorAlpha = outerColorAlpha;
this.rotationSpeed = rotationSpeed;
}
@Override
public int getInnerColor() {
return innerColor;
}
@Override
public void setInnerColor(int innerColor) {
this.innerColor = innerColor;
}
@Override
public int getOuterColor() {
return outerColor;
}
@Override
public void setOuterColor(int outerColor) {
this.outerColor = outerColor;
}
@Override
public boolean isOuterColorEnabled() {
return outerColorEnabled;
}
@Override
public void setOuterColorEnabled(boolean outerColorEnabled) {
this.outerColorEnabled = outerColorEnabled;
}
@Override
public float getOuterColorWidth() {
return outerColorWidth;
}
@Override
public void setOuterColorWidth(float outerColorWidth) {
this.outerColorWidth = outerColorWidth;
}
@Override
public float getOuterColorAlpha() {
return outerColorAlpha;
}
@Override
public void setOuterColorAlpha(float outerColorAlpha) {
this.outerColorAlpha = outerColorAlpha;
}
@Override
public float getRotationSpeed() {
return rotationSpeed;
}
@Override
public void setRotationSpeed(float rotationSpeed) {
this.rotationSpeed = rotationSpeed;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("innerColor", innerColor);
nbt.setInteger("outerColor", outerColor);
nbt.setBoolean("outerColorEnabled", outerColorEnabled);
nbt.setFloat("outerColorWidth", outerColorWidth);
nbt.setFloat("outerColorAlpha", outerColorAlpha);
nbt.setFloat("rotationSpeed", rotationSpeed);
}
public void readNBT(NBTTagCompound nbt) {
innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF;
outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF;
outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled");
outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f;
outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f;
rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f;
}
public EnergyDisplayData copy() {
return new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed);
}
}
@@ -1,12 +1,14 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyHomingData;
/**
* Groups homing/movement properties for energy projectile abilities.
* Used by Orb, Disc, and Beam (not Laser or Sweeper).
*/
public class EnergyHomingData {
public class EnergyHomingData implements IEnergyHomingData {
public float speed = 0.5f;
public boolean homing = true;
public float homingStrength = 0.15f;
@@ -21,6 +23,46 @@ public class EnergyHomingData {
this.homingRange = homingRange;
}
@Override
public float getSpeed() {
return speed;
}
@Override
public void setSpeed(float speed) {
this.speed = speed;
}
@Override
public boolean isHoming() {
return homing;
}
@Override
public void setHoming(boolean homing) {
this.homing = homing;
}
@Override
public float getHomingStrength() {
return homingStrength;
}
@Override
public void setHomingStrength(float homingStrength) {
this.homingStrength = homingStrength;
}
@Override
public float getHomingRange() {
return homingRange;
}
@Override
public void setHomingRange(float homingRange) {
this.homingRange = homingRange;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("speed", speed);
nbt.setBoolean("homing", homing);
@@ -1,12 +1,13 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyLifespanData;
/**
* Groups lifespan/range properties for energy projectile abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyLifespanData {
public class EnergyLifespanData implements IEnergyLifespanData {
public float maxDistance = 30.0f;
public int maxLifetime = 200;
@@ -17,6 +18,26 @@ public class EnergyLifespanData {
this.maxLifetime = maxLifetime;
}
@Override
public float getMaxDistance() {
return maxDistance;
}
@Override
public void setMaxDistance(float maxDistance) {
this.maxDistance = maxDistance;
}
@Override
public int getMaxLifetime() {
return maxLifetime;
}
@Override
public void setMaxLifetime(int maxLifetime) {
this.maxLifetime = maxLifetime;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setFloat("maxDistance", maxDistance);
nbt.setInteger("maxLifetime", maxLifetime);
@@ -1,12 +1,13 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.data.IEnergyLightningData;
/**
* Groups lightning visual effect properties for energy abilities.
* Used as a parameter object for entity constructors and ability configuration.
*/
public class EnergyLightningData {
public class EnergyLightningData implements IEnergyLightningData {
public boolean lightningEffect = false;
public float lightningDensity = 0.15f;
public float lightningRadius = 0.5f;
@@ -22,6 +23,46 @@ public class EnergyLightningData {
this.lightningFadeTime = lightningFadeTime;
}
@Override
public boolean isLightningEffect() {
return lightningEffect;
}
@Override
public void setLightningEffect(boolean lightningEffect) {
this.lightningEffect = lightningEffect;
}
@Override
public float getLightningDensity() {
return lightningDensity;
}
@Override
public void setLightningDensity(float lightningDensity) {
this.lightningDensity = lightningDensity;
}
@Override
public float getLightningRadius() {
return lightningRadius;
}
@Override
public void setLightningRadius(float lightningRadius) {
this.lightningRadius = lightningRadius;
}
@Override
public int getLightningFadeTime() {
return lightningFadeTime;
}
@Override
public void setLightningFadeTime(int lightningFadeTime) {
this.lightningFadeTime = lightningFadeTime;
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setBoolean("lightningEffect", lightningEffect);
nbt.setFloat("lightningDensity", lightningDensity);
@@ -0,0 +1,288 @@
package kamkeel.npcs.controllers.data.ability.data;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants;
import noppes.npcs.api.IPos;
import noppes.npcs.api.ability.data.IEnergyTrajectoryData;
import noppes.npcs.scripted.NpcAPI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
public class EnergyTrajectoryData implements IEnergyTrajectoryData {
public int currentPath = 0;
private final List<Path> trajectory = new ArrayList<>();
public EnergyTrajectoryData() {}
public EnergyTrajectoryData(int startingPath, Path... paths) {
trajectory.addAll(Arrays.asList(paths));
this.currentPath = startingPath < trajectory.size() && startingPath >= 0 ? startingPath : 0;
}
@Override
public int getCurrentPath() {
return currentPath;
}
@Override
public void setCurrentPath(int currentPath) {
this.currentPath = currentPath;
}
@Override
public int getDelay(int path) {
if (getPath(path) == null) return -1;
return getPath(path).getDelay();
}
@Override
public void setDelay(int path, int ticks) {
if (getPath(path) == null) return;
getPath(path).setDelay(ticks);
}
@Override
public IPos getPos(int path) {
IPath p = getPath(path);
return p == null ? null : p.getPos();
}
@Override
public void setPos(int path, IPos pos) {
IPath p = getPath(path);
if (p != null) p.setPos(pos);
}
@Override
public boolean isConcluded(int path) {
IPath p = getPath(path);
return p != null && p.isConcluded();
}
@Override
public void setConcluded(int path, boolean concluded) {
IPath p = getPath(path);
if (p != null) p.setConcluded(concluded);
}
@Override
public double getX(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getX();
}
@Override
public double getY(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getY();
}
@Override
public double getZ(int path) {
IPath p = getPath(path);
return p == null ? 0 : p.getZ();
}
@Override
public void setX(int path, double x) {
IPath p = getPath(path);
if (p != null) p.setX(x);
}
@Override
public void setY(int path, double y) {
IPath p = getPath(path);
if (p != null) p.setY(y);
}
@Override
public void setZ(int path, double z) {
IPath p = getPath(path);
if (p != null) p.setZ(z);
}
public IPath getPath(int path) {
if (path < 0 || path >= trajectory.size()) return null;
return trajectory.get(path);
}
@Override
public void setPath(int path, IPos pos) {
setPath(path, pos, 0);
}
@Override
public void setPath(int path, IPos pos, int delay) {
setPath(path, pos.getX(), pos.getY(), pos.getZ(), delay);
}
@Override
public void setPath(int path, double x, double y, double z) {
setPath(path, x, y, z, 0);
}
@Override
public void setPath(int path, double x, double y, double z, int delay) {
Path newPath = new Path(
NpcAPI.Instance().getIPos(x, y, z),
delay
);
while (trajectory.size() <= path) {
trajectory.add(null);
}
trajectory.set(path, newPath);
}
@Override
public IPath createPath(IPos pos) {
return new Path(pos, 0);
}
@Override
public IPath createPath(IPos pos, int delay) {
return new Path(pos, delay);
}
@Override
public IPath createPath(double x, double y, double z) {
return createPath(x, y, z, 0);
}
@Override
public IPath createPath(double x, double y, double z, int delay) {
return new Path(NpcAPI.Instance().getIPos(x, y, z), delay);
}
@Override
public void forEach(BiConsumer<Integer, IPath> lambda) {
for (int i = 0; i < trajectory.size(); i++) {
lambda.accept(i, trajectory.get(i));
}
}
public int size() {
return trajectory.size();
}
public boolean isEmpty() {
return trajectory.isEmpty();
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("currentPath", currentPath);
for (int i = 0; i < trajectory.size(); i++) {
Path path = trajectory.get(i);
NBTTagCompound pathNbt = new NBTTagCompound();
path.writeNBT(pathNbt);
nbt.setTag("Path_" + i, pathNbt);
}
}
public void readNBT(NBTTagCompound nbt) {
this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0;
int i = 0;
while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) {
NBTTagCompound pathNbt = nbt.getCompoundTag("Path_" + i);
Path path = (Path) createPath(0, 0, 0);
path.readNBT(pathNbt);
trajectory.add(path);
i++;
}
}
public static class Path implements IEnergyTrajectoryData.IPath{
public IPos pos;
public int delayTicks;
public boolean concluded;
public Path(IPos pos, int delayTicks) {
this.pos = pos;
this.delayTicks = delayTicks;
}
@Override
public IPos getPos() {
return pos;
}
@Override
public void setPos(IPos pos) {
this.pos = pos;
}
@Override
public int getDelay() {
return delayTicks;
}
@Override
public void setDelay(int delayTicks) {
this.delayTicks = delayTicks;
}
@Override
public boolean isConcluded() {
return concluded;
}
@Override
public void setConcluded(boolean concluded) {
this.concluded = concluded;
}
@Override
public double getX() {
return pos.getX();
}
@Override
public void setX(double x) {
this.pos = NpcAPI.Instance().getIPos(x, getY(), getZ());
}
@Override
public double getY() {
return pos.getY();
}
@Override
public void setY(double y) {
this.pos = NpcAPI.Instance().getIPos(getX(), y, getZ());
}
@Override
public double getZ() {
return pos.getZ();
}
@Override
public void setZ(double z) {
this.pos = NpcAPI.Instance().getIPos(pos.getX(), pos.getY(), z);
}
public void writeNBT(NBTTagCompound nbt) {
nbt.setInteger("delay", delayTicks);
nbt.setBoolean("concluded", concluded);
nbt.setDouble("X", getX());
nbt.setDouble("Y", getY());
nbt.setDouble("Z", getZ());
}
public void readNBT(NBTTagCompound nbt) {
this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0;
this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded");
double x = nbt.getDouble("X");
double y = nbt.getDouble("Y");
double z = nbt.getDouble("Z");
this.pos = NpcAPI.Instance().getIPos(x, y, z);
}
}
}
@@ -0,0 +1,60 @@
package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import net.minecraft.nbt.NBTTagCompound;
/**
* Per-projectile data: anchor point + optional color override.
* All projectiles share the primary EnergyDisplayData; this class
* allows individual projectiles to override just the inner/outer colors.
*/
public class ProjectileData {
public EnergyAnchorData anchor;
public boolean colorOverride = false;
public int innerColor = 0xFFFFFF;
public int outerColor = 0x8888FF;
public ProjectileData(AnchorPoint defaultAnchor) {
this.anchor = new EnergyAnchorData(defaultAnchor);
}
/**
* Returns the display data to use for this projectile.
* If colorOverride is false, returns the primary display data directly.
* If colorOverride is true, returns a copy with overridden inner/outer colors.
*/
public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) {
if (!colorOverride) return primary;
EnergyDisplayData resolved = primary.copy();
resolved.innerColor = this.innerColor;
resolved.outerColor = this.outerColor;
return resolved;
}
public void writeNBT(NBTTagCompound nbt) {
anchor.writeNBT(nbt);
nbt.setBoolean("colorOverride", colorOverride);
if (colorOverride) {
nbt.setInteger("overrideInnerColor", innerColor);
nbt.setInteger("overrideOuterColor", outerColor);
}
}
public void readNBT(NBTTagCompound nbt) {
anchor.readNBT(nbt);
colorOverride = nbt.getBoolean("colorOverride");
if (colorOverride) {
innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF;
outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF;
}
}
public ProjectileData copy() {
ProjectileData copy = new ProjectileData(anchor.anchorPoint);
copy.anchor = anchor.copy();
copy.colorOverride = colorOverride;
copy.innerColor = innerColor;
copy.outerColor = outerColor;
return copy;
}
}
@@ -0,0 +1,180 @@
package kamkeel.npcs.controllers.data.ability.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.builder.FieldType;
import noppes.npcs.client.gui.builder.GuiFieldBuilder;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Ability-specific extension of {@link GuiFieldBuilder} that handles
* the EFFECTS_LIST field type.
*/
@SideOnly(Side.CLIENT)
public class AbilityFieldBuilder extends GuiFieldBuilder {
// Effects list metadata: widgetId -> [effectIndex, action]
// action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add
private final Map<Integer, int[]> effectWidgetMeta = new HashMap<>();
public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) {
super(parent, fontRenderer);
}
@Override
protected int build(List<FieldDef> fields) {
effectWidgetMeta.clear();
return super.build(fields);
}
@Override
protected int buildField(FieldDef def, int y, List<FieldDef> fields, int index) {
if (def.getType() == FieldType.EFFECTS_LIST) {
return renderEffectsList(def, y);
}
return -1; // not handled
}
@SuppressWarnings("unchecked")
private int renderEffectsList(FieldDef def, int y) {
// Section header
y += 3;
sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55));
y += 15;
List<AbilityEffect> effects = (List<AbilityEffect>) def.getValue();
if (effects == null) effects = new ArrayList<>();
String[] typeNames = AbilityEffect.EffectType.getLangKeys();
String[] ampValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
for (int e = 0; e < effects.size() && e < 5; e++) {
AbilityEffect effect = effects.get(e);
// Type selector button
int typeIdx = effect.getType().ordinal();
GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx);
sw.addButton(typeBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 0});
widgetId++;
// Duration text field
GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer,
colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks()));
durField.setIntegersOnly();
durField.setMinMaxDefault(1, 12000, 60);
sw.addTextField(durField);
textFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 1});
widgetId++;
// Amplifier selector (0-10)
GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier());
sw.addButton(ampBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{e, 2});
widgetId++;
// Delete button
GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X");
sw.addButton(delBtn);
clearFieldMap.put(clearId, def);
effectWidgetMeta.put(clearId, new int[]{e, 3});
clearId++;
y += rowHeight;
}
// Add button (if < 5 effects)
if (effects.size() < 5) {
GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add");
sw.addButton(addBtn);
buttonFieldMap.put(widgetId, def);
effectWidgetMeta.put(widgetId, new int[]{effects.size(), 4});
widgetId++;
clearId++;
y += rowHeight;
}
return y;
}
// ═══════════════════════════════════════════════════════════════════
// EVENT HANDLING OVERRIDES
// ═══════════════════════════════════════════════════════════════════
@Override
@SuppressWarnings("unchecked")
public boolean handleButtonEvent(int buttonId, GuiButton button) {
// Check effects list buttons via metadata
int[] meta = effectWidgetMeta.get(buttonId);
if (meta != null) {
FieldDef def = buttonFieldMap.get(buttonId);
if (def == null) def = clearFieldMap.get(buttonId);
if (def != null && def.getType() == FieldType.EFFECTS_LIST) {
List<AbilityEffect> effects = (List<AbilityEffect>) def.getValue();
if (effects == null) return false;
int effectIdx = meta[0];
int action = meta[1];
switch (action) {
case 0: // Type changed
if (effectIdx < effects.size()) {
effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue()));
}
return true;
case 2: // Amp changed
if (effectIdx < effects.size()) {
effects.get(effectIdx).setAmplifier(((GuiNpcButton) button).getValue());
}
return true;
case 3: // Delete
if (effectIdx < effects.size()) {
effects.remove(effectIdx);
}
return true;
case 4: // Add
if (effects.size() < 5) {
effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0));
}
return true;
}
}
}
return super.handleButtonEvent(buttonId, button);
}
@Override
@SuppressWarnings("unchecked")
public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) {
int[] meta = effectWidgetMeta.get(textFieldId);
if (meta != null && meta[1] == 1) { // duration field
FieldDef def = textFieldMap.get(textFieldId);
if (def != null && def.getType() == FieldType.EFFECTS_LIST) {
List<AbilityEffect> effects = (List<AbilityEffect>) def.getValue();
if (effects != null && meta[0] < effects.size()) {
effects.get(meta[0]).setDurationTicks(field.getInteger());
}
return true;
}
}
return super.handleTextFieldEvent(textFieldId, field);
}
public Map<Integer, int[]> getEffectWidgetMeta() { return effectWidgetMeta; }
}
@@ -0,0 +1,27 @@
package kamkeel.npcs.controllers.data.ability.gui;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.builder.FieldType;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Ability-specific FieldDef factories. These create FieldDef instances
* with types that require ability-specific rendering (e.g. EFFECTS_LIST).
*/
@SideOnly(Side.CLIENT)
public class AbilityFieldDefs {
@SuppressWarnings("unchecked")
public static FieldDef effectsListField(String label, Supplier<List<AbilityEffect>> getter, Consumer<List<AbilityEffect>> setter) {
return FieldDef.custom(label, FieldType.EFFECTS_LIST,
() -> getter.get(),
v -> setter.accept((List<AbilityEffect>) v));
}
}
@@ -0,0 +1,637 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.RotationMode;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityEnergyBeam;
import java.util.Arrays;
import java.util.List;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
/**
* Energy Beam ability: A homing head with a trailing path.
* Supports 1-8 projectiles with shared visuals and per-projectile anchor points.
*/
public class AbilityBeam extends Ability implements IAbilityEnergyBeam {
private static final int MAX_PROJECTILES = 8;
// Beam shape properties (shared)
private float beamWidth = 0.4f;
private float headSize = 0.6f;
// Projectile count and fire stagger
private int projectileCount = 1;
private int fireDelay = 0;
// Shared visual data (all projectiles use these)
private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
// Shared combat/movement data
private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f);
private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f);
private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200);
// Per-projectile data (anchor + optional color override)
private ProjectileData[] projectiles;
// Transient entity state
private transient EntityAbilityBeam[] beamEntities;
public AbilityBeam() {
this.typeId = "ability.cnpc.beam";
this.name = "Beam";
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.maxRange = 20.0f;
this.minRange = 5.0f;
this.cooldownTicks = 0;
this.windUpTicks = 40;
this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE;
this.rotationMode = RotationMode.TRACK;
this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE;
this.telegraphType = TelegraphType.CIRCLE;
this.showTelegraph = true;
this.windUpAnimationName = "Ability_Beam_Windup";
this.activeAnimationName = "Ability_Beam_Active";
initProjectiles(1);
}
private void initProjectiles(int count) {
this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
this.projectiles = new ProjectileData[projectileCount];
for (int i = 0; i < projectileCount; i++) {
projectiles[i] = new ProjectileData(getDefaultAnchor(i));
}
}
private AnchorPoint getDefaultAnchor(int index) {
switch (index) {
case 0: return AnchorPoint.RIGHT_HAND;
case 1: return AnchorPoint.LEFT_HAND;
default: return AnchorPoint.FRONT;
}
}
public void setProjectileCount(int count) {
int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
if (newCount == projectileCount) return;
ProjectileData[] oldProjectiles = projectiles;
initProjectiles(newCount);
if (oldProjectiles != null) {
int copyCount = Math.min(oldProjectiles.length, newCount);
for (int i = 0; i < copyCount; i++) {
if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i];
}
}
}
public int getProjectileCount() {
return projectileCount;
}
public int getFireDelay() {
return fireDelay;
}
public void setFireDelay(int delay) {
this.fireDelay = Math.max(0, delay);
}
// Legacy compat
public int getDualFireDelay() { return fireDelay; }
public void setDualFireDelay(int delay) { setFireDelay(delay); }
@Override
public List<AbilityVariant> getVariants() {
return Arrays.asList(
new AbilityVariant("ability.variant.single", a -> {
a.setName("Beam");
}),
new AbilityVariant("ability.variant.dual", a -> {
AbilityBeam beam = (AbilityBeam) a;
a.setName("Dual Beam");
beam.setProjectileCount(2);
beam.setFireDelay(0);
// Set color override for second beam
beam.projectiles[1].colorOverride = true;
beam.projectiles[1].innerColor = 0xFFFFFF;
beam.projectiles[1].outerColor = 0xFF0000;
a.setWindUpTicks(80);
a.setWindUpAnimationName("Ability_BeamDual_Windup");
a.setActiveAnimationName("Ability_BeamDual_Active");
})
);
}
@Override
public boolean allowOverlap() {
return true;
}
@Override
public boolean isReadyForBurstCompletion(int activeTick) {
return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1);
}
@Override
public boolean isTargetingModeLocked() {
return true;
}
@Override
public TargetingMode[] getAllowedTargetingModes() {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
}
/**
* Create beam entities.
* NPC: target is the aggro target — beams will home toward it.
* Player: target is null — beams fire in caster's look direction.
*/
private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) {
EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount];
float offsetDist = 1.0f;
for (int i = 0; i < projectileCount; i++) {
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor, offsetDist);
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
entities[i] = new EntityAbilityBeam(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
beamWidth, headSize,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData,
lockMovement.locksActive());
entities[i].setEffects(this.effects);
entities[i].setSourceAbility(this);
}
if (projectileCount == 2 && entities[0] != null && entities[1] != null) {
entities[0].setSiblingEntityId(entities[1].getEntityId());
entities[1].setSiblingEntityId(entities[0].getEntityId());
}
return entities;
}
private void fireBeamEntity(EntityAbilityBeam beam, EntityLivingBase target) {
if (beam == null || beam.isDead) return;
if (isPreview()) {
beam.startPreviewFiring();
} else {
beam.startFiring(target);
}
}
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote && !isPreview()) return;
if (tick == 1) {
beamEntities = createBeamEntities(caster, target, world);
float offsetDist = 1.0f;
for (int i = 0; i < projectileCount; i++) {
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
if (isPreview()) {
beamEntities[i].setupPreview(caster, beamWidth, headSize, resolved, lightningData, projectiles[i].anchor, windUpTicks, offsetDist);
} else {
beamEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, offsetDist);
}
spawnAbilityEntity(world, beamEntities[i]);
}
}
}
@Override
public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) {
beamEntities = createBeamEntities(caster, target, world);
for (EntityAbilityBeam beam : beamEntities) {
spawnAbilityEntity(world, beam);
}
for (EntityAbilityBeam beam : beamEntities) {
fireBeamEntity(beam, target);
}
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
if (beamEntities == null) return;
fireBeamEntity(beamEntities[0], target);
if (fireDelay <= 0) {
for (int i = 1; i < projectileCount; i++) {
fireBeamEntity(beamEntities[i], target);
}
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (beamEntities == null) {
signalCompletion();
return;
}
if (fireDelay > 0) {
for (int i = 1; i < projectileCount; i++) {
if (tick == fireDelay * i) {
fireBeamEntity(beamEntities[i], target);
}
}
}
boolean allDead = true;
for (EntityAbilityBeam beam : beamEntities) {
if (beam != null && !beam.isDead) {
allDead = false;
break;
}
}
if (allDead) {
signalCompletion();
}
}
@Override
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
}
@Override
public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) {
cleanup();
}
@Override
public void cleanup() {
if (beamEntities != null) {
for (int i = 0; i < beamEntities.length; i++) {
if (beamEntities[i] != null && !beamEntities[i].isDead) {
beamEntities[i].setDead();
}
beamEntities[i] = null;
}
}
beamEntities = null;
}
@Override
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
// NPC: telegraph on aggro target position
// Player: no telegraph (beam fires in look direction, no fixed position to mark)
if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) {
return null;
}
Telegraph telegraph = Telegraph.circle(headSize * 2.0f);
telegraph.setDurationTicks(windUpTicks);
telegraph.setColor(windUpColor);
telegraph.setWarningColor(activeColor);
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(target.getEntityId());
return instance;
}
@Override
public float getTelegraphRadius() {
return headSize * 2.0f;
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("beamWidth", beamWidth);
nbt.setFloat("headSize", headSize);
nbt.setInteger("projectileCount", projectileCount);
nbt.setInteger("fireDelay", fireDelay);
// Shared visual data
displayData.writeNBT(nbt);
lightningData.writeNBT(nbt);
// Shared combat/movement data
combatData.writeNBT(nbt);
homingData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
// Per-projectile data
for (int i = 0; i < projectileCount; i++) {
NBTTagCompound projNbt = new NBTTagCompound();
projectiles[i].writeNBT(projNbt);
nbt.setTag("Projectile_" + i, projNbt);
}
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f;
this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f;
int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1;
initProjectiles(count);
if (nbt.hasKey("fireDelay")) {
this.fireDelay = nbt.getInteger("fireDelay");
} else if (nbt.hasKey("dualFireDelay")) {
this.fireDelay = nbt.getInteger("dualFireDelay");
} else {
this.fireDelay = 0;
}
combatData.readNBT(nbt);
homingData.readNBT(nbt);
lifespanData.readNBT(nbt);
if (nbt.hasKey("Projectile_0")) {
NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0");
if (proj0.hasKey("colorOverride")) {
// NEW format
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
for (int i = 0; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i));
}
}
} else {
// OLD per-projectile format
displayData.readNBT(proj0);
lightningData.readNBT(proj0);
projectiles[0].anchor.readNBT(proj0);
for (int i = 1; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i);
projectiles[i].anchor.readNBT(projNbt);
EnergyDisplayData tempDisplay = new EnergyDisplayData();
tempDisplay.readNBT(projNbt);
if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) {
projectiles[i].colorOverride = true;
projectiles[i].innerColor = tempDisplay.innerColor;
projectiles[i].outerColor = tempDisplay.outerColor;
}
}
}
}
} else {
// LEGACY flat format
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
projectiles[0].anchor.readNBT(nbt);
}
}
// ═══════════════════════════════════════════════════════════════════
// API GETTERS & SETTERS
// ═══════════════════════════════════════════════════════════════════
public float getBeamWidth() { return beamWidth; }
public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; }
public float getHeadSize() { return headSize; }
public void setHeadSize(float headSize) { this.headSize = headSize; }
public float getSpeed() { return homingData.speed; }
public void setSpeed(float speed) { this.homingData.speed = speed; }
public float getMaxDistance() { return lifespanData.maxDistance; }
public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; }
public int getMaxLifetime() { return lifespanData.maxLifetime; }
public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; }
public float getDamage() { return combatData.damage; }
public void setDamage(float damage) { this.combatData.damage = damage; }
public float getKnockback() { return combatData.knockback; }
public void setKnockback(float knockback) { this.combatData.knockback = knockback; }
public float getKnockbackUp() { return combatData.knockbackUp; }
public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; }
public boolean isHoming() { return homingData.homing; }
public void setHoming(boolean homing) { this.homingData.homing = homing; }
public float getHomingStrength() { return homingData.homingStrength; }
public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; }
public float getHomingRange() { return homingData.homingRange; }
public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; }
public boolean isExplosive() { return combatData.explosive; }
public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; }
public float getExplosionRadius() { return combatData.explosionRadius; }
public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; }
public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; }
public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; }
// Shared display data (primary colors)
public int getInnerColor() { return displayData.innerColor; }
public void setInnerColor(int innerColor) { displayData.innerColor = innerColor; }
public int getOuterColor() { return displayData.outerColor; }
public void setOuterColor(int outerColor) { displayData.outerColor = outerColor; }
public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; }
public void setOuterColorEnabled(boolean outerColorEnabled) { displayData.outerColorEnabled = outerColorEnabled; }
public float getOuterColorWidth() { return displayData.outerColorWidth; }
public void setOuterColorWidth(float outerColorWidth) { displayData.outerColorWidth = outerColorWidth; }
public float getOuterColorAlpha() { return displayData.outerColorAlpha; }
public void setOuterColorAlpha(float outerColorAlpha) { displayData.outerColorAlpha = outerColorAlpha; }
public float getRotationSpeed() { return displayData.rotationSpeed; }
public void setRotationSpeed(float rotationSpeed) { displayData.rotationSpeed = rotationSpeed; }
// Shared lightning data
public boolean hasLightningEffect() { return lightningData.lightningEffect; }
public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; }
public float getLightningDensity() { return lightningData.lightningDensity; }
public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; }
public float getLightningRadius() { return lightningData.lightningRadius; }
public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; }
public int getLightningFadeTime() { return lightningData.lightningFadeTime; }
public void setLightningFadeTime(int lightningFadeTime) { lightningData.lightningFadeTime = lightningFadeTime; }
// Anchor - default to projectile 0
public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; }
public void setAnchorPointEnum(AnchorPoint anchorPoint) { projectiles[0].anchor.anchorPoint = anchorPoint; }
public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; }
public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; }
public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; }
public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; }
public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; }
public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; }
@Override
public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); }
@Override
public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
// Indexed API methods
public int getInnerColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.innerColor : displayData.innerColor;
}
public void setInnerColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.innerColor = color;
}
public int getOuterColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.outerColor : displayData.outerColor;
}
public void setOuterColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.outerColor = color;
}
public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); }
public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; }
public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; }
public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; }
private int clampIndex(int index) {
return Math.max(0, Math.min(index, projectileCount - 1));
}
@Override
public int getMaxPreviewDuration() {
return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100;
}
// ═══════════════════════════════════════════════════════════════════
// GUI FIELD DEFINITIONS
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.row(
FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES),
FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay)
.range(0, 200).visibleWhen(() -> projectileCount > 1)
));
defs.add(FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed)
));
defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback));
defs.add(FieldDef.section("ability.section.beam"));
defs.add(FieldDef.row(
FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth),
FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize)
));
defs.add(FieldDef.row(
FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance),
FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime)
));
defs.add(FieldDef.section("ability.section.homing"));
defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming),
FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange).visibleWhen(this::isHoming)
));
defs.add(FieldDef.section("ability.section.explosive"));
defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"));
defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive));
defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects));
// Visual tab - shared primary colors
defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled)
.tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled));
defs.add(FieldDef.row(
FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth)
.visibleWhen(this::isOuterColorEnabled),
FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha)
.range(0, 1).visibleWhen(this::isOuterColorEnabled)
).tab("ability.tab.visual"));
// Visual tab - shared effects
defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual"));
defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect)
.tab("ability.tab.visual"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity)
.visibleWhen(this::hasLightningEffect).range(0.01f, 100f),
FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius)
.range(0.1f, 100f).visibleWhen(this::hasLightningEffect)
).tab("ability.tab.visual"));
// Visual tab - per-projectile sections
for (int i = 0; i < MAX_PROJECTILES; i++) {
final int idx = i;
String sectionKey = "ability.section.projectile" + (i + 1);
defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual")
.visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class,
() -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.row(
FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v),
FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v)
).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
// Color override (only when multiple projectiles)
defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1));
defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
}
}
}
@@ -14,13 +14,13 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityCharge;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityCharge;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -58,17 +58,6 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
this.activeSound = "mob.zombie.attack";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityCharge(this, callback);
}
@Override
public boolean isTargetingModeLocked() {
return true;
@@ -98,11 +87,13 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
}
/**
* Locks the charge direction based on current target position.
* Called once at windup start - direction won't change even if target moves.
* Locks the charge direction. Called once at windup start — direction won't change even if target moves.
* NPC: charges toward aggro target.
* Player: charges in look direction.
*/
private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) {
if (target != null) {
if (!isPlayerCaster(caster) && target != null) {
// NPC: charge toward aggro target
double dx = target.posX - caster.posX;
double dz = target.posZ - caster.posZ;
double len = Math.sqrt(dx * dx + dz * dz);
@@ -113,6 +104,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw));
}
} else {
// Player: charge in look direction
float yaw = (float) Math.toRadians(caster.rotationYaw);
chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw));
}
@@ -149,7 +141,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
if (chargeDirection == null) return;
// Enforce rotation every tick
enforceLockedRotation(caster);
if (!isPreview()) {
enforceLockedRotation(caster);
}
// Calculate distance traveled
double distanceTraveled = Math.sqrt(
@@ -161,12 +155,15 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
if (distanceTraveled >= maxRange) {
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
if (!isPreview()) {
caster.velocityChanged = true;
}
signalCompletion();
return;
}
if (isChargeBlocked(caster)) {
// Block detection (skip in preview - no real world collision)
if (!isPreview() && isChargeBlocked(caster)) {
stopMomentum(caster);
signalCompletion();
return;
@@ -176,10 +173,12 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
caster.motionX = chargeDirection.xCoord * chargeSpeed;
caster.motionY = 0;
caster.motionZ = chargeDirection.zCoord * chargeSpeed;
caster.velocityChanged = true;
if (!isPreview()) {
caster.velocityChanged = true;
}
// Server-side collision damage
if (!world.isRemote) {
// Server-side collision damage (skip in preview)
if (!world.isRemote && !isPreview()) {
AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth);
@SuppressWarnings("unchecked")
@@ -222,7 +221,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
private void stopMomentum(EntityLivingBase caster) {
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
if (!isPreview()) {
caster.velocityChanged = true;
}
}
private boolean isChargeBlocked(EntityLivingBase caster) {
@@ -260,9 +261,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
return null;
}
// Calculate direction to target at this moment (locked)
// NPC: telegraph points toward aggro target
// Player: telegraph points in look direction
float yaw;
if (target != null) {
if (!isPlayerCaster(caster) && target != null) {
double dx = target.posX - caster.posX;
double dz = target.posZ - caster.posZ;
yaw = (float) Math.toDegrees(Math.atan2(-dx, dz));
@@ -288,66 +290,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
return instance;
}
// ==================== PREVIEW MODE ====================
private transient double previewDirX, previewDirZ;
private transient double previewStartX, previewStartZ;
private transient boolean previewCharging = false;
@Override
@SideOnly(Side.CLIENT)
public void onPreviewExecute(EntityNPCInterface npc) {
previewStartX = npc.posX;
previewStartZ = npc.posZ;
previewCharging = false;
// Calculate direction toward fake target
if (previewTarget != null) {
double dx = previewTarget.posX - npc.posX;
double dz = previewTarget.posZ - npc.posZ;
double len = Math.sqrt(dx * dx + dz * dz);
if (len > 0) {
previewDirX = dx / len;
previewDirZ = dz / len;
} else {
float yaw = (float) Math.toRadians(npc.rotationYaw);
previewDirX = -Math.sin(yaw);
previewDirZ = Math.cos(yaw);
}
} else {
float yaw = (float) Math.toRadians(npc.rotationYaw);
previewDirX = -Math.sin(yaw);
previewDirZ = Math.cos(yaw);
}
previewCharging = true;
}
@Override
@SideOnly(Side.CLIENT)
public void onPreviewActiveTick(EntityNPCInterface npc, int tick) {
if (!previewCharging) return;
// Check distance traveled
double distTraveled = Math.sqrt(
Math.pow(npc.posX - previewStartX, 2) +
Math.pow(npc.posZ - previewStartZ, 2)
);
if (distTraveled >= maxRange) {
previewCharging = false;
return;
}
npc.prevPosX = npc.posX;
npc.prevPosY = npc.posY;
npc.prevPosZ = npc.posZ;
npc.posX += previewDirX * chargeSpeed;
npc.posZ += previewDirZ * chargeSpeed;
}
@Override
public int getPreviewActiveDuration() {
public int getMaxPreviewDuration() {
return (int) Math.ceil(maxRange / chargeSpeed) + 5;
}
@@ -405,4 +349,20 @@ public class AbilityCharge extends Ability implements IAbilityCharge {
public void setHitWidth(float hitWidth) {
this.hitWidth = hitWidth;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("ability.chargeSpeed", this::getChargeSpeed, this::setChargeSpeed)
),
FieldDef.row(
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback),
FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth)
),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -1,7 +1,5 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
@@ -11,13 +9,17 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityCutter;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilityCutter;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -31,7 +33,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
public enum SweepMode {
SWIPE,
SPIN
SPIN;
@Override
public String toString() {
switch (this) {
case SWIPE: return "ability.sweep.swipe";
case SPIN: return "ability.sweep.spin";
default: return name();
}
}
}
private float arcAngle = 90.0f;
@@ -61,17 +72,8 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
this.telegraphType = TelegraphType.CONE;
this.windUpSound = "random.bow";
this.activeSound = "random.break";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityCutter(this, callback);
this.windUpAnimationName = "Ability_Cutter_Windup";
this.activeAnimationName = "Ability_Cutter_Active";
}
@Override
@@ -107,32 +109,48 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote) return;
if (world.isRemote && !isPreview()) return;
switch (sweepMode) {
case SWIPE:
float prevRotation = currentRotation;
currentRotation += sweepSpeed;
if (currentRotation > arcAngle / 2.0f) {
signalCompletion(); // Swipe arc complete
if (!isPreview()) {
performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f);
}
signalCompletion();
return;
}
performSweepDamage(caster, world, innerRadius, range, currentRotation);
currentRotation += sweepSpeed;
if (!isPreview()) {
performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation);
}
break;
case SPIN:
if (tick >= spinDurationTicks) {
signalCompletion(); // Spin duration complete
signalCompletion();
return;
}
float prevSpin = currentRotation;
currentRotation = (currentRotation + sweepSpeed) % 360.0f;
hitEntities.clear();
performSweepDamage(caster, world, innerRadius, range, currentRotation);
if (!isPreview()) {
hitEntities.clear();
performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation);
}
break;
}
}
private void performSweepDamage(EntityLivingBase caster, World world, float minDist, float maxDist, float angleOffset) {
float casterYaw = caster.rotationYaw + angleOffset;
/**
* Check for entities between two sweep angles, ensuring no gaps between ticks.
* For SWIPE mode, this covers the continuous arc from startAngle to endAngle.
*/
private void performSweepDamageRange(EntityLivingBase caster, World world, float minDist, float maxDist,
float startAngle, float endAngle) {
// Calculate the angular range covered this tick
float minAngle = Math.min(startAngle, endAngle);
float maxAngle = Math.max(startAngle, endAngle);
AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(
caster.posX - maxDist, caster.posY - 1, caster.posZ - maxDist,
@@ -153,7 +171,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
double dist = Math.sqrt(dx * dx + dz * dz);
if (dist < minDist || dist > maxDist) continue;
if (!isInArc(dx, dz, casterYaw, arcAngle)) continue;
if (!isInSweepRange(dx, dz, caster.rotationYaw, minAngle, maxAngle)) continue;
hitEntities.add(entity.getEntityId());
@@ -170,6 +188,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
}
}
/**
* Check if an entity falls within the angular range between two sweep positions.
* This ensures entities at long range can't slip between tick-gaps.
*/
private boolean isInSweepRange(double dx, double dz, float casterYaw, float minAngle, float maxAngle) {
double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz));
double entityRelative = normalizeAngle(angleToEntity - casterYaw);
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);
@@ -311,4 +339,30 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
public float getCurrentRotation() {
return currentRotation;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("gui.range", this::getRange, this::setRange)
),
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback),
FieldDef.section("ability.section.sweep"),
FieldDef.enumField("ability.sweepMode", SweepMode.class, this::getSweepModeEnum, this::setSweepModeEnum)
.hover("ability.hover.sweepMode"),
FieldDef.row(
FieldDef.floatField("ability.arcAngle", this::getArcAngle, this::setArcAngle),
FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius)
),
FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed),
FieldDef.intField("ability.spinDuration", this::getSpinDurationTicks, this::setSpinDurationTicks)
.range(1, 1000)
.visibleWhen(() -> this.getSweepModeEnum() == SweepMode.SPIN),
FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing)
.hover("ability.hover.piercing"),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -12,13 +12,13 @@ import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityDash;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.api.ability.type.IAbilityDash;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
@@ -32,7 +32,16 @@ public class AbilityDash extends Ability implements IAbilityDash {
*/
public enum DashMode {
AGGRESSIVE,
DEFENSIVE
DEFENSIVE;
@Override
public String toString() {
switch (this) {
case AGGRESSIVE: return "ability.dash.aggressive";
case DEFENSIVE: return "ability.dash.defensive";
default: return name();
}
}
}
/**
@@ -78,12 +87,14 @@ public class AbilityDash extends Ability implements IAbilityDash {
// Type-specific parameters
private DashMode dashMode = DashMode.DEFENSIVE;
private float dashDistance = 4.0f;
private float dashSpeed = 1.5f;
private float dashSpeed = 0.5f;
// Runtime state
private transient Vec3 dashDirection;
private transient double startX, startY, startZ;
private transient double prevTickX, prevTickZ;
private transient DashDirection chosenDirection;
private transient int maxActiveTicks;
public AbilityDash() {
this.typeId = "ability.cnpc.dash";
@@ -102,15 +113,8 @@ public class AbilityDash extends Ability implements IAbilityDash {
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(
IAbilityConfigCallback callback) {
return new SubGuiAbilityDash(this, callback);
public boolean hasDamage() {
return false;
}
@Override
@@ -133,6 +137,11 @@ public class AbilityDash extends Ability implements IAbilityDash {
startX = caster.posX;
startY = caster.posY;
startZ = caster.posZ;
prevTickX = caster.posX;
prevTickZ = caster.posZ;
// Safety timeout: expected ticks + generous buffer to prevent infinite dash
maxActiveTicks = dashSpeed > 0 ? (int)(dashDistance / dashSpeed) + 10 : 10;
// Choose random direction based on mode
DashDirection[] directions = dashMode == DashMode.AGGRESSIVE
@@ -140,9 +149,10 @@ public class AbilityDash extends Ability implements IAbilityDash {
: DEFENSIVE_DIRECTIONS;
chosenDirection = directions[RANDOM.nextInt(directions.length)];
// Calculate dash direction relative to target
// NPC: dash direction is relative to aggro target facing
// Player: dash direction is relative to look direction
float baseYaw;
if (target != null) {
if (!isPlayerCaster(caster) && target != null) {
double dx = target.posX - caster.posX;
double dz = target.posZ - caster.posZ;
baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz));
@@ -160,63 +170,87 @@ public class AbilityDash extends Ability implements IAbilityDash {
Math.cos(yawRad)
);
// Small upward impulse for a skip/hop arc (gravity handles the descent)
caster.motionY = 0.2;
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (dashDirection == null) return;
// Safety timeout or missing state: force-complete to prevent stuck NPC
if (!isPreview() && (dashDirection == null || tick > maxActiveTicks)) {
stopDash(caster);
signalCompletion();
return;
}
// Calculate distance traveled
double distanceTraveled = Math.sqrt(
Math.pow(caster.posX - startX, 2) +
Math.pow(caster.posZ - startZ, 2)
);
if (dashDirection == null) {
signalCompletion();
return;
}
// Stall detection: if entity hasn't moved since last tick, it's stuck against a wall
if (!isPreview() && tick > 1) {
double dx = caster.posX - prevTickX;
double dz = caster.posZ - prevTickZ;
if (dx * dx + dz * dz < 0.0001) {
stopDash(caster);
signalCompletion();
return;
}
}
prevTickX = caster.posX;
prevTickZ = caster.posZ;
// Check if reached max distance
if (distanceTraveled >= dashDistance) {
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
double travelDx = caster.posX - startX;
double travelDz = caster.posZ - startZ;
if (travelDx * travelDx + travelDz * travelDz >= (double) dashDistance * dashDistance) {
stopDash(caster);
signalCompletion();
return;
}
if (isDashBlocked(caster)) {
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
// Block detection (skip in preview - no real world collision)
if (!isPreview() && isDashBlocked(caster)) {
stopDash(caster);
signalCompletion();
return;
}
// Move caster
// Move caster (motionY left to gravity for skip arc)
caster.motionX = dashDirection.xCoord * dashSpeed;
caster.motionY = 0;
caster.motionZ = dashDirection.zCoord * dashSpeed;
caster.velocityChanged = true;
if (!isPreview()) {
caster.velocityChanged = true;
// Trail particles
world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0);
// Trail particles
world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0);
}
}
private void stopDash(EntityLivingBase caster) {
caster.motionX = 0;
caster.motionZ = 0;
if (!isPreview()) {
caster.velocityChanged = true;
}
}
@Override
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
stopDash(caster);
}
@Override
public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) {
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
stopDash(caster);
}
@Override
public void cleanup() {
dashDirection = null;
chosenDirection = null;
maxActiveTicks = 0;
}
private boolean isDashBlocked(EntityLivingBase caster) {
@@ -226,66 +260,8 @@ public class AbilityDash extends Ability implements IAbilityDash {
return !caster.worldObj.getCollidingBoundingBoxes(caster, caster.boundingBox.copy().offset(nextX, 0, nextZ)).isEmpty();
}
// ==================== PREVIEW MODE ====================
private transient double previewDirX, previewDirZ;
private transient double previewStartX, previewStartZ;
private transient boolean previewDashing = false;
@Override
@SideOnly(Side.CLIENT)
public void onPreviewExecute(EntityNPCInterface npc) {
previewStartX = npc.posX;
previewStartZ = npc.posZ;
previewDashing = false;
// Pick a random direction based on mode
DashDirection[] directions = dashMode == DashMode.AGGRESSIVE
? AGGRESSIVE_DIRECTIONS
: DEFENSIVE_DIRECTIONS;
DashDirection dir = directions[RANDOM.nextInt(directions.length)];
float baseYaw;
if (previewTarget != null) {
double dx = previewTarget.posX - npc.posX;
double dz = previewTarget.posZ - npc.posZ;
baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz));
} else {
baseYaw = npc.rotationYaw;
}
float dashYaw = baseYaw + dir.getAngleOffset();
float yawRad = (float) Math.toRadians(dashYaw);
previewDirX = -Math.sin(yawRad);
previewDirZ = Math.cos(yawRad);
previewDashing = true;
}
@Override
@SideOnly(Side.CLIENT)
public void onPreviewActiveTick(EntityNPCInterface npc, int tick) {
if (!previewDashing) return;
double distTraveled = Math.sqrt(
Math.pow(npc.posX - previewStartX, 2) +
Math.pow(npc.posZ - previewStartZ, 2)
);
if (distTraveled >= dashDistance) {
previewDashing = false;
return;
}
npc.prevPosX = npc.posX;
npc.prevPosY = npc.posY;
npc.prevPosZ = npc.posZ;
npc.posX += previewDirX * dashSpeed;
npc.posZ += previewDirZ * dashSpeed;
}
@Override
public int getPreviewActiveDuration() {
public int getMaxPreviewDuration() {
return (int) Math.ceil(dashDistance / dashSpeed) + 5;
}
@@ -309,7 +285,7 @@ public class AbilityDash extends Ability implements IAbilityDash {
this.dashMode = DashMode.DEFENSIVE;
}
this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f;
this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 1.5f;
this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 0.5f;
}
// Getters & Setters
@@ -351,4 +327,17 @@ public class AbilityDash extends Ability implements IAbilityDash {
public DashDirection getChosenDirection() {
return chosenDirection;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.enumField("ability.dashMode", DashMode.class, this::getDashModeEnum, this::setDashModeEnum)
.hover("ability.hover.dashMode"),
FieldDef.row(
FieldDef.floatField("ability.dashDistance", this::getDashDistance, this::setDashDistance),
FieldDef.floatField("ability.dashSpeed", this::getDashSpeed, this::setDashSpeed)
)
));
}
}
@@ -12,41 +12,55 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityDisc;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityDisc;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.Arrays;
import java.util.List;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
/**
* Disc ability: Spawns a flat spinning disc projectile.
* Supports 1-8 projectiles with shared visuals and per-projectile anchor points.
* Has optional boomerang behavior to return to owner.
*/
public class AbilityDisc extends Ability implements IAbilityDisc {
// Disc geometry
private static final int MAX_PROJECTILES = 8;
// Disc geometry (shared)
private float discRadius = 1.0f;
private float discThickness = 0.2f;
private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward)
// Boomerang properties
// Boomerang properties (shared)
private boolean boomerang = false;
private int boomerangDelay = 40;
// Energy data classes
private EnergyColorData colorData = new EnergyColorData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f);
private EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f);
private EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200);
private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND);
// Projectile count and fire stagger
private int projectileCount = 1;
private int fireDelay = 0;
// Transient state for disc entity (used during windup charging)
private transient EntityAbilityDisc discEntity = null;
// Shared visual data (all projectiles use these)
private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
// Shared combat/movement data
private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f);
private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f);
private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200);
// Per-projectile data (anchor + optional color override)
private ProjectileData[] projectiles;
// Transient entity state
private transient EntityAbilityDisc[] discEntities;
public AbilityDisc() {
this.typeId = "ability.cnpc.disc";
@@ -59,20 +73,90 @@ public class AbilityDisc extends Ability implements IAbilityDisc {
this.lockMovement = LockMovementType.WINDUP;
this.telegraphType = TelegraphType.CIRCLE;
this.showTelegraph = true;
// Default built-in animations
this.windUpAnimationName = "Ability_Disc_Windup";
this.activeAnimationName = "Ability_Disc_Active";
initProjectiles(1);
}
private void initProjectiles(int count) {
this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
this.projectiles = new ProjectileData[projectileCount];
for (int i = 0; i < projectileCount; i++) {
projectiles[i] = new ProjectileData(getDefaultAnchor(i));
}
}
/**
* Disc anchor order is REVERSED from Orb/Beam: [0]=LEFT_HAND, [1]=RIGHT_HAND
*/
private AnchorPoint getDefaultAnchor(int index) {
switch (index) {
case 0: return AnchorPoint.RIGHT_HAND;
case 1: return AnchorPoint.LEFT_HAND;
default: return AnchorPoint.FRONT;
}
}
public void setProjectileCount(int count) {
int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
if (newCount == projectileCount) return;
ProjectileData[] oldProjectiles = projectiles;
initProjectiles(newCount);
if (oldProjectiles != null) {
int copyCount = Math.min(oldProjectiles.length, newCount);
for (int i = 0; i < copyCount; i++) {
if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i];
}
}
}
public int getProjectileCount() {
return projectileCount;
}
public int getFireDelay() {
return fireDelay;
}
public void setFireDelay(int delay) {
this.fireDelay = Math.max(0, delay);
}
// Legacy compat
public int getDualFireDelay() { return fireDelay; }
public void setDualFireDelay(int delay) { setFireDelay(delay); }
@Override
public List<AbilityVariant> getVariants() {
return Arrays.asList(
new AbilityVariant("ability.variant.single", a -> {
a.setName("Disc");
}),
new AbilityVariant("ability.variant.dual", a -> {
AbilityDisc disc = (AbilityDisc) a;
a.setName("Dual Disc");
disc.setProjectileCount(2);
disc.setFireDelay(10);
// Set color override for second disc
disc.projectiles[1].colorOverride = true;
disc.projectiles[1].innerColor = 0xFFFFFF;
disc.projectiles[1].outerColor = 0x8800FF;
a.setWindUpAnimationName("Ability_DiscDual_Windup");
a.setActiveAnimationName("Ability_DiscDual_Active");
})
);
}
@Override
public boolean hasTypeSettings() {
public boolean allowOverlap() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityDisc(this, callback);
public boolean isReadyForBurstCompletion(int activeTick) {
return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1);
}
@Override
@@ -85,48 +169,115 @@ public class AbilityDisc extends Ability implements IAbilityDisc {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) {
signalCompletion();
return;
/**
* Create disc entities.
* NPC: target is the aggro target — discs will home toward it.
* Player: target is null — discs fire in caster's look direction.
*/
private EntityAbilityDisc[] createDiscEntities(EntityLivingBase caster, EntityLivingBase target, World world) {
EntityAbilityDisc[] entities = new EntityAbilityDisc[projectileCount];
for (int i = 0; i < projectileCount; i++) {
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor);
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
entities[i] = new EntityAbilityDisc(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
discRadius, discThickness,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData,
boomerang, boomerangDelay);
entities[i].setEffects(this.effects);
entities[i].setSourceAbility(this);
}
// Start moving the disc that was spawned during windup
if (discEntity != null && !discEntity.isDead) {
discEntity.startMoving(target);
if (projectileCount == 2 && entities[0] != null && entities[1] != null) {
entities[0].setSiblingEntityId(entities[1].getEntityId());
entities[1].setSiblingEntityId(entities[0].getEntityId());
}
return entities;
}
// Ability stays active until entity dies (prevents firing another while projectile is alive)
// Movement locking is handled separately by the base class
private void fireDiscEntity(EntityAbilityDisc disc, EntityLivingBase target) {
if (disc == null || disc.isDead) return;
if (isPreview()) {
disc.startPreviewFiring();
} else {
disc.startMoving(target);
}
}
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote) return;
if (world.isRemote && !isPreview()) return;
// Spawn disc in charging mode on first tick of windup
if (tick == 1) {
// Create disc in charging mode - follows caster based on anchor point during windup
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData);
discEntity = new EntityAbilityDisc(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
discRadius, discThickness,
colorData, combatData, homingData, lightningData, lifespanData,
boomerang, boomerangDelay);
discEntity.setupCharging(anchorData, windUpTicks);
discEntities = createDiscEntities(caster, target, world);
for (int i = 0; i < projectileCount; i++) {
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
if (isPreview()) {
discEntities[i].setupPreview(caster, discRadius, discThickness, resolved, lightningData, projectiles[i].anchor, windUpTicks, vertical);
} else {
discEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, vertical);
}
spawnAbilityEntity(world, discEntities[i]);
}
}
}
discEntity.setEffects(this.effects);
world.spawnEntityInWorld(discEntity);
@Override
public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) {
discEntities = createDiscEntities(caster, target, world);
for (EntityAbilityDisc disc : discEntities) {
spawnAbilityEntity(world, disc);
}
for (EntityAbilityDisc disc : discEntities) {
fireDiscEntity(disc, target);
}
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
if (discEntities == null) return;
// Fire first projectile immediately
fireDiscEntity(discEntities[0], target);
// Fire remaining projectiles if no delay
if (fireDelay <= 0) {
for (int i = 1; i < projectileCount; i++) {
fireDiscEntity(discEntities[i], target);
}
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Signal completion when entity dies
if (discEntity == null || discEntity.isDead) {
discEntity = null;
if (discEntities == null) {
signalCompletion();
return;
}
// Fire staggered projectiles
if (fireDelay > 0) {
for (int i = 1; i < projectileCount; i++) {
if (tick == fireDelay * i) {
fireDiscEntity(discEntities[i], target);
}
}
}
// Check if all entities are dead
boolean allDead = true;
for (EntityAbilityDisc disc : discEntities) {
if (disc != null && !disc.isDead) {
allDead = false;
break;
}
}
if (allDead) {
signalCompletion();
}
}
@@ -135,18 +286,29 @@ public class AbilityDisc extends Ability implements IAbilityDisc {
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
}
@Override
public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) {
cleanup();
}
@Override
public void cleanup() {
// Despawn disc entity if still alive
if (discEntity != null && !discEntity.isDead) {
discEntity.setDead();
if (discEntities != null) {
for (int i = 0; i < discEntities.length; i++) {
if (discEntities[i] != null && !discEntities[i].isDead) {
discEntities[i].setDead();
}
discEntities[i] = null;
}
}
discEntity = null;
discEntities = null;
}
@Override
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) {
// NPC: telegraph on aggro target position
// Player: no telegraph (discs fire in look direction, no fixed position to mark)
if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) {
return null;
}
@@ -175,108 +337,336 @@ public class AbilityDisc extends Ability implements IAbilityDisc {
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("discRadius", discRadius);
nbt.setFloat("discThickness", discThickness);
nbt.setBoolean("vertical", vertical);
nbt.setBoolean("boomerang", boomerang);
nbt.setInteger("boomerangDelay", boomerangDelay);
anchorData.writeNBT(nbt);
colorData.writeNBT(nbt);
nbt.setInteger("projectileCount", projectileCount);
nbt.setInteger("fireDelay", fireDelay);
// Shared visual data
displayData.writeNBT(nbt);
lightningData.writeNBT(nbt);
// Shared combat/movement data
combatData.writeNBT(nbt);
homingData.writeNBT(nbt);
lightningData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
// Per-projectile data
for (int i = 0; i < projectileCount; i++) {
NBTTagCompound projNbt = new NBTTagCompound();
projectiles[i].writeNBT(projNbt);
nbt.setTag("Projectile_" + i, projNbt);
}
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f;
this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f;
this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical");
this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang");
this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40;
anchorData.readNBT(nbt);
colorData.readNBT(nbt);
int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1;
initProjectiles(count);
// Read fireDelay with fallback to old dualFireDelay key
if (nbt.hasKey("fireDelay")) {
this.fireDelay = nbt.getInteger("fireDelay");
} else if (nbt.hasKey("dualFireDelay")) {
this.fireDelay = nbt.getInteger("dualFireDelay");
} else {
this.fireDelay = 0;
}
// Shared combat/movement data
combatData.readNBT(nbt);
homingData.readNBT(nbt);
lightningData.readNBT(nbt);
lifespanData.readNBT(nbt);
// Determine format and read accordingly
if (nbt.hasKey("Projectile_0")) {
NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0");
if (proj0.hasKey("colorOverride")) {
// NEW format: shared visuals at root + ProjectileData per projectile
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
for (int i = 0; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i));
}
}
} else {
// OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i)
// Read primary visuals from Projectile_0
displayData.readNBT(proj0);
lightningData.readNBT(proj0);
projectiles[0].anchor.readNBT(proj0);
// Read remaining projectiles, set color override if colors differ
for (int i = 1; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i);
projectiles[i].anchor.readNBT(projNbt);
// Check if this projectile had different colors
EnergyDisplayData tempDisplay = new EnergyDisplayData();
tempDisplay.readNBT(projNbt);
if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) {
projectiles[i].colorOverride = true;
projectiles[i].innerColor = tempDisplay.innerColor;
projectiles[i].outerColor = tempDisplay.outerColor;
}
}
}
}
} else {
// LEGACY flat format: all data at root level
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
projectiles[0].anchor.readNBT(nbt);
}
}
// Getters & Setters
// ═══════════════════════════════════════════════════════════════════
// API GETTERS & SETTERS
// ═══════════════════════════════════════════════════════════════════
public float getSpeed() { return homingData.speed; }
public void setSpeed(float speed) { homingData.speed = speed; }
public float getDiscRadius() { return discRadius; }
public void setDiscRadius(float discRadius) { this.discRadius = discRadius; }
public float getDiscThickness() { return discThickness; }
public void setDiscThickness(float discThickness) { this.discThickness = discThickness; }
public float getMaxDistance() { return lifespanData.maxDistance; }
public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; }
public int getMaxLifetime() { return lifespanData.maxLifetime; }
public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; }
public float getDamage() { return combatData.damage; }
public void setDamage(float damage) { combatData.damage = damage; }
public float getKnockback() { return combatData.knockback; }
public void setKnockback(float knockback) { combatData.knockback = knockback; }
public float getKnockbackUp() { return combatData.knockbackUp; }
public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; }
public boolean isHoming() { return homingData.homing; }
public void setHoming(boolean homing) { homingData.homing = homing; }
public float getHomingStrength() { return homingData.homingStrength; }
public void setHomingStrength(float homingStrength) { homingData.homingStrength = homingStrength; }
public float getHomingRange() { return homingData.homingRange; }
public void setHomingRange(float homingRange) { homingData.homingRange = homingRange; }
public boolean isVertical() { return vertical; }
public void setVertical(boolean vertical) { this.vertical = vertical; }
public boolean isBoomerang() { return boomerang; }
public void setBoomerang(boolean boomerang) { this.boomerang = boomerang; }
public int getBoomerangDelay() { return boomerangDelay; }
public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; }
public float getMaxDistance() { return lifespanData.maxDistance; }
public void setMaxDistance(float d) { lifespanData.maxDistance = d; }
public int getMaxLifetime() { return lifespanData.maxLifetime; }
public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; }
public float getDamage() { return combatData.damage; }
public void setDamage(float d) { combatData.damage = d; }
public float getKnockback() { return combatData.knockback; }
public void setKnockback(float k) { combatData.knockback = k; }
public float getKnockbackUp() { return combatData.knockbackUp; }
public void setKnockbackUp(float k) { combatData.knockbackUp = k; }
public boolean isHoming() { return homingData.homing; }
public void setHoming(boolean h) { homingData.homing = h; }
public float getHomingStrength() { return homingData.homingStrength; }
public void setHomingStrength(float s) { homingData.homingStrength = s; }
public float getHomingRange() { return homingData.homingRange; }
public void setHomingRange(float r) { homingData.homingRange = r; }
public boolean isExplosive() { return combatData.explosive; }
public void setExplosive(boolean explosive) { combatData.explosive = explosive; }
public void setExplosive(boolean e) { combatData.explosive = e; }
public float getExplosionRadius() { return combatData.explosionRadius; }
public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; }
public void setExplosionRadius(float r) { combatData.explosionRadius = r; }
public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; }
public void setExplosionDamageFalloff(float explosionDamageFalloff) { combatData.explosionDamageFalloff = explosionDamageFalloff; }
public int getInnerColor() { return colorData.innerColor; }
public void setInnerColor(int innerColor) { colorData.innerColor = innerColor; }
public int getOuterColor() { return colorData.outerColor; }
public void setOuterColor(int outerColor) { colorData.outerColor = outerColor; }
public float getOuterColorWidth() { return colorData.outerColorWidth; }
public void setOuterColorWidth(float outerColorWidth) { colorData.outerColorWidth = outerColorWidth; }
public float getOuterColorAlpha() { return colorData.outerColorAlpha; }
public void setOuterColorAlpha(float outerColorAlpha) { colorData.outerColorAlpha = outerColorAlpha; }
public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; }
public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; }
public float getRotationSpeed() { return colorData.rotationSpeed; }
public void setRotationSpeed(float rotationSpeed) { colorData.rotationSpeed = rotationSpeed; }
public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; }
// Shared display data (primary colors)
public int getInnerColor() { return displayData.innerColor; }
public void setInnerColor(int c) { displayData.innerColor = c; }
public int getOuterColor() { return displayData.outerColor; }
public void setOuterColor(int c) { displayData.outerColor = c; }
public float getOuterColorWidth() { return displayData.outerColorWidth; }
public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; }
public float getOuterColorAlpha() { return displayData.outerColorAlpha; }
public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; }
public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; }
public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; }
public float getRotationSpeed() { return displayData.rotationSpeed; }
public void setRotationSpeed(float s) { displayData.rotationSpeed = s; }
// Shared lightning data
public boolean hasLightningEffect() { return lightningData.lightningEffect; }
public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; }
public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; }
public float getLightningDensity() { return lightningData.lightningDensity; }
public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; }
public void setLightningDensity(float d) { lightningData.lightningDensity = d; }
public float getLightningRadius() { return lightningData.lightningRadius; }
public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; }
public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; }
public float getAnchorOffsetX() { return anchorData.anchorOffsetX; }
public float getAnchorOffsetY() { return anchorData.anchorOffsetY; }
public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; }
public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; }
public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; }
public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; }
public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; }
public void setLightningRadius(float r) { lightningData.lightningRadius = r; }
public int getLightningFadeTime() { return lightningData.lightningFadeTime; }
public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; }
// Anchor - default to projectile 0
public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; }
public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; }
public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; }
public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; }
public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; }
public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; }
public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; }
public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; }
@Override
public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); }
public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); }
@Override
public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); }
public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
@Override
@SideOnly(Side.CLIENT)
public Entity createPreviewEntity(EntityNPCInterface npc) {
if (npc == null || npc.worldObj == null) return null;
// Indexed API methods
public int getInnerColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.innerColor : displayData.innerColor;
}
public void setInnerColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.innerColor = color;
}
EntityAbilityDisc disc = new EntityAbilityDisc(npc.worldObj);
disc.setupPreview(npc, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks);
return disc;
public int getOuterColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.outerColor : displayData.outerColor;
}
public void setOuterColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.outerColor = color;
}
public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); }
public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; }
public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; }
public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; }
private int clampIndex(int index) {
return Math.max(0, Math.min(index, projectileCount - 1));
}
@Override
public int getPreviewActiveDuration() {
public int getMaxPreviewDuration() {
return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100;
}
// ═══════════════════════════════════════════════════════════════════
// GUI FIELD DEFINITIONS
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
// Type tab - projectile count and fire delay
defs.add(FieldDef.row(
FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES),
FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay)
.range(0, 200).visibleWhen(() -> projectileCount > 1)
));
// Type tab - disc properties
defs.add(FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed)
));
defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback));
defs.add(FieldDef.section("ability.section.disc"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius),
FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness)
));
defs.add(FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical)
.hover("ability.hover.vertical"));
defs.add(FieldDef.row(
FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance),
FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime)
));
defs.add(FieldDef.section("ability.section.homing"));
defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"));
defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming));
defs.add(FieldDef.section("ability.section.boomerang"));
defs.add(FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang).hover("ability.hover.boomerang"));
defs.add(FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay).visibleWhen(this::isBoomerang));
defs.add(FieldDef.section("ability.section.explosive"));
defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"));
defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive));
defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects));
// Visual tab - shared primary colors
defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled)
.tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled));
defs.add(FieldDef.row(
FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth)
.visibleWhen(this::isOuterColorEnabled),
FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha)
.range(0, 1).visibleWhen(this::isOuterColorEnabled)
).tab("ability.tab.visual"));
// Visual tab - shared effects
defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual"));
defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect)
.tab("ability.tab.visual"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity)
.visibleWhen(this::hasLightningEffect).range(0.01f, 100f),
FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius)
.range(0.1f, 100f).visibleWhen(this::hasLightningEffect)
).tab("ability.tab.visual"));
// Visual tab - per-projectile sections
for (int i = 0; i < MAX_PROJECTILES; i++) {
final int idx = i;
String sectionKey = "ability.section.projectile" + (i + 1);
defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual")
.visibleWhen(() -> idx < projectileCount));
// Anchor point
defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class,
() -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.row(
FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v),
FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v)
).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
// Color override (only when multiple projectiles)
defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1));
defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
}
}
}
@@ -1,285 +0,0 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityEnergyBeam;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.api.ability.type.IAbilityEnergyBeam;
import noppes.npcs.entity.EntityNPCInterface;
/**
* Energy Beam ability: A homing head with a trailing path.
* The beam stays attached to the origin and curves as it homes in on target.
* Cannot cross over itself (self-intersection prevention).
*/
public class AbilityEnergyBeam extends Ability implements IAbilityEnergyBeam {
// Shape properties (standalone)
private float beamWidth = 0.4f;
private float headSize = 0.6f;
// Data classes
private EnergyColorData colorData = new EnergyColorData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f);
private EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f);
private EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200);
private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND);
// Transient state for beam entity (used during windup charging)
private transient EntityAbilityBeam beamEntity = null;
public AbilityEnergyBeam() {
this.typeId = "ability.cnpc.beam";
this.name = "Beam";
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.maxRange = 20.0f;
this.minRange = 5.0f;
this.cooldownTicks = 0;
this.windUpTicks = 40;
this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE;
this.telegraphType = TelegraphType.CIRCLE;
this.showTelegraph = true;
// Default built-in animations
this.windUpAnimationName = "Ability_Beam_Windup";
this.activeAnimationName = "Ability_Beam_Active";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityEnergyBeam(this, callback);
}
@Override
public boolean isTargetingModeLocked() {
return true;
}
@Override
public TargetingMode[] getAllowedTargetingModes() {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) {
signalCompletion();
return;
}
// Start firing the beam that was spawned during windup
if (beamEntity != null && !beamEntity.isDead) {
beamEntity.startFiring(target);
}
// Ability stays active until entity dies (prevents firing another while projectile is alive)
// Movement locking is handled separately by the base class
}
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote) return;
// Spawn beam in charging mode on first tick of windup
if (tick == 1) {
float offsetDist = 1.0f;
// Create beam in charging mode - follows caster based on anchor point during windup
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData, offsetDist);
beamEntity = new EntityAbilityBeam(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
beamWidth, headSize,
colorData, combatData, homingData, lightningData, lifespanData,
lockMovement.locksActive());
beamEntity.setupCharging(anchorData, windUpTicks, offsetDist);
beamEntity.setEffects(this.effects);
world.spawnEntityInWorld(beamEntity);
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Signal completion when entity dies
if (beamEntity == null || beamEntity.isDead) {
beamEntity = null;
signalCompletion();
}
}
@Override
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
}
@Override
public void cleanup() {
// Despawn beam entity if still alive
if (beamEntity != null && !beamEntity.isDead) {
beamEntity.setDead();
}
beamEntity = null;
}
@Override
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) {
return null;
}
// Create circle telegraph at target position
Telegraph telegraph = Telegraph.circle(headSize * 2.0f);
telegraph.setDurationTicks(windUpTicks);
telegraph.setColor(windUpColor);
telegraph.setWarningColor(activeColor);
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
// Position at target and follow target during windup
TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(target.getEntityId());
return instance;
}
@Override
public float getTelegraphRadius() {
return headSize * 2.0f;
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("beamWidth", beamWidth);
nbt.setFloat("headSize", headSize);
anchorData.writeNBT(nbt);
colorData.writeNBT(nbt);
combatData.writeNBT(nbt);
homingData.writeNBT(nbt);
lightningData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f;
this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f;
anchorData.readNBT(nbt);
colorData.readNBT(nbt);
combatData.readNBT(nbt);
homingData.readNBT(nbt);
lightningData.readNBT(nbt);
lifespanData.readNBT(nbt);
}
// Getters & Setters - Standalone fields
public float getBeamWidth() { return beamWidth; }
public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; }
public float getHeadSize() { return headSize; }
public void setHeadSize(float headSize) { this.headSize = headSize; }
// Getters & Setters - Color data
public int getInnerColor() { return colorData.innerColor; }
public void setInnerColor(int innerColor) { this.colorData.innerColor = innerColor; }
public int getOuterColor() { return colorData.outerColor; }
public void setOuterColor(int outerColor) { this.colorData.outerColor = outerColor; }
public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; }
public void setOuterColorEnabled(boolean outerColorEnabled) { this.colorData.outerColorEnabled = outerColorEnabled; }
public float getOuterColorWidth() { return colorData.outerColorWidth; }
public void setOuterColorWidth(float outerColorWidth) { this.colorData.outerColorWidth = outerColorWidth; }
public float getOuterColorAlpha() { return colorData.outerColorAlpha; }
public void setOuterColorAlpha(float outerColorAlpha) { this.colorData.outerColorAlpha = outerColorAlpha; }
public float getRotationSpeed() { return colorData.rotationSpeed; }
public void setRotationSpeed(float rotationSpeed) { this.colorData.rotationSpeed = rotationSpeed; }
// Getters & Setters - Combat data
public float getDamage() { return combatData.damage; }
public void setDamage(float damage) { this.combatData.damage = damage; }
public float getKnockback() { return combatData.knockback; }
public void setKnockback(float knockback) { this.combatData.knockback = knockback; }
public float getKnockbackUp() { return combatData.knockbackUp; }
public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; }
public boolean isExplosive() { return combatData.explosive; }
public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; }
public float getExplosionRadius() { return combatData.explosionRadius; }
public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; }
public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; }
public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; }
// Getters & Setters - Homing data
public float getSpeed() { return homingData.speed; }
public void setSpeed(float speed) { this.homingData.speed = speed; }
public boolean isHoming() { return homingData.homing; }
public void setHoming(boolean homing) { this.homingData.homing = homing; }
public float getHomingStrength() { return homingData.homingStrength; }
public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; }
public float getHomingRange() { return homingData.homingRange; }
public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; }
// Getters & Setters - Lightning data
public boolean hasLightningEffect() { return lightningData.lightningEffect; }
public void setLightningEffect(boolean lightningEffect) { this.lightningData.lightningEffect = lightningEffect; }
public float getLightningDensity() { return lightningData.lightningDensity; }
public void setLightningDensity(float lightningDensity) { this.lightningData.lightningDensity = lightningDensity; }
public float getLightningRadius() { return lightningData.lightningRadius; }
public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; }
// Getters & Setters - Lifespan data
public float getMaxDistance() { return lifespanData.maxDistance; }
public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; }
public int getMaxLifetime() { return lifespanData.maxLifetime; }
public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; }
// Getters & Setters - Anchor point
public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; }
public float getAnchorOffsetX() { return anchorData.anchorOffsetX; }
public float getAnchorOffsetY() { return anchorData.anchorOffsetY; }
public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; }
public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; }
public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; }
public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; }
public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; }
@Override
public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); }
@Override
public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); }
@Override
@SideOnly(Side.CLIENT)
public Entity createPreviewEntity(EntityNPCInterface npc) {
if (npc == null || npc.worldObj == null) return null;
EntityAbilityBeam beam = new EntityAbilityBeam(npc.worldObj);
beam.setupPreview(npc, beamWidth, headSize, colorData, lightningData, anchorData, windUpTicks, 1.0f);
return beam;
}
@Override
public int getPreviewActiveDuration() {
return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100;
}
}
@@ -1,24 +1,29 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.ability.*;
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.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityGuard;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.api.handler.data.IAnimation;
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.api.ability.type.IAbilityGuard;
import java.util.Random;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import noppes.npcs.util.ValueUtil;
import java.util.Arrays;
import java.util.List;
/**
* Guard ability: Defensive stance that reduces incoming damage.
@@ -26,54 +31,62 @@ import java.util.Random;
*/
public class AbilityGuard extends Ability implements IAbilityGuard {
private static final Random RANDOM = new Random();
// Type-specific parameters
private int durationTicks = 60;
private float damageReduction = 0.5f;
private boolean canCounter = false;
private CounterType counterType = CounterType.FLAT;
private AbilityGuard.CounterType counterType = AbilityGuard.CounterType.FLAT;
private float counterValue = 6.0f;
private float counterChance = 0.3f;
private String counterSound = "random.wood_click";
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 enum CounterType {
FLAT,
PERCENT
}
public AbilityGuard() {
this.typeId = "ability.cnpc.guard";
this.name = "Guard";
this.targetingMode = TargetingMode.SELF;
this.lockMovement = LockMovementType.ACTIVE;
this.cooldownTicks = 0;
this.windUpTicks = 10;
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.windUpSound = "random.anvil_use";
this.activeSound = "random.anvil_land";
this.allowedBy = UserType.NPC_ONLY;
this.activeSound = "random.anvil_use";
this.allowedBy = UserType.BOTH;
this.activeAnimationName = "Ability_Guard_Active";
this.counterAnimationName = "Ability_Guard_Counter";
}
@Override
public boolean hasTypeSettings() {
return true;
public boolean hasDamage() {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(
IAbilityConfigCallback callback) {
return new SubGuiAbilityGuard(this, callback);
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
@@ -91,41 +104,56 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
lastAttacker = null;
counterTriggered = false;
lastDamageTaken = 0.0f;
counterEligible = true;
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Counter attack logic if triggered
if (canCounter && counterTriggered && lastAttacker != null && !world.isRemote) {
if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !world.isRemote) {
performCounter(caster, world);
}
// Check if guard duration has ended
if (tick > counterWindow && counterEligible) {
counterEligible = false;
}
if (tick >= durationTicks) {
signalCompletion();
}
// Just enough to see the counter animation
if (counterTriggered && tick >= counterWindow + 10) {
signalCompletion();
}
}
/**
* Called externally when the caster takes damage while guarding.
* This should be called from the damage handling code.
*
* @param attacker The entity that attacked
* @param damage The damage amount (after reduction)
*/
public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) {
if (!canCounter || attacker == null) return;
if (!isDirectHit(source)) return;
if (RANDOM.nextFloat() >= counterChance) return;
if (!isGuarding() || attacker == null) return;
lastAttacker = attacker;
lastDamageTaken = damage;
counterTriggered = true;
// Counter will be performed in onActiveTick - don't self-interrupt
float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage);
float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth());
caster.setHealth(newHealth);
if (!canCounter || !counterEligible || counterTriggered || !isDirectHit(source)) {
caster.setHealth(newHealth);
} else {
caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth()));
counterTriggered = true;
}
}
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 == CounterType.PERCENT
float counterDamage = counterType == AbilityGuard.CounterType.PERCENT
? lastDamageTaken * (counterValue / 100.0f)
: counterValue;
@@ -135,18 +163,32 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
}
// Use shared animation utility - only available for NPCs
if (caster instanceof EntityNPCInterface) {
((EntityNPCInterface) caster).abilities.playAbilityAnimation(counterAnimationId);
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());
}
}
counterTriggered = false;
counterEligible = false;
lastAttacker = null;
lastDamageTaken = 0.0f;
}
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 IAnimation getCounterAnimation() {
if (AnimationController.Instance == null) return null;
if (counterAnimationId > 0) {
return AnimationController.Instance.get(counterAnimationId);
}
if (!counterAnimationName.isEmpty()) {
return AnimationController.Instance.get(counterAnimationName, true);
}
return null;
}
/**
@@ -154,7 +196,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
* Returns 0.5 for 50% reduction.
*/
public float getDamageReductionFactor() {
if (isExecuting() && getPhase() == kamkeel.npcs.controllers.data.ability.AbilityPhase.ACTIVE) {
if (isExecuting() && getPhase() == AbilityPhase.ACTIVE) {
return damageReduction;
}
return 0.0f;
@@ -164,7 +206,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
* Check if the caster is currently in guard stance.
*/
public boolean isGuarding() {
return isExecuting() && getPhase() == kamkeel.npcs.controllers.data.ability.AbilityPhase.ACTIVE;
return isExecuting() && getPhase() == AbilityPhase.ACTIVE;
}
@Override
@@ -185,11 +227,12 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
nbt.setInteger("durationTicks", durationTicks);
nbt.setFloat("damageReduction", damageReduction);
nbt.setBoolean("canCounter", canCounter);
nbt.setInteger("counterWindow", counterWindow);
nbt.setString("counterType", counterType.name());
nbt.setFloat("counterValue", counterValue);
nbt.setFloat("counterChance", counterChance);
nbt.setString("counterSound", counterSound);
nbt.setInteger("counterAnimationId", counterAnimationId);
nbt.setString("counterAnimationName", counterAnimationName);
}
@Override
@@ -197,6 +240,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60;
this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f;
this.canCounter = nbt.hasKey("canCounter") && nbt.getBoolean("canCounter");
this.counterWindow = nbt.hasKey("counterWindow") ? nbt.getInteger("counterWindow") : 10;
try {
this.counterType = CounterType.valueOf(nbt.getString("counterType"));
} catch (Exception e) {
@@ -209,9 +253,11 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
} else {
this.counterValue = 6.0f;
}
this.counterChance = nbt.hasKey("counterChance") ? nbt.getFloat("counterChance") : 0.3f;
this.counterSound = nbt.hasKey("counterSound") ? nbt.getString("counterSound") : "random.wood_click";
this.counterAnimationId = nbt.hasKey("counterAnimationId") ? nbt.getInteger("counterAnimationId") : -1;
this.counterAnimationName = nbt.hasKey("counterAnimationName") ?
nbt.getString("counterAnimationName") :
"Ability_Guard_Counter";
}
// Getters & Setters
@@ -223,17 +269,26 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
this.durationTicks = Math.max(1, durationTicks);
}
@Override
public int getCounterWindow() {
return this.counterWindow;
}
@Override
public void setCounterWindow(int ticks) {
this.counterWindow = Math.min(durationTicks, ticks);
}
@Override
public float getDamageReduction() {
return damageReduction;
}
@Override
public void setDamageReduction(float damageReduction) {
this.damageReduction = damageReduction;
}
public boolean isCanCounter() {
return canCounter;
}
@Override
public boolean canCounter() {
@@ -271,14 +326,6 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
this.counterValue = counterValue;
}
public float getCounterChance() {
return counterChance;
}
public void setCounterChance(float counterChance) {
this.counterChance = counterChance;
}
public String getCounterSound() {
return counterSound;
}
@@ -294,4 +341,48 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
public void setCounterAnimationId(int counterAnimationId) {
this.counterAnimationId = counterAnimationId;
}
public String getCounterAnimationName() {
return counterAnimationName;
}
public void setCounterAnimationName(String name) {
this.counterAnimationName = name;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> 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.activeAnimation",
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);
}
}
@@ -1,10 +1,9 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
@@ -14,13 +13,17 @@ import net.minecraft.potion.PotionEffect;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityHazard;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilityHazard;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
@@ -35,14 +38,35 @@ public class AbilityHazard extends Ability implements IAbilityHazard {
public enum HazardShape {
CIRCLE,
RING,
CONE
CONE;
@Override
public String toString() {
switch (this) {
case CIRCLE: return "ability.shape.circle";
case RING: return "ability.shape.ring";
case CONE: return "ability.shape.cone";
default: return name();
}
}
}
public enum PlacementMode {
AT_CASTER,
AT_TARGET,
FOLLOW_CASTER,
FOLLOW_TARGET
FOLLOW_TARGET;
@Override
public String toString() {
switch (this) {
case AT_CASTER: return "ability.placement.atCaster";
case AT_TARGET: return "ability.placement.atTarget";
case FOLLOW_CASTER: return "ability.placement.followCaster";
case FOLLOW_TARGET: return "ability.placement.followTarget";
default: return name();
}
}
}
private int durationTicks = 100;
@@ -88,18 +112,12 @@ public class AbilityHazard extends Ability implements IAbilityHazard {
this.cooldownTicks = 0;
this.windUpTicks = 30;
this.telegraphType = TelegraphType.CIRCLE;
this.allowedBy = UserType.NPC_ONLY;
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(
IAbilityConfigCallback callback) {
return new SubGuiAbilityHazard(this, callback);
public boolean allowBurst() {
return false;
}
@Override
@@ -186,14 +204,12 @@ public class AbilityHazard extends Ability implements IAbilityHazard {
}
break;
case AT_TARGET:
// Use telegraph position if available, apply offset
if (telegraph != null) {
double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(),
minOffset, maxOffset, randomOffset, RANDOM);
zoneX = pos[0];
zoneY = pos[1];
zoneZ = pos[2];
// Update telegraph to show actual hazard position
telegraph.setX(zoneX);
telegraph.setY(zoneY);
telegraph.setZ(zoneZ);
@@ -232,7 +248,7 @@ public class AbilityHazard extends Ability implements IAbilityHazard {
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote) return;
if (world.isRemote && !isPreview()) return;
// Check if hazard duration has ended
if (tick >= durationTicks) {
@@ -240,53 +256,55 @@ public class AbilityHazard extends Ability implements IAbilityHazard {
return;
}
damagedThisTick.clear();
ticksSinceDamage++;
if (!isPreview()) {
damagedThisTick.clear();
ticksSinceDamage++;
switch (placement) {
case FOLLOW_CASTER:
zoneX = caster.posX;
zoneY = caster.posY;
zoneZ = caster.posZ;
break;
case FOLLOW_TARGET:
if (target != null) {
zoneX = target.posX;
zoneY = target.posY;
zoneZ = target.posZ;
}
break;
default:
break;
}
if (ticksSinceDamage >= damageInterval) {
ticksSinceDamage = 0;
AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(
zoneX - radius, zoneY - heightBelow, zoneZ - radius,
zoneX + radius, zoneY + heightAbove, zoneZ + radius
);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox);
for (EntityLivingBase entity : entities) {
if (entity == caster && !affectsCaster) continue;
if (damagedThisTick.contains(entity.getEntityId())) continue;
if (!isInZone(entity, caster)) continue;
if (damagePerSecond > 0) {
if (ignoreInvulnFrames) {
entity.hurtResistantTime = 0;
switch (placement) {
case FOLLOW_CASTER:
zoneX = caster.posX;
zoneY = caster.posY;
zoneZ = caster.posZ;
break;
case FOLLOW_TARGET:
if (target != null) {
zoneX = target.posX;
zoneY = target.posY;
zoneZ = target.posZ;
}
// Apply damage with scripted event support (no knockback for hazard)
boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0);
if (!wasHit) continue; // Skip debuffs if hit was cancelled
}
break;
default:
break;
}
applyDebuffs(entity);
damagedThisTick.add(entity.getEntityId());
if (ticksSinceDamage >= damageInterval) {
ticksSinceDamage = 0;
AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(
zoneX - radius, zoneY - heightBelow, zoneZ - radius,
zoneX + radius, zoneY + heightAbove, zoneZ + radius
);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox);
for (EntityLivingBase entity : entities) {
if (entity == caster && !affectsCaster) continue;
if (damagedThisTick.contains(entity.getEntityId())) continue;
if (!isInZone(entity, caster)) continue;
if (damagePerSecond > 0) {
if (ignoreInvulnFrames) {
entity.hurtResistantTime = 0;
}
// Apply damage with scripted event support (no knockback for hazard)
boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0);
if (!wasHit) continue; // Skip debuffs if hit was cancelled
}
applyDebuffs(entity);
damagedThisTick.add(entity.getEntityId());
}
}
}
}
@@ -616,4 +634,35 @@ public class AbilityHazard extends Ability implements IAbilityHazard {
public double getZoneZ() {
return zoneZ;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000),
FieldDef.enumField("ability.shape", HazardShape.class, this::getShapeEnum, this::setShapeEnum)
.hover("ability.hover.shape"),
FieldDef.enumField("ability.placement", PlacementMode.class, this::getPlacementEnum, this::setPlacementEnum)
.hover("ability.hover.placement"),
FieldDef.section("ability.section.area"),
FieldDef.row(
FieldDef.floatField("gui.radius", this::getRadius, this::setRadius),
FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius)
),
FieldDef.section("ability.section.damage"),
FieldDef.row(
FieldDef.floatField("ability.damagePerSecond", this::getDamagePerSecond, this::setDamagePerSecond),
FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval)
),
FieldDef.section("ability.section.debuffs"),
FieldDef.row(
FieldDef.intField("ability.slownessLevel", this::getSlownessLevel, this::setSlownessLevel),
FieldDef.intField("ability.debuffDuration", this::getDebuffDuration, this::setDebuffDuration)
),
FieldDef.intField("ability.poisonLevel", this::getPoisonLevel, this::setPoisonLevel),
FieldDef.boolField("ability.affectsCaster", this::isAffectsCaster, this::setAffectsCaster)
.hover("ability.hover.affectsCaster"),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -1,7 +1,5 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
@@ -11,14 +9,16 @@ import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityHeal;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.api.ability.type.IAbilityHeal;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@@ -59,14 +59,13 @@ public class AbilityHeal extends Ability implements IAbilityHeal {
}
@Override
public boolean hasTypeSettings() {
return true;
public boolean hasDamage() {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityHeal(this, callback);
public boolean allowBurst() {
return false;
}
@Override
@@ -81,27 +80,31 @@ public class AbilityHeal extends Ability implements IAbilityHeal {
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) return;
if (world.isRemote && !isPreview()) return;
getHealedAllies().clear();
if (!isPreview()) {
getHealedAllies().clear();
// Always find allies if we're healing them (needed for both instant and HoT)
if (healAllies && healRadius > 0) {
findAlliesInRadius(caster, world);
// Always find allies if we're healing them (needed for both instant and HoT)
if (healAllies && healRadius > 0) {
findAlliesInRadius(caster, world);
}
if (instantHeal) {
// Instant heal - apply all healing now
if (healSelf) {
healEntity(caster);
spawnHealParticles(world, caster);
}
for (EntityLivingBase ally : getHealedAllies()) {
healEntity(ally);
spawnHealParticles(world, ally);
}
}
}
if (instantHeal) {
// Instant heal - apply all healing now
if (healSelf) {
healEntity(caster);
spawnHealParticles(world, caster);
}
for (EntityLivingBase ally : getHealedAllies()) {
healEntity(ally);
spawnHealParticles(world, ally);
}
// Instant heal completes immediately
signalCompletion();
}
@@ -110,7 +113,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal {
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote || instantHeal) return;
if ((world.isRemote && !isPreview()) || instantHeal) return;
// Heal over time - distribute heal across duration ticks
if (tick % 10 == 0) {
@@ -289,4 +292,27 @@ public class AbilityHeal extends Ability implements IAbilityHeal {
public void setInstantHeal(boolean instantHeal) {
this.instantHeal = instantHeal;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.boolField("ability.instantHeal", this::isInstantHeal, this::setInstantHeal)
.hover("ability.hover.instant"),
FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks)
.range(1, 1000).visibleWhen(() -> !this.isInstantHeal()),
FieldDef.section("ability.section.healing"),
FieldDef.row(
FieldDef.floatField("ability.healAmount", this::getHealAmount, this::setHealAmount),
FieldDef.floatField("ability.healPercent", this::getHealPercent, this::setHealPercent)
),
FieldDef.floatField("ability.healRadius", this::getHealRadius, this::setHealRadius),
FieldDef.row(
FieldDef.boolField("ability.healSelf", this::isHealSelf, this::setHealSelf)
.hover("ability.hover.healSelf"),
FieldDef.boolField("ability.healAllies", this::isHealAllies, this::setHealAllies)
.hover("ability.hover.healAllies")
)
));
}
}
@@ -6,49 +6,44 @@ import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityHeavyHit;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityHeavyHit;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.Arrays;
import java.util.List;
/**
* Heavy Hit ability: Single-target melee attack with optional stun.
* Deals high damage to one target and can stun them.
* Heavy Hit ability: AOE rectangle melee attack in front of the caster.
* Deals high damage to all entities within a rectangular zone and can apply effects.
* Has a LINE telegraph showing the hit area during windup, making it dodgeable.
*/
public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit {
private float damage = 8.0f;
private float knockback = 2.0f;
private float hitLength = 4.0f; // How far in front of the caster the hit reaches
private float hitWidth = 3.0f; // How wide to each side (total width = hitWidth * 2)
public AbilityHeavyHit() {
this.typeId = "ability.cnpc.heavy_hit";
this.name = "Heavy Hit";
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.maxRange = 3.0f;
this.targetingMode = TargetingMode.AOE_SELF;
this.maxRange = 5.0f;
this.minRange = 0.0f;
this.lockMovement = LockMovementType.NO;
this.lockMovement = LockMovementType.WINDUP;
this.cooldownTicks = 0;
this.windUpTicks = 30;
this.telegraphType = TelegraphType.POINT;
this.showTelegraph = false;
this.telegraphType = TelegraphType.LINE;
this.showTelegraph = true;
this.windUpSound = "random.anvil_use";
this.activeSound = "random.anvil_land";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(
IAbilityConfigCallback callback) {
return new SubGuiAbilityHeavyHit(this, callback);
this.windUpAnimationName = "Ability_HeavyHit_Windup";
this.activeAnimationName = "Ability_HeavyHit_Active";
}
@Override
@@ -58,43 +53,92 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit {
@Override
public TargetingMode[] getAllowedTargetingModes() {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
return new TargetingMode[]{TargetingMode.AOE_SELF};
}
@Override
public float getTelegraphLength() {
return hitLength;
}
@Override
public float getTelegraphWidth() {
return hitWidth * 2.0f; // Total width (hitWidth is distance to each side)
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote || target == null) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
// Apply damage with scripted event support
boolean wasHit = applyAbilityDamage(caster, target, damage, knockback);
if (!isPreview()) {
// Calculate forward and right vectors from caster yaw
float yawRad = (float) Math.toRadians(caster.rotationYaw);
double forwardX = -Math.sin(yawRad);
double forwardZ = Math.cos(yawRad);
double rightX = forwardZ; // perpendicular right
double rightZ = -forwardX;
// Apply effects if hit wasn't cancelled
if (wasHit) {
applyEffects(target);
// Search area: AABB that encompasses the rectangle
float searchDist = Math.max(hitLength, hitWidth) + 1.0f;
@SuppressWarnings("unchecked")
List<Entity> entities = world.getEntitiesWithinAABBExcludingEntity(
caster, caster.boundingBox.expand(searchDist, 2, searchDist));
boolean anyHit = false;
for (Entity entity : entities) {
if (!(entity instanceof EntityLivingBase) || entity == caster) continue;
EntityLivingBase livingTarget = (EntityLivingBase) entity;
double dx = livingTarget.posX - caster.posX;
double dz = livingTarget.posZ - caster.posZ;
// Project onto forward direction (must be in front, within hitLength)
double forwardDist = dx * forwardX + dz * forwardZ;
if (forwardDist < 0 || forwardDist > hitLength) continue;
// Project onto right direction (must be within hitWidth to each side)
double sideDist = dx * rightX + dz * rightZ;
if (Math.abs(sideDist) > hitWidth) continue;
// Entity is within the rectangle - apply damage
boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback);
if (wasHit) {
applyEffects(livingTarget);
anyHit = true;
}
}
// Play hit sound even if nothing was hit (the attack still happens)
if (!anyHit) {
world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f);
}
}
// Heavy Hit is instant
signalCompletion();
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Heavy Hit is instant, no active tick needed
// Just enough delay to see the active animation
if (tick == 10)
signalCompletion();
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("damage", damage);
nbt.setFloat("knockback", knockback);
nbt.setFloat("hitLength", hitLength);
nbt.setFloat("hitWidth", hitWidth);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f;
this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 2.0f;
this.hitLength = nbt.hasKey("hitLength") ? nbt.getFloat("hitLength") : 4.0f;
this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 3.0f;
}
// Getters & Setters
@@ -113,4 +157,37 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit {
public void setKnockback(float knockback) {
this.knockback = knockback;
}
public float getHitLength() {
return hitLength;
}
public void setHitLength(float hitLength) {
this.hitLength = hitLength;
}
public float getHitWidth() {
return hitWidth;
}
public void setHitWidth(float hitWidth) {
this.hitWidth = hitWidth;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)
),
FieldDef.section("ability.section.hitZone"),
FieldDef.row(
FieldDef.floatField("ability.hitLength", this::getHitLength, this::setHitLength),
FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth)
),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -3,24 +3,25 @@ package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.RotationMode;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.data.EnergyColorData;
import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.*;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityLaser;
import net.minecraft.entity.Entity;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityLaserShot;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.api.ability.type.IAbilityLaserShot;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.Arrays;
import java.util.List;
/**
* Laser Shot ability: Fast expanding thin line that pierces through targets.
@@ -34,10 +35,12 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
private int lingerTicks = 8;
// Data classes
private EnergyColorData colorData = new EnergyColorData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f);
private EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100);
private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f);
private final EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f);
private final EnergyLightningData lightningData = new EnergyLightningData();
private final EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100);
private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT);
private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
// Transient state for laser entity (used for movement locking)
private transient EntityAbilityLaser laserEntity = null;
@@ -50,7 +53,9 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
this.minRange = 3.0f;
this.cooldownTicks = 0;
this.windUpTicks = 15;
this.lockMovement = LockMovementType.WINDUP;
this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE;
this.rotationMode = RotationMode.TRACK;
this.rotationPhase = LockMovementType.WINDUP;
this.telegraphType = TelegraphType.LINE;
this.showTelegraph = true;
// Default built-in animations
@@ -59,16 +64,10 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
}
@Override
public boolean hasTypeSettings() {
public boolean allowOverlap() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityLaserShot(this, callback);
}
@Override
public boolean isTargetingModeLocked() {
return false;
@@ -89,30 +88,65 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
return laserWidth * 2.0f; // Make telegraph slightly wider for visibility
}
/**
* Spawn laser entity.
* NPC: target is the aggro target — laser expands toward it.
* Player: target is null — laser expands in caster's look direction.
*/
private EntityAbilityLaser spawnLaserEntity(EntityLivingBase caster, EntityLivingBase target, World world) {
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData);
EntityAbilityLaser entity = new EntityAbilityLaser(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
laserWidth,
colorData, combatData, lightningData, lifespanData, trajectoryData,
expansionSpeed, lingerTicks
);
entity.setEffects(this.effects);
entity.setSourceAbility(this);
spawnAbilityEntity(world, entity);
return entity;
}
private void fireLaserEntity(EntityAbilityLaser laser, EntityLivingBase target) {
if (laser == null || laser.isDead) return;
laser.setLockVerticalDirection(true);
laser.startMoving(target);
}
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote && !isPreview()) return;
if (tick == 1) {
laserEntity = spawnLaserEntity(caster, target, world);
if (isPreview()) {
laserEntity.setupPreview(caster, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance);
} else {
laserEntity.setupCharging(anchorData, windUpTicks);
}
}
}
@Override
public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) {
laserEntity = spawnLaserEntity(caster, target, world);
fireLaserEntity(laserEntity, target);
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
double spawnX = caster.posX;
double spawnY = caster.posY + caster.getEyeHeight();
double spawnZ = caster.posZ;
if (laserEntity == null) {
signalCompletion();
return;
}
laserEntity = new EntityAbilityLaser(
world, caster, target,
spawnX, spawnY, spawnZ,
laserWidth,
colorData, combatData, lightningData, lifespanData,
expansionSpeed, lingerTicks
);
laserEntity.setEffects(this.effects);
world.spawnEntityInWorld(laserEntity);
// Ability stays active until entity dies (prevents firing another while projectile is alive)
// Movement locking is handled separately by the base class
fireLaserEntity(laserEntity, target);
}
@Override
@@ -130,6 +164,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
@Override
public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) {
cleanup();
}
@Override
@@ -146,6 +181,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
nbt.setFloat("laserWidth", laserWidth);
nbt.setFloat("expansionSpeed", expansionSpeed);
nbt.setInteger("lingerTicks", lingerTicks);
anchorData.writeNBT(nbt);
colorData.writeNBT(nbt);
combatData.writeNBT(nbt);
lightningData.writeNBT(nbt);
@@ -157,6 +193,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
this.laserWidth = nbt.hasKey("laserWidth") ? nbt.getFloat("laserWidth") : 0.3f;
this.expansionSpeed = nbt.hasKey("expansionSpeed") ? nbt.getFloat("expansionSpeed") : 3.0f;
this.lingerTicks = nbt.hasKey("lingerTicks") ? nbt.getInteger("lingerTicks") : 8;
anchorData.readNBT(nbt);
colorData.readNBT(nbt);
combatData.readNBT(nbt);
lightningData.readNBT(nbt);
@@ -210,23 +247,78 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot {
public float getLightningRadius() { return lightningData.lightningRadius; }
public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; }
@Override
@SideOnly(Side.CLIENT)
public Entity createPreviewEntity(EntityNPCInterface npc) {
if (npc == null || npc.worldObj == null) return null;
public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; }
EntityAbilityLaser laser = new EntityAbilityLaser(npc.worldObj);
laser.setupPreview(npc, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance);
return laser;
public float getAnchorOffsetX() { return anchorData.anchorOffsetX; }
public float getAnchorOffsetY() { return anchorData.anchorOffsetY; }
public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; }
public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; }
public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; }
public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; }
public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; }
public int getAnchorPoint() {
return anchorData.anchorPoint.ordinal();
}
public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); }
@Override
public int getPreviewActiveDuration() {
public int getMaxPreviewDuration() {
return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60;
}
@SideOnly(Side.CLIENT)
@Override
public boolean spawnPreviewDuringWindup() {
return false; // Laser has no charging, spawns at active phase
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
// Type tab
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.row(
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback),
FieldDef.floatField("ability.knockbackUp", this::getKnockbackUp, this::setKnockbackUp)
),
FieldDef.section("ability.section.beam"),
FieldDef.row(
FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth),
FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed)
),
FieldDef.row(
FieldDef.intField("ability.lingerTicks", this::getLingerTicks, this::setLingerTicks),
FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime)
),
FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance),
FieldDef.section("ability.section.explosive"),
FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"),
FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects),
// Visual tab
FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum)
.tab("ability.tab.visual"),
FieldDef.row(
FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX),
FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY)
).tab("ability.tab.visual"),
FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ)
.tab("ability.tab.visual"),
FieldDef.section("ability.section.colors").tab("ability.tab.visual"),
FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"),
FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"),
FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled),
FieldDef.row(
FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth)
.visibleWhen(this::isOuterColorEnabled),
FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha)
.range(0, 1).visibleWhen(this::isOuterColorEnabled)
).tab("ability.tab.visual"),
FieldDef.section("ability.section.effects").tab("ability.tab.visual"),
FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"),
FieldDef.row(
FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity)
.range(0.01f, 100f).visibleWhen(this::hasLightningEffect),
FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius)
.range(0.1f, 100f).visibleWhen(this::hasLightningEffect)
).tab("ability.tab.visual")
));
}
}
@@ -12,37 +12,48 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityOrb;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityOrb;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.Arrays;
import java.util.List;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
/**
* Orb ability: Spawns a homing projectile sphere that tracks target.
* The EntityAbilityOrb handles all movement, collision, and damage logic.
* This ability just configures and spawns the orb entity.
* Orb ability: Spawns homing projectile sphere(s) that track target.
* Supports 1-8 projectiles with shared visuals and per-projectile anchor points.
*/
public class AbilityOrb extends Ability implements IAbilityOrb {
// Ability-specific properties
private static final int MAX_PROJECTILES = 8;
// Orb properties
private float orbSize = 1.0f;
// Data classes for energy properties
public final EnergyColorData colorData = new EnergyColorData();
public final EnergyCombatData combatData = new EnergyCombatData();
public final EnergyHomingData homingData = new EnergyHomingData();
public final EnergyLightningData lightningData = new EnergyLightningData();
public final EnergyLifespanData lifespanData = new EnergyLifespanData();
private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND);
// Projectile count and fire stagger
private int projectileCount = 1;
private int fireDelay = 0;
// Transient state for orb entity (used during windup charging)
private transient EntityAbilityOrb orbEntity = null;
// Shared visual data (all projectiles use these)
private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f);
private EnergyLightningData lightningData = new EnergyLightningData();
private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
// Shared combat/movement data
private final EnergyCombatData combatData = new EnergyCombatData();
private final EnergyHomingData homingData = new EnergyHomingData();
private final EnergyLifespanData lifespanData = new EnergyLifespanData();
// Per-projectile data (anchor + optional color override)
private ProjectileData[] projectiles;
// Transient entity state
private transient EntityAbilityOrb[] orbEntities;
public AbilityOrb() {
this.typeId = "ability.cnpc.orb";
@@ -55,20 +66,100 @@ public class AbilityOrb extends Ability implements IAbilityOrb {
this.lockMovement = LockMovementType.WINDUP;
this.telegraphType = TelegraphType.CIRCLE;
this.showTelegraph = true;
// Default built-in animation
this.windUpAnimationName = "Ability_Orb_Windup";
this.activeAnimationName = "Ability_Orb_Active";
initProjectiles(1);
}
private void initProjectiles(int count) {
this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
this.projectiles = new ProjectileData[projectileCount];
for (int i = 0; i < projectileCount; i++) {
projectiles[i] = new ProjectileData(getDefaultAnchor(i));
}
}
private AnchorPoint getDefaultAnchor(int index) {
switch (index) {
case 0: return AnchorPoint.RIGHT_HAND;
case 1: return AnchorPoint.LEFT_HAND;
default: return AnchorPoint.FRONT;
}
}
public void setProjectileCount(int count) {
int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES));
if (newCount == projectileCount) return;
ProjectileData[] oldProjectiles = projectiles;
initProjectiles(newCount);
// Preserve existing projectile data
if (oldProjectiles != null) {
int copyCount = Math.min(oldProjectiles.length, newCount);
for (int i = 0; i < copyCount; i++) {
if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i];
}
}
}
public int getProjectileCount() {
return projectileCount;
}
public int getFireDelay() {
return fireDelay;
}
public void setFireDelay(int delay) {
this.fireDelay = Math.max(0, delay);
}
// Legacy compat
public int getDualFireDelay() { return fireDelay; }
public void setDualFireDelay(int delay) { setFireDelay(delay); }
@Override
public List<AbilityVariant> getVariants() {
return Arrays.asList(
new AbilityVariant("ability.variant.single", a -> {
a.setName("Orb");
}),
new AbilityVariant("ability.variant.dual", a -> {
AbilityOrb orb = (AbilityOrb) a;
a.setName("Dual Orb");
orb.setProjectileCount(2);
orb.setFireDelay(5);
a.setWindUpAnimationName("Ability_OrbDual_Windup");
a.setActiveAnimationName("Ability_OrbDual_Active");
}),
new AbilityVariant("ability.variant.barrage", a -> {
AbilityOrb orb = (AbilityOrb) a;
a.setName("Orb Barrage");
orb.setOrbSize(0.5f);
orb.setDamage(4.0f);
orb.setKnockback(0.0f);
orb.setKnockbackUp(0.0f);
a.setMaxRange(75.0f);
a.setBurstEnabled(true);
a.setBurstAmount(15);
a.setBurstDelay(10);
a.setBurstReplayAnimations(false);
a.setBurstOverlap(true);
a.setWindUpAnimationName("Ability_BeamDual_Windup");
a.setActiveAnimationName("Ability_BeamDual_Active");
})
);
}
@Override
public boolean hasTypeSettings() {
public boolean allowOverlap() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityOrb(this, callback);
public boolean isReadyForBurstCompletion(int activeTick) {
return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1);
}
@Override
@@ -81,71 +172,147 @@ public class AbilityOrb extends Ability implements IAbilityOrb {
return new TargetingMode[]{TargetingMode.AGGRO_TARGET};
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) {
signalCompletion();
return;
/**
* Create orb entities.
* NPC: target is the aggro target — orbs will home toward it.
* Player: target is null — orbs fire in caster's look direction.
*/
private EntityAbilityOrb[] createOrbEntities(EntityLivingBase caster, EntityLivingBase target, World world) {
EntityAbilityOrb[] entities = new EntityAbilityOrb[projectileCount];
for (int i = 0; i < projectileCount; i++) {
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor);
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
entities[i] = new EntityAbilityOrb(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize,
resolved, combatData, homingData, lightningData, lifespanData, trajectoryData);
entities[i].setEffects(this.effects);
entities[i].setSourceAbility(this);
}
// Start moving the orb that was spawned during windup
if (orbEntity != null && !orbEntity.isDead) {
orbEntity.startMoving(target);
if (projectileCount == 2 && entities[0] != null && entities[1] != null) {
entities[0].setSiblingEntityId(entities[1].getEntityId());
entities[1].setSiblingEntityId(entities[0].getEntityId());
}
return entities;
}
// Ability stays active until entity dies (prevents firing another while projectile is alive)
// Movement locking is handled separately by the base class
private void fireOrbEntity(EntityAbilityOrb orb, EntityLivingBase target) {
if (orb == null || orb.isDead) return;
if (isPreview()) {
orb.startPreviewFiring();
} else {
orb.startMoving(target);
}
}
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (world.isRemote) return;
if (world.isRemote && !isPreview()) return;
// Spawn orb in charging mode on first tick of windup
if (tick == 1) {
// Create orb in charging mode - follows caster based on anchor point during windup
Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData);
orbEntity = new EntityAbilityOrb(
world, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize,
colorData, combatData, homingData, lightningData, lifespanData);
orbEntity.setupCharging(anchorData, windUpTicks);
orbEntities = createOrbEntities(caster, target, world);
for (int i = 0; i < projectileCount; i++) {
EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData);
if (isPreview()) {
orbEntities[i].setupPreview(caster, orbSize, resolved, lightningData, projectiles[i].anchor, windUpTicks);
} else {
orbEntities[i].setupCharging(projectiles[i].anchor, windUpTicks);
}
spawnAbilityEntity(world, orbEntities[i]);
}
}
}
orbEntity.setEffects(this.effects);
world.spawnEntityInWorld(orbEntity);
@Override
public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) {
orbEntities = createOrbEntities(caster, target, world);
for (EntityAbilityOrb orb : orbEntities) {
spawnAbilityEntity(world, orb);
}
for (EntityAbilityOrb orb : orbEntities) {
fireOrbEntity(orb, target);
}
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
if (orbEntities == null) return;
// Fire first projectile immediately
fireOrbEntity(orbEntities[0], target);
// Fire remaining projectiles if no delay
if (fireDelay <= 0) {
for (int i = 1; i < projectileCount; i++) {
fireOrbEntity(orbEntities[i], target);
}
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Signal completion when entity dies
if (orbEntity == null || orbEntity.isDead) {
orbEntity = null;
if (orbEntities == null) {
signalCompletion();
return;
}
// Fire staggered projectiles
if (fireDelay > 0) {
for (int i = 1; i < projectileCount; i++) {
if (tick == fireDelay * i) {
fireOrbEntity(orbEntities[i], target);
}
}
}
// Check if all entities are dead
boolean allDead = true;
for (EntityAbilityOrb orb : orbEntities) {
if (orb != null && !orb.isDead) {
allDead = false;
break;
}
}
if (allDead) {
signalCompletion();
}
}
@Override
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
// Nothing to clean up - entity manages itself
}
@Override
public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) {
cleanup();
}
@Override
public void cleanup() {
// Despawn orb entity if still alive
if (orbEntity != null && !orbEntity.isDead) {
orbEntity.setDead();
if (orbEntities != null) {
for (int i = 0; i < orbEntities.length; i++) {
if (orbEntities[i] != null && !orbEntities[i].isDead) {
orbEntities[i].setDead();
}
orbEntities[i] = null;
}
}
orbEntity = null;
orbEntities = null;
}
@Override
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) {
// NPC: telegraph on aggro target position
// Player: no telegraph (orbs fire in look direction, no fixed position to mark)
if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) {
return null;
}
// Create small circle telegraph at target position
Telegraph telegraph = Telegraph.circle(orbSize * 1.5f);
telegraph.setDurationTicks(windUpTicks);
telegraph.setColor(windUpColor);
@@ -153,7 +320,6 @@ public class AbilityOrb extends Ability implements IAbilityOrb {
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
// Position at target and follow target during windup
TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
instance.setEntityIdToFollow(target.getEntityId());
@@ -169,253 +335,316 @@ public class AbilityOrb extends Ability implements IAbilityOrb {
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("orbSize", orbSize);
anchorData.writeNBT(nbt);
colorData.writeNBT(nbt);
nbt.setInteger("projectileCount", projectileCount);
nbt.setInteger("fireDelay", fireDelay);
// Shared visual data
displayData.writeNBT(nbt);
lightningData.writeNBT(nbt);
// Shared combat/movement data
combatData.writeNBT(nbt);
homingData.writeNBT(nbt);
lightningData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
// Backward compat: old key was "orbSpeed"
// Per-projectile data
for (int i = 0; i < projectileCount; i++) {
NBTTagCompound projNbt = new NBTTagCompound();
projectiles[i].writeNBT(projNbt);
nbt.setTag("Projectile_" + i, projNbt);
}
// Backward compat write
nbt.setFloat("orbSpeed", homingData.speed);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f;
anchorData.readNBT(nbt);
colorData.readNBT(nbt);
int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1;
initProjectiles(count);
// Read fireDelay with fallback to old dualFireDelay key
if (nbt.hasKey("fireDelay")) {
this.fireDelay = nbt.getInteger("fireDelay");
} else if (nbt.hasKey("dualFireDelay")) {
this.fireDelay = nbt.getInteger("dualFireDelay");
} else {
this.fireDelay = 0;
}
// Shared combat/movement data
combatData.readNBT(nbt);
homingData.readNBT(nbt);
lightningData.readNBT(nbt);
lifespanData.readNBT(nbt);
// Backward compat: old key was "orbSpeed"
// Determine format and read accordingly
if (nbt.hasKey("Projectile_0")) {
NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0");
if (proj0.hasKey("colorOverride")) {
// NEW format: shared visuals at root + ProjectileData per projectile
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
for (int i = 0; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i));
}
}
} else {
// OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i)
// Read primary visuals from Projectile_0
displayData.readNBT(proj0);
lightningData.readNBT(proj0);
projectiles[0].anchor.readNBT(proj0);
// Read remaining projectiles, set color override if colors differ
for (int i = 1; i < projectileCount; i++) {
if (nbt.hasKey("Projectile_" + i)) {
NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i);
projectiles[i].anchor.readNBT(projNbt);
// Check if this projectile had different colors
EnergyDisplayData tempDisplay = new EnergyDisplayData();
tempDisplay.readNBT(projNbt);
if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) {
projectiles[i].colorOverride = true;
projectiles[i].innerColor = tempDisplay.innerColor;
projectiles[i].outerColor = tempDisplay.outerColor;
}
}
}
}
} else {
// LEGACY flat format: all data at root level
displayData.readNBT(nbt);
lightningData.readNBT(nbt);
projectiles[0].anchor.readNBT(nbt);
}
// Backward compat
if (nbt.hasKey("orbSpeed")) {
homingData.speed = nbt.getFloat("orbSpeed");
}
}
// Getters & Setters
public float getOrbSpeed() {
return homingData.speed;
// ═══════════════════════════════════════════════════════════════════
// API GETTERS & SETTERS
// ═══════════════════════════════════════════════════════════════════
public float getOrbSpeed() { return homingData.speed; }
public void setOrbSpeed(float speed) { homingData.speed = speed; }
public float getOrbSize() { return orbSize; }
public void setOrbSize(float size) { this.orbSize = size; }
public float getMaxDistance() { return lifespanData.maxDistance; }
public void setMaxDistance(float d) { lifespanData.maxDistance = d; }
public int getMaxLifetime() { return lifespanData.maxLifetime; }
public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; }
public float getDamage() { return combatData.damage; }
public void setDamage(float d) { combatData.damage = d; }
public float getKnockback() { return combatData.knockback; }
public void setKnockback(float k) { combatData.knockback = k; }
public float getKnockbackUp() { return combatData.knockbackUp; }
public void setKnockbackUp(float k) { combatData.knockbackUp = k; }
public boolean isHoming() { return homingData.homing; }
public void setHoming(boolean h) { homingData.homing = h; }
public float getHomingStrength() { return homingData.homingStrength; }
public void setHomingStrength(float s) { homingData.homingStrength = s; }
public float getHomingRange() { return homingData.homingRange; }
public void setHomingRange(float r) { homingData.homingRange = r; }
public boolean isExplosive() { return combatData.explosive; }
public void setExplosive(boolean e) { combatData.explosive = e; }
public float getExplosionRadius() { return combatData.explosionRadius; }
public void setExplosionRadius(float r) { combatData.explosionRadius = r; }
public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; }
public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; }
// Shared display data (primary colors)
public int getInnerColor() { return displayData.innerColor; }
public void setInnerColor(int c) { displayData.innerColor = c; }
public int getOuterColor() { return displayData.outerColor; }
public void setOuterColor(int c) { displayData.outerColor = c; }
public float getOuterColorWidth() { return displayData.outerColorWidth; }
public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; }
public float getOuterColorAlpha() { return displayData.outerColorAlpha; }
public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; }
public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; }
public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; }
public float getRotationSpeed() { return displayData.rotationSpeed; }
public void setRotationSpeed(float s) { displayData.rotationSpeed = s; }
// Shared lightning data
public boolean hasLightningEffect() { return lightningData.lightningEffect; }
public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; }
public float getLightningDensity() { return lightningData.lightningDensity; }
public void setLightningDensity(float d) { lightningData.lightningDensity = d; }
public float getLightningRadius() { return lightningData.lightningRadius; }
public void setLightningRadius(float r) { lightningData.lightningRadius = r; }
public int getLightningFadeTime() { return lightningData.lightningFadeTime; }
public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; }
// Anchor - default to projectile 0
public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; }
public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; }
public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; }
public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; }
public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; }
public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; }
public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; }
public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; }
public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); }
@Override
public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
// Indexed API methods
public int getInnerColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.innerColor : displayData.innerColor;
}
public void setInnerColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.innerColor = color;
}
public void setOrbSpeed(float orbSpeed) {
homingData.speed = orbSpeed;
public int getOuterColor(int index) {
ProjectileData p = projectiles[clampIndex(index)];
return p.colorOverride ? p.outerColor : displayData.outerColor;
}
public void setOuterColor(int index, int color) {
ProjectileData p = projectiles[clampIndex(index)];
p.colorOverride = true;
p.outerColor = color;
}
public float getOrbSize() {
return orbSize;
}
public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); }
public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); }
public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; }
public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; }
public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; }
public void setOrbSize(float orbSize) {
this.orbSize = orbSize;
}
public float getMaxDistance() {
return lifespanData.maxDistance;
}
public void setMaxDistance(float maxDistance) {
lifespanData.maxDistance = maxDistance;
}
public int getMaxLifetime() {
return lifespanData.maxLifetime;
}
public void setMaxLifetime(int maxLifetime) {
lifespanData.maxLifetime = maxLifetime;
}
public float getDamage() {
return combatData.damage;
}
public void setDamage(float damage) {
combatData.damage = damage;
}
public float getKnockback() {
return combatData.knockback;
}
public void setKnockback(float knockback) {
combatData.knockback = knockback;
}
public float getKnockbackUp() {
return combatData.knockbackUp;
}
public void setKnockbackUp(float knockbackUp) {
combatData.knockbackUp = knockbackUp;
}
public boolean isHoming() {
return homingData.homing;
}
public void setHoming(boolean homing) {
homingData.homing = homing;
}
public float getHomingStrength() {
return homingData.homingStrength;
}
public void setHomingStrength(float homingStrength) {
homingData.homingStrength = homingStrength;
}
public float getHomingRange() {
return homingData.homingRange;
}
public void setHomingRange(float homingRange) {
homingData.homingRange = homingRange;
}
public boolean isExplosive() {
return combatData.explosive;
}
public void setExplosive(boolean explosive) {
combatData.explosive = explosive;
}
public float getExplosionRadius() {
return combatData.explosionRadius;
}
public void setExplosionRadius(float explosionRadius) {
combatData.explosionRadius = explosionRadius;
}
public float getExplosionDamageFalloff() {
return combatData.explosionDamageFalloff;
}
public void setExplosionDamageFalloff(float explosionDamageFalloff) {
combatData.explosionDamageFalloff = explosionDamageFalloff;
}
public int getInnerColor() {
return colorData.innerColor;
}
public void setInnerColor(int innerColor) {
colorData.innerColor = innerColor;
}
public int getOuterColor() {
return colorData.outerColor;
}
public void setOuterColor(int outerColor) {
colorData.outerColor = outerColor;
}
public float getOuterColorWidth() {
return colorData.outerColorWidth;
}
public void setOuterColorWidth(float outerColorWidth) {
colorData.outerColorWidth = outerColorWidth;
}
public float getOuterColorAlpha() {
return colorData.outerColorAlpha;
}
public void setOuterColorAlpha(float outerColorAlpha) {
colorData.outerColorAlpha = outerColorAlpha;
}
public boolean isOuterColorEnabled() {
return colorData.outerColorEnabled;
}
public void setOuterColorEnabled(boolean outerColorEnabled) {
colorData.outerColorEnabled = outerColorEnabled;
}
public float getRotationSpeed() {
return colorData.rotationSpeed;
}
public void setRotationSpeed(float rotationSpeed) {
colorData.rotationSpeed = rotationSpeed;
}
public boolean hasLightningEffect() {
return lightningData.lightningEffect;
}
public void setLightningEffect(boolean lightningEffect) {
lightningData.lightningEffect = lightningEffect;
}
public float getLightningDensity() {
return lightningData.lightningDensity;
}
public void setLightningDensity(float lightningDensity) {
lightningData.lightningDensity = lightningDensity;
}
public float getLightningRadius() {
return lightningData.lightningRadius;
}
public void setLightningRadius(float lightningRadius) {
lightningData.lightningRadius = lightningRadius;
}
public int getLightningFadeTime() {
return lightningData.lightningFadeTime;
}
public void setLightningFadeTime(int lightningFadeTime) {
lightningData.lightningFadeTime = lightningFadeTime;
}
public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; }
public float getAnchorOffsetX() { return anchorData.anchorOffsetX; }
public float getAnchorOffsetY() { return anchorData.anchorOffsetY; }
public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; }
public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; }
public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; }
public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; }
public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; }
public int getAnchorPoint() {
return anchorData.anchorPoint.ordinal();
private int clampIndex(int index) {
return Math.max(0, Math.min(index, projectileCount - 1));
}
@Override
public void setAnchorPoint(int point) {
this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point);
}
@Override
@SideOnly(Side.CLIENT)
public Entity createPreviewEntity(EntityNPCInterface npc) {
if (npc == null || npc.worldObj == null) return null;
EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj);
orb.setupPreview(npc, orbSize, colorData, lightningData, anchorData, windUpTicks);
return orb;
}
@Override
public int getPreviewActiveDuration() {
public int getMaxPreviewDuration() {
return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100;
}
// ═══════════════════════════════════════════════════════════════════
// GUI FIELD DEFINITIONS
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
// Type tab - projectile count and fire delay
defs.add(FieldDef.row(
FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES),
FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay)
.range(0, 200).visibleWhen(() -> projectileCount > 1)
));
// Type tab - orb properties
defs.add(FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed)
));
defs.add(FieldDef.row(
FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize),
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)
));
defs.add(FieldDef.row(
FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance),
FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime)
));
defs.add(FieldDef.section("ability.section.homing"));
defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"));
defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming));
defs.add(FieldDef.section("ability.section.explosive"));
defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"));
defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive));
defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects));
// Visual tab - shared primary colors
defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled)
.tab("ability.tab.visual"));
defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled));
defs.add(FieldDef.row(
FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth)
.visibleWhen(this::isOuterColorEnabled),
FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha)
.range(0, 1).visibleWhen(this::isOuterColorEnabled)
).tab("ability.tab.visual"));
// Visual tab - shared effects
defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual"));
defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed)
.tab("ability.tab.visual"));
defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect)
.tab("ability.tab.visual"));
defs.add(FieldDef.row(
FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity)
.visibleWhen(this::hasLightningEffect).range(0.01f, 100f),
FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius)
.range(0.1f, 100f).visibleWhen(this::hasLightningEffect)
).tab("ability.tab.visual"));
// Visual tab - per-projectile sections
for (int i = 0; i < MAX_PROJECTILES; i++) {
final int idx = i;
String sectionKey = "ability.section.projectile" + (i + 1);
defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual")
.visibleWhen(() -> idx < projectileCount));
// Anchor point
defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class,
() -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.row(
FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v),
FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v)
).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount));
// Color override (only when multiple projectiles)
defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1));
defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v)
.tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride));
}
}
}
@@ -9,12 +9,16 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityProjectile;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilityProjectile;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import java.util.Arrays;
import java.util.List;
/**
@@ -48,14 +52,8 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile {
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityProjectile(this, callback);
public boolean allowBurst() {
return false;
}
@Override
@@ -70,61 +68,129 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile {
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote || target == null) return;
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
if (isPlayerCaster(caster)) {
// Player: instant hit-scan in look direction
executePlayerProjectile(caster, world);
} else if (target != null) {
// NPC: instant hit-scan on aggro target
executeNpcProjectile(caster, target, world);
}
signalCompletion();
}
/**
* NPC projectile: instant hit-scan damage on the aggro target.
*/
private void executeNpcProjectile(EntityLivingBase caster, EntityLivingBase target, World world) {
if (isPreview()) return;
// Calculate direction to target
double dx = target.posX - caster.posX;
double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight());
double dz = target.posZ - caster.posZ;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) { dx /= len; dy /= len; dz /= len; }
if (len > 0) {
dx /= len;
dy /= len;
dz /= len;
}
// Deal instant damage with scripted event support
// TODO: Use custom EntityAbilityProjectile for actual tracking
applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz);
// Play sound
world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f);
// Handle splash damage for explosive projectiles
if (explosive && explosionRadius > 0) {
@SuppressWarnings("unchecked")
List<Entity> entities = world.getEntitiesWithinAABBExcludingEntity(target,
target.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius));
applyExplosionDamage(caster, target, world, target.posX, target.posY, target.posZ);
}
for (Entity entity : entities) {
if (entity instanceof EntityLivingBase && entity != caster) {
EntityLivingBase living = (EntityLivingBase) entity;
float dist = target.getDistanceToEntity(living);
if (dist < explosionRadius) {
float falloff = 1.0f - (dist / explosionRadius);
// Apply splash damage with scripted event support (no knockback)
applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0);
}
}
}
spawnProjectileParticles(world, caster, target);
}
// Explosion particles
world.playSoundAtEntity(target, "random.explode", 0.5f, 1.0f);
for (int i = 0; i < 10; i++) {
world.spawnParticle("explode",
target.posX + (world.rand.nextDouble() - 0.5) * explosionRadius,
target.posY + world.rand.nextDouble() * target.height,
target.posZ + (world.rand.nextDouble() - 0.5) * explosionRadius,
0, 0.1, 0);
/**
* Player projectile: fires instant hit-scan in look direction.
* Raycasts for the first entity in range and applies damage.
*/
private void executePlayerProjectile(EntityLivingBase caster, World world) {
if (isPreview()) return;
Vec3 look = caster.getLookVec();
double eyeX = caster.posX;
double eyeY = caster.posY + caster.getEyeHeight();
double eyeZ = caster.posZ;
// Raycast: find the closest entity along look direction
EntityLivingBase hitTarget = null;
double closestDist = maxRange;
@SuppressWarnings("unchecked")
List<Entity> candidates = world.getEntitiesWithinAABBExcludingEntity(caster,
caster.boundingBox.expand(maxRange, maxRange, maxRange));
for (Entity entity : candidates) {
if (!(entity instanceof EntityLivingBase)) continue;
if (entity.isDead) continue;
// Check if entity is roughly along look direction
double dx = entity.posX - eyeX;
double dy = (entity.posY + entity.height / 2) - eyeY;
double dz = entity.posZ - eyeZ;
double dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist > maxRange || dist < 0.5) continue;
// Dot product to check alignment with look vector
double dot = (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) / dist;
if (dot < 0.95) continue; // Must be within ~18 degree cone
if (dist < closestDist) {
closestDist = dist;
hitTarget = (EntityLivingBase) entity;
}
}
// Spawn projectile particles (visual trail)
spawnProjectileParticles(world, caster, target);
world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f);
// Projectile is instant
signalCompletion();
if (hitTarget != null) {
applyAbilityDamageWithDirection(caster, hitTarget, damage, knockback, look.xCoord, look.zCoord);
if (explosive && explosionRadius > 0) {
applyExplosionDamage(caster, hitTarget, world, hitTarget.posX, hitTarget.posY, hitTarget.posZ);
}
spawnProjectileParticles(world, caster, hitTarget);
} else {
// No hit — spawn particles along look direction anyway
spawnProjectileParticlesInDirection(world, caster, look);
}
}
/**
* Apply explosion splash damage around a point.
*/
private void applyExplosionDamage(EntityLivingBase caster, EntityLivingBase primaryTarget, World world,
double x, double y, double z) {
@SuppressWarnings("unchecked")
List<Entity> entities = world.getEntitiesWithinAABBExcludingEntity(primaryTarget,
primaryTarget.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius));
for (Entity entity : entities) {
if (entity instanceof EntityLivingBase && entity != caster) {
EntityLivingBase living = (EntityLivingBase) entity;
float dist = primaryTarget.getDistanceToEntity(living);
if (dist < explosionRadius) {
float falloff = 1.0f - (dist / explosionRadius);
applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0);
}
}
}
world.playSoundAtEntity(primaryTarget, "random.explode", 0.5f, 1.0f);
for (int i = 0; i < 10; i++) {
world.spawnParticle("explode",
x + (world.rand.nextDouble() - 0.5) * explosionRadius,
y + world.rand.nextDouble() * 2,
z + (world.rand.nextDouble() - 0.5) * explosionRadius,
0, 0.1, 0);
}
}
private void spawnProjectileParticles(World world, EntityLivingBase caster, EntityLivingBase target) {
@@ -158,6 +224,31 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile {
}
}
/**
* Spawn projectile particles along a direction (player miss — no entity hit).
*/
private void spawnProjectileParticlesInDirection(World world, EntityLivingBase caster, Vec3 look) {
double startX = caster.posX;
double startY = caster.posY + caster.getEyeHeight();
double startZ = caster.posZ;
String particle = "flame";
if (projectileType.equals("arrow")) {
particle = "crit";
} else if (projectileType.equals("magic")) {
particle = "witchMagic";
}
int steps = (int) Math.max(5, maxRange * 2);
for (int i = 0; i < steps; i++) {
double progress = (double) i / steps * maxRange;
double px = startX + look.xCoord * progress;
double py = startY + look.yCoord * progress;
double pz = startZ + look.zCoord * progress;
world.spawnParticle(particle, px, py, pz, 0, 0, 0);
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Projectile is instant, nothing to do per-tick
@@ -256,4 +347,24 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile {
public void setHomingStrength(float homingStrength) {
this.homingStrength = homingStrength;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed)
),
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback),
FieldDef.stringEnumField("ability.projectileType", new String[]{"fireball", "arrow", "magic"}, this::getProjectileType, this::setProjectileType),
FieldDef.section("ability.section.homing"),
FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"),
FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming),
FieldDef.section("ability.section.explosive"),
FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"),
FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -11,13 +11,13 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityShockwave;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityShockwave;
import java.util.Arrays;
import java.util.List;
/**
@@ -40,19 +40,10 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave {
this.cooldownTicks = 0;
this.windUpTicks = 25;
this.telegraphType = TelegraphType.CIRCLE;
this.windUpSound = "random.explode";
this.windUpSound = "game.tnt.primed";
this.activeSound = "random.explode";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityShockwave(this, callback);
this.windUpAnimationName = "Ability_Shockwave_Windup";
this.activeAnimationName = "Ability_Shockwave_Active";
}
@Override
@@ -72,58 +63,58 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave {
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
// Shockwave is instant - apply effect immediately after windup
if (!isPreview()) {
// Shockwave is instant - apply effect immediately after windup
// Get all entities in radius
AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box);
// Get all entities in radius
AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box);
int count = 0;
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
int count = 0;
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
double dist = caster.getDistanceToEntity(entity);
if (dist > pushRadius) continue;
double dist = caster.getDistanceToEntity(entity);
if (dist > pushRadius) continue;
count++;
if (count > maxTargets) break;
count++;
if (count > maxTargets) break;
// Calculate push direction (away from caster)
double dx = entity.posX - caster.posX;
double dz = entity.posZ - caster.posZ;
double len = Math.sqrt(dx * dx + dz * dz);
// Calculate push direction (away from caster)
double dx = entity.posX - caster.posX;
double dz = entity.posZ - caster.posZ;
double len = Math.sqrt(dx * dx + dz * dz);
if (len > 0) {
dx /= len;
dz /= len;
} else {
// Entity is directly on top of caster, push in random direction
double angle = Math.random() * Math.PI * 2;
dx = Math.cos(angle);
dz = Math.sin(angle);
}
if (len > 0) {
dx /= len;
dz /= len;
} else {
// Entity is directly on top of caster, push in random direction
double angle = Math.random() * Math.PI * 2;
dx = Math.cos(angle);
dz = Math.sin(angle);
}
// Scale knockback by distance (closer = stronger)
float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f;
float finalPush = pushStrength * distFactor;
// Apply damage with custom knockback direction
boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz);
// Scale knockback by distance (closer = stronger)
float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f;
float finalPush = pushStrength * distFactor;
// Apply damage with custom knockback direction
boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz);
// Apply effects if hit connected
if (wasHit) {
applyEffects(entity);
// Apply effects if hit connected
if (wasHit) {
applyEffects(entity);
}
}
}
// Shockwave completes instantly
signalCompletion();
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Shockwave is instant - nothing to do per-tick
if (tick == 10)
signalCompletion();
}
@Override
@@ -175,4 +166,18 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave {
this.maxTargets = maxTargets;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.section("ability.section.push"),
FieldDef.row(
FieldDef.floatField("gui.radius", this::getPushRadius, this::setPushRadius),
FieldDef.floatField("gui.strength", this::getPushStrength, this::setPushStrength)
),
FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -13,13 +13,14 @@ import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilitySlam;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilitySlam;
import somehussar.gui.annotationHandling.GuiEditable;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import java.util.Arrays;
import java.util.List;
/**
@@ -64,17 +65,6 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
this.activeAnimationName = "Ability_Slam_Active";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilitySlam(this, callback);
}
/**
* Slam can be AOE_SELF (jump in place) or AOE_TARGET (leap to target).
*/
@@ -95,54 +85,114 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
@Override
public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
// Update target position during windup
if (targetingMode == TargetingMode.AOE_SELF) {
// AOE_SELF: slam at caster's current position
if (isPlayerCaster(caster)) {
// Player: slam will launch from current position, no target tracking needed
targetX = caster.posX;
targetY = caster.posY;
targetZ = caster.posZ;
} else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) {
// AOE_TARGET: telegraph follows target via setEntityIdToFollow
targetX = target.posX;
targetY = target.posY;
targetZ = target.posZ;
} else {
// NPC: update target position during windup for telegraph tracking
if (targetingMode == TargetingMode.AOE_SELF) {
targetX = caster.posX;
targetY = caster.posY;
targetZ = caster.posZ;
} else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) {
targetX = target.posX;
targetY = target.posY;
targetZ = target.posZ;
}
}
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
// Lock in the destination at moment of launch
hasLaunched = false;
hasLanded = false;
airTicks = 0;
caster.fallDistance = 0;
if (isPlayerCaster(caster)) {
executePlayerSlam(caster);
} else {
executeNpcSlam(caster, target);
}
}
/**
* NPC slam: Lock destination based on targeting mode, then launch in a ballistic arc toward it.
*/
private void executeNpcSlam(EntityLivingBase caster, EntityLivingBase target) {
if (targetingMode == TargetingMode.AOE_SELF) {
// AOE_SELF: slam in place (just jump up)
targetX = caster.posX;
targetY = caster.posY;
targetZ = caster.posZ;
} else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) {
// AOE_TARGET: leap to target's current position
targetX = target.posX;
targetY = target.posY;
targetZ = target.posZ;
} else {
// Fallback: slam in place
targetX = caster.posX;
targetY = caster.posY;
targetZ = caster.posZ;
}
hasLaunched = false;
hasLanded = false;
airTicks = 0;
// Reset fall distance to prevent fall damage during slam
caster.fallDistance = 0;
// Calculate and apply leap velocity
launchTowardTarget(caster);
}
/**
* Player slam: Launch straight up. Player controls horizontal movement via WASD.
* AOE damage triggers wherever the player lands.
*/
private void executePlayerSlam(EntityLivingBase caster) {
targetX = caster.posX;
targetY = caster.posY;
targetZ = caster.posZ;
double vy = calculateLaunchVelocity(Math.max(1.0, leapHeight));
caster.motionY = vy;
hasLaunched = true;
caster.velocityChanged = true;
}
/**
* Calculate the initial vertical velocity needed to reach a target height
* in Minecraft's physics (gravity=0.08, vertical drag=0.98).
* Uses iterative simulation since the drag makes a closed-form solution impractical.
*/
private static double calculateLaunchVelocity(double targetHeight) {
// Binary search for the initial velocity that reaches targetHeight
double lo = 0.0, hi = 10.0;
for (int iter = 0; iter < 30; iter++) {
double mid = (lo + hi) / 2.0;
double maxY = simulateMaxHeight(mid);
if (maxY < targetHeight) {
lo = mid;
} else {
hi = mid;
}
}
return (lo + hi) / 2.0;
}
/**
* Simulate Minecraft vertical physics to find peak height reached
* with a given initial upward velocity.
*/
private static double simulateMaxHeight(double vy) {
double y = 0;
double maxY = 0;
for (int t = 0; t < 200 && vy > 0; t++) {
y += vy;
vy -= 0.08; // gravity
vy *= 0.98; // vertical drag
if (y > maxY) maxY = y;
}
return maxY;
}
/**
* Calculate ballistic arc and launch caster toward target.
* Accounts for Minecraft's drag physics to actually reach the destination.
* leapHeight = exact peak height in blocks above launch point.
* leapSpeed = velocity multiplier (faster motion, same height).
*/
private void launchTowardTarget(EntityLivingBase caster) {
double dx = targetX - caster.posX;
@@ -150,17 +200,23 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
double dz = targetZ - caster.posZ;
double horizontalDist = Math.sqrt(dx * dx + dz * dz);
// Calculate vertical velocity to reach exact leapHeight
double arcHeight = Math.max(1.0, leapHeight);
double vy = calculateLaunchVelocity(arcHeight);
// For AOE_SELF or very close targets, just hop in place
if (horizontalDist < 0.5) {
caster.motionX = 0;
caster.motionZ = 0;
caster.motionY = 0.8 * leapSpeed;
caster.motionY = vy;
hasLaunched = true;
if (caster instanceof EntityNPCInterface) {
if (!isPreview() && caster instanceof EntityNPCInterface) {
((EntityNPCInterface) caster).setNpcJumpingState(true);
}
caster.velocityChanged = true;
caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f);
if (!isPreview()) {
caster.velocityChanged = true;
caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f);
}
return;
}
@@ -174,8 +230,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
targetZ = caster.posZ + dz;
}
// Choose flight time based on distance - shorter distances = faster
int flightTicks = (int) Math.max(15, Math.min(horizontalDist * 1.5, 30));
// Choose flight time based on distance, scaled by speed (faster = fewer ticks)
double speedFactor = Math.max(0.1, leapSpeed);
int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40));
// Minecraft applies drag of 0.91 per tick to horizontal motion in air
// Total distance traveled with initial velocity v0 over n ticks:
@@ -185,34 +242,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
double dragPowN = Math.pow(drag, flightTicks);
double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN);
// Scale by leap speed
vHorizontal *= leapSpeed;
// Vertical velocity calculation:
// Minecraft gravity is 0.08 per tick, with 0.98 drag on vertical motion
// For a nice arc, we want to peak roughly in the middle of the flight
double gravity = 0.08;
double verticalDrag = 0.98;
// Calculate required upward velocity to create a nice arc and land at target height
// Peak height should be proportional to horizontal distance for visual appeal
double arcHeight = Math.max(1.0, leapHeight) * leapSpeed;
// Approximate the required initial vertical velocity
// Account for gravity and drag - use a simplified model
double peakTicks = flightTicks * 0.4; // Peak around 40% through flight
double vy = (arcHeight * 2.0 / peakTicks) + (gravity * peakTicks * 0.5);
// Adjust for height difference
// Adjust vertical velocity for height difference between start and target
if (dy > 0) {
vy += dy / flightTicks * 1.5; // Going up - need more velocity
} else if (dy < 0) {
vy += dy / flightTicks * 0.3; // Going down - gravity helps
}
// Ensure minimum upward velocity for visible jump
vy = Math.max(vy, 0.6 * leapSpeed);
// Normalize horizontal direction and apply velocity
double dirX = dx / horizontalDist;
double dirZ = dz / horizontalDist;
@@ -222,16 +258,17 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
caster.motionY = vy;
hasLaunched = true;
if (caster instanceof EntityNPCInterface) {
if (!isPreview() && caster instanceof EntityNPCInterface) {
((EntityNPCInterface) caster).setNpcJumpingState(true);
}
caster.velocityChanged = true;
if (!isPreview()) {
caster.velocityChanged = true;
}
// Face the target
float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI);
caster.rotationYaw = targetYaw;
caster.rotationYawHead = targetYaw;
}
@Override
@@ -242,7 +279,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
airTicks++;
// Continuously reset fall distance during slam to prevent fall damage
caster.fallDistance = 0;
if (!isPreview()) {
caster.fallDistance = 0;
}
// Check for landing
if (caster.onGround && airTicks > 3) {
@@ -257,12 +296,15 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
return;
}
// While in air, face toward target
double dx = targetX - caster.posX;
double dz = targetZ - caster.posZ;
float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI);
caster.rotationYaw = targetYaw;
caster.rotationYawHead = targetYaw;
// NPC: face toward target destination while in air
// Player: free look — player controls their own camera
if (!isPreview() && !isPlayerCaster(caster)) {
double dx = targetX - caster.posX;
double dz = targetZ - caster.posZ;
float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI);
caster.rotationYaw = targetYaw;
caster.rotationYawHead = targetYaw;
}
}
/**
@@ -270,22 +312,25 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
*/
private void onLanding(EntityLivingBase caster, World world) {
hasLanded = true;
if (caster instanceof EntityNPCInterface) {
if (!isPreview() && caster instanceof EntityNPCInterface) {
((EntityNPCInterface) caster).setNpcJumpingState(false);
}
// Signal that the ability has completed its active phase
signalCompletion();
// Reset fall distance to prevent fall damage on landing
caster.fallDistance = 0;
// Stop horizontal momentum
caster.motionX = 0;
caster.motionZ = 0;
caster.velocityChanged = true;
if (world.isRemote) return;
if (!isPreview()) {
// Reset fall distance to prevent fall damage on landing
caster.fallDistance = 0;
caster.velocityChanged = true;
}
if (world.isRemote && !isPreview()) return;
if (isPreview()) return;
// Play slam impact sound on landing
world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f);
@@ -351,7 +396,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
@Override
public void onComplete(EntityLivingBase caster, EntityLivingBase target) {
if (caster instanceof EntityNPCInterface) {
if (!isPreview() && caster instanceof EntityNPCInterface) {
((EntityNPCInterface) caster).setNpcJumpingState(false);
}
hasLaunched = false;
@@ -361,7 +406,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
@Override
public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) {
if (caster instanceof EntityNPCInterface) {
if (!isPreview() && caster instanceof EntityNPCInterface) {
((EntityNPCInterface) caster).setNpcJumpingState(false);
}
hasLaunched = false;
@@ -377,97 +422,8 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
airTicks = 0;
}
// ==================== PREVIEW MODE ====================
private transient double previewVelX, previewVelY, previewVelZ;
private transient boolean previewLaunched = false;
private transient double previewGroundY;
@Override
@SideOnly(Side.CLIENT)
public void onPreviewExecute(EntityNPCInterface npc) {
previewLaunched = false;
double tx, ty, tz;
if (previewTarget != null && targetingMode == TargetingMode.AOE_TARGET) {
tx = previewTarget.posX;
ty = previewTarget.posY;
tz = previewTarget.posZ;
} else {
tx = npc.posX;
ty = npc.posY;
tz = npc.posZ;
}
previewGroundY = npc.posY;
double dx = tx - npc.posX;
double dz = tz - npc.posZ;
double horizontalDist = Math.sqrt(dx * dx + dz * dz);
if (horizontalDist < 0.5) {
previewVelX = 0;
previewVelZ = 0;
previewVelY = 0.8 * leapSpeed;
} else {
if (horizontalDist > maxRange) {
double scale = maxRange / horizontalDist;
dx *= scale;
dz *= scale;
horizontalDist = maxRange;
}
int flightTicks = (int) Math.max(15, Math.min(horizontalDist * 1.5, 30));
double drag = 0.91;
double dragPowN = Math.pow(drag, flightTicks);
double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN) * leapSpeed;
double arcHeight = Math.max(1.0, leapHeight) * leapSpeed;
double peakTicks = flightTicks * 0.4;
double vy = (arcHeight * 2.0 / peakTicks) + (0.08 * peakTicks * 0.5);
vy = Math.max(vy, 0.6 * leapSpeed);
double dirX = dx / horizontalDist;
double dirZ = dz / horizontalDist;
previewVelX = dirX * vHorizontal;
previewVelZ = dirZ * vHorizontal;
previewVelY = vy;
}
previewLaunched = true;
}
@Override
@SideOnly(Side.CLIENT)
public void onPreviewActiveTick(EntityNPCInterface npc, int tick) {
if (!previewLaunched) return;
// Apply velocity
npc.prevPosX = npc.posX;
npc.prevPosY = npc.posY;
npc.prevPosZ = npc.posZ;
npc.posX += previewVelX;
npc.posY += previewVelY;
npc.posZ += previewVelZ;
// Gravity and drag
previewVelY -= 0.08;
previewVelY *= 0.98;
previewVelX *= 0.91;
previewVelZ *= 0.91;
// Ground clamp - stop falling below starting Y
if (npc.posY < previewGroundY && previewVelY < 0) {
npc.posY = previewGroundY;
previewVelY = 0;
previewVelX = 0;
previewVelZ = 0;
previewLaunched = false;
}
}
@Override
public int getPreviewActiveDuration() {
public int getMaxPreviewDuration() {
return 60;
}
@@ -509,11 +465,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
TelegraphInstance instance = new TelegraphInstance(telegraph, targetX, groundY, targetZ, caster.rotationYaw);
instance.setCasterEntityId(caster.getEntityId());
// AOE_TARGET: telegraph follows target during windup
if (targetingMode == TargetingMode.AOE_TARGET && target != null) {
// NPC AOE_TARGET: telegraph follows target during windup
// Player: telegraph stays at caster position (no target to follow)
if (!isPlayerCaster(caster) && targetingMode == TargetingMode.AOE_TARGET && target != null) {
instance.setEntityIdToFollow(target.getEntityId());
}
// AOE_SELF: telegraph stays at caster position, no follow
return instance;
}
@@ -581,4 +537,22 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
public void setLeapHeight(float leapHeight) {
this.leapHeight = leapHeight;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.row(
FieldDef.floatField("gui.radius", this::getRadius, this::setRadius),
FieldDef.floatField("ability.knockback", this::getKnockbackStrength, this::setKnockbackStrength)
),
FieldDef.section("ability.section.leap"),
FieldDef.row(
FieldDef.floatField("gui.speed", this::getLeapSpeed, this::setLeapSpeed),
FieldDef.floatField("gui.height", this::getLeapHeight, this::setLeapHeight)
),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -5,7 +5,9 @@ import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.data.EnergyColorData;
import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
@@ -13,12 +15,11 @@ import kamkeel.npcs.entity.EntityAbilitySweeper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import noppes.npcs.LogWriter;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilitySweeper;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.api.ability.type.IAbilitySweeper;
import java.util.Arrays;
import java.util.List;
/**
* Sweeper ability: A low sweeping beam that rotates around the NPC.
* Players can jump over it. The beam completes a set number of rotations before ending.
@@ -41,7 +42,7 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper {
private boolean lockOnTarget = false;
// Visual properties
private EnergyColorData colorData = new EnergyColorData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f);
private EnergyDisplayData colorData = new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f);
// Runtime state (transient)
private transient EntityAbilitySweeper activeEntity = null;
@@ -61,14 +62,8 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper {
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilitySweeper(this, callback);
public boolean allowBurst() {
return false;
}
@Override
@@ -83,19 +78,26 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper {
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) {
if (world.isRemote && !isPreview()) {
signalCompletion();
return;
}
// Spawn the entity that handles BOTH visuals AND damage
// Spawn the sweeper entity that handles BOTH visuals AND damage.
// NPC: target is the aggro target — lockOnTarget tracks it during sweep.
// Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect.
activeEntity = new EntityAbilitySweeper(world, caster, target,
beamLength, beamWidth, beamHeight,
colorData,
sweepSpeed, numberOfRotations,
damage, damageInterval, piercing,
lockOnTarget);
world.spawnEntityInWorld(activeEntity);
if (isPreview()) {
activeEntity.setupPreview(caster);
}
spawnAbilityEntity(world, activeEntity);
// Ability stays active until entity dies (prevents firing another while projectile is alive)
// Movement locking is handled separately by the base class
@@ -110,6 +112,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper {
}
}
@Override
public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) {
cleanup();
}
@Override
public void cleanup() {
// Clean up entity if still alive
@@ -204,4 +211,49 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper {
public void setOuterColorWidth(float outerColorWidth) { colorData.outerColorWidth = outerColorWidth; }
public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; }
public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; }
@Override
public int getMaxPreviewDuration() {
return (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval)
),
FieldDef.section("ability.section.beam"),
FieldDef.row(
FieldDef.floatField("gui.length", this::getBeamLength, this::setBeamLength),
FieldDef.floatField("gui.width", this::getBeamWidth, this::setBeamWidth)
),
FieldDef.row(
FieldDef.floatField("gui.height", this::getBeamHeight, this::setBeamHeight),
FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed)
),
FieldDef.intField("ability.rotations", this::getNumberOfRotations, this::setNumberOfRotations),
FieldDef.row(
FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing)
.hover("ability.hover.piercing"),
FieldDef.boolField("ability.lockTarget", this::isLockOnTarget, this::setLockOnTarget)
.hover("ability.hover.lockTarget")
),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects),
// Visual tab
FieldDef.section("ability.section.colors").tab("ability.tab.visual"),
FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor)
.tab("ability.tab.visual"),
FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled)
.tab("ability.tab.visual"),
FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled),
FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth)
.tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)
));
}
}
@@ -1,10 +1,9 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
@@ -14,13 +13,17 @@ import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityTeleport;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilityTeleport;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
@@ -35,7 +38,17 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
public enum TeleportMode {
BLINK,
BEHIND,
SINGLE
SINGLE;
@Override
public String toString() {
switch (this) {
case BLINK: return "ability.teleport.blink";
case BEHIND: return "ability.teleport.behind";
case SINGLE: return "ability.teleport.single";
default: return name();
}
}
}
private static final Random RANDOM = new Random();
@@ -60,6 +73,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
this.typeId = "ability.cnpc.teleport";
this.name = "Teleport";
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.allowedBy = UserType.NPC_ONLY;
this.maxRange = 30.0f;
this.minRange = 5.0f;
this.cooldownTicks = 0;
@@ -73,15 +87,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(
IAbilityConfigCallback callback) {
return new SubGuiAbilityTeleport(this, callback);
public boolean hasDamage() {
return false;
}
@Override
@@ -123,7 +130,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
}
private void performBlink(EntityLivingBase caster, EntityLivingBase target, World world) {
if (world.isRemote) return;
if (world.isRemote && !isPreview()) return;
double oldX = caster.posX;
double oldY = caster.posY;
@@ -132,36 +139,47 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
Vec3 destination = calculateDestination(caster, target, world);
if (destination == null) return;
boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight;
if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ,
destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) {
destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ,
if (!isPreview()) {
boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight;
if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ,
destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) {
destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ,
destination.xCoord, destination.yCoord, destination.zCoord);
if (destination == null) return;
}
destination = findSafeDestination(world, oldX, oldY, oldZ,
destination.xCoord, destination.yCoord, destination.zCoord);
if (destination == null) return;
// Damage at origin
if (damageAtStart) {
dealDamageAt(caster, world, oldX, oldY, oldZ);
}
// Spawn particles at origin
spawnTeleportParticles(world, oldX, oldY, oldZ);
}
destination = findSafeDestination(world, oldX, oldY, oldZ,
destination.xCoord, destination.yCoord, destination.zCoord);
if (destination == null) return;
// Damage at origin
if (damageAtStart) {
dealDamageAt(caster, world, oldX, oldY, oldZ);
}
// Spawn particles at origin
spawnTeleportParticles(world, oldX, oldY, oldZ);
// Teleport
caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord);
if (isPreview()) {
caster.setPosition(destination.xCoord, destination.yCoord, destination.zCoord);
caster.prevPosX = destination.xCoord;
caster.prevPosY = destination.yCoord;
caster.prevPosZ = destination.zCoord;
} else {
caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord);
}
caster.fallDistance = 0;
// Spawn particles at destination
spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord);
if (!isPreview()) {
// Spawn particles at destination
spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord);
// Damage at destination
if (damageAtEnd) {
dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord);
// Damage at destination
if (damageAtEnd) {
dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord);
}
}
// Face target after teleport
@@ -212,26 +230,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
}
}
// No target (player use) - teleport in caster's look direction
Vec3 look = caster.getLookVec();
switch (mode) {
case BEHIND:
// Teleport forward in look direction by behindDistance
newX = caster.posX + look.xCoord * behindDistance;
newZ = caster.posZ + look.zCoord * behindDistance;
newY = caster.posY;
return Vec3.createVectorHelper(newX, newY, newZ);
case SINGLE:
case BLINK:
default:
// Teleport forward in look direction within blinkRadius
double dist = Math.min(blinkRadius, maxRange);
double offset = (RANDOM.nextDouble() * 0.5 + 0.5) * dist; // 50-100% of max distance
newX = caster.posX + look.xCoord * offset;
newZ = caster.posZ + look.zCoord * offset;
newY = caster.posY;
return Vec3.createVectorHelper(newX, newY, newZ);
}
// NPC-only ability — should not reach here
return null;
}
private Vec3 findSafeDestination(World world, double oldX, double oldY, double oldZ,
@@ -555,4 +555,43 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
public void setDamageRadius(float damageRadius) {
this.damageRadius = damageRadius;
}
@Override
public int getMaxPreviewDuration() {
int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1;
return blinkLimit * blinkDelayTicks + 10;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.enumField("ability.mode", TeleportMode.class, this::getModeEnum, this::setModeEnum),
FieldDef.floatField("ability.blinkRadius", this::getBlinkRadius, this::setBlinkRadius)
.visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK || this.getModeEnum() == TeleportMode.SINGLE),
FieldDef.row(
FieldDef.intField("ability.blinkCount", this::getBlinkCount, this::setBlinkCount)
.visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK),
FieldDef.intField("ability.blinkDelay", this::getBlinkDelayTicks, this::setBlinkDelayTicks)
.visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK)
),
FieldDef.floatField("ability.behindDistance", this::getBehindDistance, this::setBehindDistance)
.visibleWhen(() -> this.getModeEnum() == TeleportMode.BEHIND),
FieldDef.boolField("ability.lineOfSight", this::isRequireLineOfSight, this::setRequireLineOfSight)
.hover("ability.hover.lineOfSight")
.visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK || this.getModeEnum() == TeleportMode.SINGLE),
FieldDef.section("ability.section.damage"),
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("gui.radius", this::getDamageRadius, this::setDamageRadius)
),
FieldDef.row(
FieldDef.boolField("ability.damageAtStart", this::isDamageAtStart, this::setDamageAtStart)
.hover("ability.hover.dmgAtStart"),
FieldDef.boolField("ability.damageAtEnd", this::isDamageAtEnd, this::setDamageAtEnd)
.hover("ability.hover.dmgAtEnd")
),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -1,10 +1,9 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
@@ -12,13 +11,17 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityTrap;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilityTrap;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
@@ -34,7 +37,17 @@ public class AbilityTrap extends Ability implements IAbilityTrap {
public enum TrapPlacement {
AT_CASTER,
AT_TARGET,
AHEAD_OF_CASTER
AHEAD_OF_CASTER;
@Override
public String toString() {
switch (this) {
case AT_CASTER: return "ability.trapPlace.atCaster";
case AT_TARGET: return "ability.trapPlace.atTarget";
case AHEAD_OF_CASTER: return "ability.trapPlace.aheadOfCaster";
default: return name();
}
}
}
private int durationTicks = 200;
@@ -71,17 +84,12 @@ public class AbilityTrap extends Ability implements IAbilityTrap {
this.cooldownTicks = 0;
this.windUpTicks = 20;
this.telegraphType = TelegraphType.CIRCLE;
this.allowedBy = UserType.NPC_ONLY;
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) {
return new SubGuiAbilityTrap(this, callback);
public boolean allowBurst() {
return false;
}
@Override
@@ -122,7 +130,6 @@ public class AbilityTrap extends Ability implements IAbilityTrap {
}
break;
case AT_TARGET:
// Telegraph follows target during windup, locks on execute
if (target != null) {
instance.setEntityIdToFollow(target.getEntityId());
}
@@ -148,14 +155,12 @@ public class AbilityTrap extends Ability implements IAbilityTrap {
trapZ = caster.posZ;
break;
case AT_TARGET:
// Use telegraph position with offset
if (telegraph != null) {
double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(),
minOffset, maxOffset, randomOffset, RANDOM);
trapX = pos[0];
trapY = pos[1];
trapZ = pos[2];
// Update telegraph to show actual trap position
telegraph.setX(trapX);
telegraph.setY(trapY);
telegraph.setZ(trapZ);
@@ -206,26 +211,28 @@ public class AbilityTrap extends Ability implements IAbilityTrap {
return;
}
AxisAlignedBB box = AxisAlignedBB.getBoundingBox(
trapX - triggerRadius, trapY - 1, trapZ - triggerRadius,
trapX + triggerRadius, trapY + 2, trapZ + triggerRadius
);
if (!isPreview()) {
AxisAlignedBB box = AxisAlignedBB.getBoundingBox(
trapX - triggerRadius, trapY - 1, trapZ - triggerRadius,
trapX + triggerRadius, trapY + 2, trapZ + triggerRadius
);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box);
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue;
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue;
double dx = entity.posX - trapX;
double dz = entity.posZ - trapZ;
double dist = Math.sqrt(dx * dx + dz * dz);
double dx = entity.posX - trapX;
double dz = entity.posZ - trapZ;
double dist = Math.sqrt(dx * dx + dz * dz);
if (dist <= triggerRadius) {
triggerTrap(caster, entity, world);
return;
if (dist <= triggerRadius) {
triggerTrap(caster, entity, world);
return;
}
}
}
}
@@ -464,4 +471,31 @@ public class AbilityTrap extends Ability implements IAbilityTrap {
public boolean isArmed() {
return armed;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks)
.range(1, 2000),
FieldDef.enumField("ability.placement", TrapPlacement.class, this::getPlacementEnum, this::setPlacementEnum)
.hover("ability.hover.placement"),
FieldDef.section("ability.section.trigger"),
FieldDef.row(
FieldDef.floatField("gui.radius", this::getTriggerRadius, this::setTriggerRadius),
FieldDef.intField("ability.armTime", this::getArmTime, this::setArmTime)
),
FieldDef.row(
FieldDef.intField("ability.maxTriggers", this::getMaxTriggers, this::setMaxTriggers),
FieldDef.intField("ability.triggerCooldown", this::getTriggerCooldown, this::setTriggerCooldown)
),
FieldDef.section("ability.section.damage"),
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("gui.radius", this::getDamageRadius, this::setDamageRadius)
),
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -1,7 +1,5 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.LockMovementType;
import kamkeel.npcs.controllers.data.ability.TargetingMode;
@@ -10,13 +8,16 @@ import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityVortex;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.client.gui.builder.FieldDef;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import noppes.npcs.api.ability.type.IAbilityVortex;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -62,18 +63,6 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
this.activeSound = "mob.ghast.fireball";
}
@Override
public boolean hasTypeSettings() {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiAbilityConfig createConfigGui(
IAbilityConfigCallback callback) {
return new SubGuiAbilityVortex(this, callback);
}
@Override
public boolean isTargetingModeLocked() {
return true;
@@ -95,29 +84,32 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
pullComplete = false;
ticksSincePullDamage = 0;
if (aoe) {
AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box);
if (!isPreview()) {
if (aoe) {
AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius);
@SuppressWarnings("unchecked")
List<EntityLivingBase> entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box);
int count = 0;
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
int count = 0;
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
double dist = caster.getDistanceToEntity(entity);
if (dist <= pullRadius) {
getPulledEntities().add(entity.getUniqueID());
count++;
if (count >= maxTargets) break;
double dist = caster.getDistanceToEntity(entity);
if (dist <= pullRadius) {
getPulledEntities().add(entity.getUniqueID());
count++;
if (count >= maxTargets) break;
}
}
}
} else {
// Single target mode - still check pullRadius
if (target != null && !target.isDead) {
double dist = caster.getDistanceToEntity(target);
if (dist <= pullRadius) {
getPulledEntities().add(target.getUniqueID());
} else {
// NPC single-target mode: pull the aggro target
// Player: single-target mode has no effect (no target to pull — use AOE mode instead)
if (!isPlayerCaster(caster) && target != null && !target.isDead) {
double dist = caster.getDistanceToEntity(target);
if (dist <= pullRadius) {
getPulledEntities().add(target.getUniqueID());
}
}
}
}
@@ -125,6 +117,12 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) {
if (isPreview()) {
// No entities to pull in preview, just run animation for a duration
if (tick >= 60) signalCompletion();
return;
}
if (pullComplete || getPulledEntities().isEmpty()) {
signalCompletion();
return;
@@ -149,7 +147,7 @@ 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.0f) {
if (dist <= 1.5f) {
getPulledEntities().remove(uuid);
onTargetArrived(caster, entity, world);
continue;
@@ -157,7 +155,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
anyStillPulling = true;
double factor = pullStrength / dist;
// Clamp speed to never exceed half the remaining distance, preventing overshoot/slingshot
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;
@@ -309,4 +310,31 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
public void setPullDamage(float pullDamage) {
this.pullDamage = pullDamage;
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.row(
FieldDef.floatField("ability.pullRadius", this::getPullRadius, this::setPullRadius),
FieldDef.floatField("ability.pullStrength", this::getPullStrength, this::setPullStrength)
),
FieldDef.section("ability.section.damage"),
FieldDef.row(
FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage),
FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)
),
FieldDef.section("ability.section.aoe"),
FieldDef.boolField("gui.enabled", this::isAoe, this::setAoe)
.hover("ability.hover.aoe"),
FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets)
.visibleWhen(this::isAoe),
FieldDef.section("ability.section.pullDamage"),
FieldDef.boolField("gui.enabled", this::isDamageOnPull, this::setDamageOnPull)
.hover("ability.hover.dmgOnPull"),
FieldDef.floatField("enchantment.damage", this::getPullDamage, this::setPullDamage)
.visibleWhen(this::isDamageOnPull),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
}
}
@@ -1,6 +1,5 @@
package kamkeel.npcs.entity;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
@@ -27,12 +26,6 @@ import java.util.List;
*/
public class EntityAbilityBeam extends EntityAbilityProjectile {
// Beam-specific movement properties
private float speed = 0.5f;
private boolean homing = true;
private float homingStrength = 0.35f; // Increased from 0.15 for better tracking
private float homingRange = 20.0f;
// Beam shape properties
private float beamWidth = 0.3f;
private float headSize = 0.5f;
@@ -57,7 +50,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
private int chargeDuration = 40;
private int chargeTick = 0;
private float chargeOffsetDistance = 1.0f;
private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT);
// Trail fading for non-anchored beams (comet effect)
private boolean fadeTrail = false;
@@ -108,22 +100,20 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
* If false, beam is free-moving with trailing length (no tail orb).
*/
public EntityAbilityBeam(World world, EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z,
float beamWidth, float headSize,
EnergyColorData color, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan,
boolean anchoredMode) {
double x, double y, double z,
float beamWidth, float headSize,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory,
boolean anchoredMode) {
super(world);
// Initialize base properties via parent
initProjectile(owner, target, x, y, z, headSize, color, combat, lightning, lifespan);
initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan, trajectory);
// Beam-specific properties from homing data
this.speed = homing.speed;
this.homing = homing.homing;
this.homingStrength = homing.homingStrength;
this.homingRange = homing.homingRange;
this.homingData = homing;
this.beamWidth = beamWidth;
this.headSize = headSize;
@@ -153,16 +143,16 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
double dz = target.posZ - z;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
this.motionX = (dx / len) * speed;
this.motionY = (dy / len) * speed;
this.motionZ = (dz / len) * speed;
this.motionX = (dx / len) * getSpeed();
this.motionY = (dy / len) * getSpeed();
this.motionZ = (dz / len) * getSpeed();
}
} else {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
this.motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
this.motionY = -Math.sin(pitch) * speed;
this.motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
this.motionY = -Math.sin(pitch) * getSpeed();
this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
}
}
@@ -178,7 +168,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
this.motionZ = 0;
}
public void setupPreview(EntityLivingBase owner, float beamWidth, float headSize, EnergyColorData color, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) {
public void setupPreview(EntityLivingBase owner, float beamWidth, float headSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) {
this.setPreviewMode(true);
this.setPreviewOwner(owner);
@@ -186,15 +176,8 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
this.beamWidth = beamWidth;
this.headSize = headSize;
this.size = headSize;
this.innerColor = color.innerColor;
this.outerColor = color.outerColor;
this.outerColorEnabled = color.outerColorEnabled;
this.outerColorWidth = color.outerColorWidth;
this.outerColorAlpha = color.outerColorAlpha;
this.rotationSpeed = color.rotationSpeed;
this.lightningEffect = lightning.lightningEffect;
this.lightningDensity = lightning.lightningDensity;
this.lightningRadius = lightning.lightningRadius;
this.displayData = display;
this.lightningData = lightning;
// Set charging state
this.setCharging(true);
@@ -239,26 +222,41 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
setCharging(false);
// Update start position to current position
// Origin (tail) stays at the charged position
startX = posX;
startY = posY;
startZ = posZ;
// Reset head offset to origin
headOffsetX = 0;
headOffsetY = 0;
headOffsetZ = 0;
prevHeadOffsetX = 0;
prevHeadOffsetY = 0;
prevHeadOffsetZ = 0;
// Origin no longer follows owner after firing
attachedToOwner = false;
// Sync prev position to prevent visual jump on first frame
prevPosX = posX;
prevPosY = posY;
prevPosZ = posZ;
// Reset trail
trailPoints.clear();
trailPointAges.clear();
trailPoints.add(Vec3.createVectorHelper(0, 0, 0));
// Fire forward based on owner facing direction
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = 0; // Fire horizontally
motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
motionY = -Math.sin(pitch) * speed;
motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
motionX = -Math.sin(yaw) * getSpeed();
motionY = 0;
motionZ = Math.cos(yaw) * getSpeed();
} else {
motionX = speed;
motionX = getSpeed();
motionY = 0;
motionZ = 0;
}
@@ -301,7 +299,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
if (fadeTrail) trailPointAges.add(0);
// Calculate velocity toward target (head starts at origin = startX/Y/Z)
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (target != null) {
double dx = target.posX - startX;
@@ -309,16 +307,16 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
double dz = target.posZ - startZ;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
motionX = (dx / len) * speed;
motionY = (dy / len) * speed;
motionZ = (dz / len) * speed;
motionX = (dx / len) * getSpeed();
motionY = (dy / len) * getSpeed();
motionZ = (dz / len) * getSpeed();
}
} else if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
motionY = -Math.sin(pitch) * speed;
motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
motionY = -Math.sin(pitch) * getSpeed();
motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
}
if (DEBUG_LOGGING && !worldObj.isRemote) {
@@ -336,9 +334,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
headOffsetY * headOffsetY +
headOffsetZ * headOffsetZ
);
boolean exceeded = distFromOrigin >= maxDistance;
boolean exceeded = distFromOrigin >= getMaxDistance();
if (exceeded && !worldObj.isRemote && DEBUG_LOGGING) {
LogWriter.info("[Beam] DEAD: Max distance exceeded. dist=" + distFromOrigin + " max=" + maxDistance);
LogWriter.info("[Beam] DEAD: Max distance exceeded. dist=" + distFromOrigin + " max=" + getMaxDistance());
}
return exceeded;
}
@@ -392,7 +390,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
// Update origin if attached to owner
if (attachedToOwner) {
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner != null) {
startX = owner.posX;
startY = owner.posY + owner.getEyeHeight() * 0.7;
@@ -436,7 +434,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
private void updateCharging() {
chargeTick++;
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner == null || owner.isDead) {
setDead();
return;
@@ -458,13 +456,11 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
);
}
// Offset downward by half headSize to center
double centeredY = pos.yCoord - headSize * 0.5;
setPosition(pos.xCoord, centeredY, pos.zCoord);
setPosition(pos.xCoord, pos.yCoord, pos.zCoord);
// Also update origin for when firing starts
startX = pos.xCoord;
startY = centeredY;
startY = pos.yCoord;
startZ = pos.zCoord;
}
@@ -529,7 +525,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
// Update origin if attached to owner
if (attachedToOwner) {
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner != null) {
startX = owner.posX;
startY = owner.posY + owner.getEyeHeight() * 0.7;
@@ -550,9 +546,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
}
private void updateHoming() {
if (!homing) return;
if (!isHoming()) return;
Entity target = getTarget();
Entity target = getTargetEntity();
if (target == null || !target.isEntityAlive()) return;
// Calculate world position of head
@@ -565,18 +561,18 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
double dz = target.posZ - headWorldZ;
double dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist <= homingRange && dist > 0) {
if (dist <= getHomingRange() && dist > 0) {
// Calculate effective homing strength - increases when closer to commit to target
float effectiveStrength = homingStrength;
if (dist < homingRange * 0.3) {
effectiveStrength = Math.min(1.0f, homingStrength * 2.5f);
} else if (dist < homingRange * 0.6) {
effectiveStrength = Math.min(0.8f, homingStrength * 1.5f);
float effectiveStrength = getHomingStrength();
if (dist < getHomingRange() * 0.3) {
effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f);
} else if (dist < getHomingRange() * 0.6) {
effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f);
}
double desiredVX = (dx / dist) * speed;
double desiredVY = (dy / dist) * speed;
double desiredVZ = (dz / dist) * speed;
double desiredVX = (dx / dist) * getSpeed();
double desiredVY = (dy / dist) * getSpeed();
double desiredVZ = (dz / dist) * getSpeed();
motionX += (desiredVX - motionX) * effectiveStrength;
motionY += (desiredVY - motionY) * effectiveStrength;
@@ -584,9 +580,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ);
if (vLen > 0) {
motionX = (motionX / vLen) * speed;
motionY = (motionY / vLen) * speed;
motionZ = (motionZ / vLen) * speed;
motionX = (motionX / vLen) * getSpeed();
motionY = (motionY / vLen) * getSpeed();
motionZ = (motionZ / vLen) * getSpeed();
}
}
}
@@ -604,7 +600,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
hasHit = true;
if (explosive) {
if (isExplosive()) {
posX = blockHit.hitVec.xCoord;
posY = blockHit.hitVec.yCoord;
posZ = blockHit.hitVec.zCoord;
@@ -632,7 +628,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
}
hasHit = true;
if (explosive) {
if (isExplosive()) {
posX = headX;
posY = headY;
posZ = headZ;
@@ -748,10 +744,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
@Override
protected void readProjectileNBT(NBTTagCompound nbt) {
this.speed = nbt.hasKey("Speed") ? nbt.getFloat("Speed") : 0.5f;
this.homing = !nbt.hasKey("Homing") || nbt.getBoolean("Homing");
this.homingStrength = nbt.hasKey("HomingStrength") ? nbt.getFloat("HomingStrength") : 0.15f;
this.homingRange = nbt.hasKey("HomingRange") ? nbt.getFloat("HomingRange") : 20.0f;
this.beamWidth = nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f;
this.headSize = nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f;
this.headOffsetX = nbt.hasKey("HeadOffsetX") ? nbt.getDouble("HeadOffsetX") : 0;
@@ -772,7 +764,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
this.fadeTrail = nbt.hasKey("FadeTrail") && nbt.getBoolean("FadeTrail");
this.trailFadeTime = nbt.hasKey("TrailFadeTime") ? nbt.getInteger("TrailFadeTime") : 20;
this.anchorData.readNBT(nbt);
// Read trail points (relative to origin)
trailPoints.clear();
@@ -791,10 +782,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile {
@Override
protected void writeProjectileNBT(NBTTagCompound nbt) {
nbt.setFloat("Speed", speed);
nbt.setBoolean("Homing", homing);
nbt.setFloat("HomingStrength", homingStrength);
nbt.setFloat("HomingRange", homingRange);
nbt.setFloat("BeamWidth", beamWidth);
nbt.setFloat("HeadSize", headSize);
nbt.setDouble("HeadOffsetX", headOffsetX);
@@ -1,6 +1,5 @@
package kamkeel.npcs.entity;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
@@ -21,11 +20,7 @@ import java.util.List;
*/
public class EntityAbilityDisc extends EntityAbilityProjectile {
// Disc-specific movement properties
private float speed = 0.5f;
private boolean homing = true;
private float homingStrength = 0.35f; // Increased from 0.15 for better tracking
private float homingRange = 20.0f;
// Disc-specific movement propertie
// Boomerang properties
private boolean boomerang = false;
@@ -36,6 +31,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
// Disc shape properties
private float discRadius = 1.0f; // Width of disc
private float discThickness = 0.2f; // Height of disc
private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward)
// Charging state (during windup)
private boolean charging = false;
@@ -43,7 +39,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
private int chargeTick = 0;
private float targetDiscRadius = 1.0f; // Full radius to grow to during charging
private float targetDiscThickness = 0.2f; // Full thickness to grow to during charging
private EnergyAnchorData anchorData = new EnergyAnchorData();
// Data watcher index for charging state (synced to clients)
private static final int DW_CHARGING = 20;
@@ -84,22 +79,18 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
* Full constructor with all parameters using data classes.
*/
public EntityAbilityDisc(World world, EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z,
float discRadius, float discThickness,
EnergyColorData color, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan,
boolean boomerang, int boomerangDelay) {
double x, double y, double z,
float discRadius, float discThickness,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory,
boolean boomerang, int boomerangDelay) {
super(world);
// Initialize base properties
initProjectile(owner, target, x, y, z, discRadius, color, combat, lightning, lifespan);
initProjectile(owner, target, x, y, z, discRadius, display, combat, lightning, lifespan, trajectory);
// Disc-specific properties from homing data
this.speed = homing.speed;
this.homing = homing.homing;
this.homingStrength = homing.homingStrength;
this.homingRange = homing.homingRange;
this.homingData = homing;
this.boomerang = boomerang;
this.boomerangDelay = boomerangDelay;
@@ -114,16 +105,16 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
double dz = target.posZ - z;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
this.motionX = (dx / len) * speed;
this.motionY = (dy / len) * speed;
this.motionZ = (dz / len) * speed;
this.motionX = (dx / len) * getSpeed();
this.motionY = (dy / len) * getSpeed();
this.motionZ = (dz / len) * getSpeed();
}
} else {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
this.motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
this.motionY = -Math.sin(pitch) * speed;
this.motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
this.motionY = -Math.sin(pitch) * getSpeed();
this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
}
}
@@ -132,11 +123,12 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
* The disc will grow from 0 to discRadius over chargeDuration ticks.
* Position follows the owner based on anchor point.
*/
public void setupCharging(EnergyAnchorData anchor, int chargeDuration) {
public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) {
setCharging(true);
this.chargeDuration = chargeDuration;
this.chargeTick = 0;
this.anchorData = anchor;
this.vertical = vertical;
this.targetDiscRadius = this.discRadius;
this.targetDiscThickness = this.discThickness;
this.discRadius = 0.01f;
@@ -154,25 +146,20 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
* Follows anchor point and animations like in the real game.
* Can be fired when transitioning to active phase.
*/
public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyColorData color, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) {
public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, boolean vertical) {
this.setPreviewMode(true);
this.setPreviewOwner(owner);
// Set visual properties
this.innerColor = color.innerColor;
this.outerColor = color.outerColor;
this.outerColorEnabled = color.outerColorEnabled;
this.outerColorWidth = color.outerColorWidth;
this.rotationSpeed = color.rotationSpeed;
this.lightningEffect = lightning.lightningEffect;
this.lightningDensity = lightning.lightningDensity;
this.lightningRadius = lightning.lightningRadius;
this.displayData = display;
this.lightningData = lightning;
// Set charging state
this.setCharging(true);
this.chargeDuration = chargeDuration;
this.chargeTick = 0;
this.anchorData = anchor;
this.vertical = vertical;
// Store target size and start at 0 for grow effect
this.targetDiscRadius = discRadius;
@@ -216,15 +203,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
prevPosZ = posZ;
// Fire forward based on owner facing direction
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = 0; // Fire horizontally
motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
motionY = -Math.sin(pitch) * speed;
motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
motionY = -Math.sin(pitch) * getSpeed();
motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
} else {
motionX = speed;
motionX = getSpeed();
motionY = 0;
motionZ = 0;
}
@@ -245,7 +232,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
startZ = posZ;
// Calculate velocity toward target
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (target != null) {
double dx = target.posX - posX;
@@ -253,23 +240,23 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
double dz = target.posZ - posZ;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
motionX = (dx / len) * speed;
motionY = (dy / len) * speed;
motionZ = (dz / len) * speed;
motionX = (dx / len) * getSpeed();
motionY = (dy / len) * getSpeed();
motionZ = (dz / len) * getSpeed();
}
} else if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
motionY = -Math.sin(pitch) * speed;
motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
motionY = -Math.sin(pitch) * getSpeed();
motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
}
}
@Override
protected void updateRotation() {
// Disc spins ONLY on Y axis (flat spin like a saw blade)
this.rotationValY += rotationSpeed;
this.rotationValY += getRotationSpeed();
// No wobble - keep X and Z at 0 for stable flight
if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f;
}
@@ -312,7 +299,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
if (this.isCollidedHorizontally || this.isCollidedVertically) {
if (!worldObj.isRemote) {
hasHit = true;
if (explosive) {
if (isExplosive()) {
doExplosion();
}
}
@@ -331,14 +318,14 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
if (boomerang) {
// If not returning yet, check if we should start returning
if (!returning && !hasHit) {
if (distTraveled >= maxDistance * 0.8 || ticksSinceMiss >= boomerangDelay) {
if (distTraveled >= getMaxDistance() * 0.8 || ticksSinceMiss >= boomerangDelay) {
returning = true;
}
}
// If returning, only die when close to owner
if (returning) {
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner != null) {
double distToOwner = Math.sqrt(
(posX - owner.posX) * (posX - owner.posX) +
@@ -356,7 +343,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
}
// Non-boomerang: standard max distance check
return distTraveled >= maxDistance;
return distTraveled >= getMaxDistance();
}
/**
@@ -370,9 +357,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
}
private void updateHoming() {
if (!homing) return;
if (!isHoming()) return;
Entity target = getTarget();
Entity target = getTargetEntity();
if (target == null || !target.isEntityAlive()) return;
double dx = target.posX - posX;
@@ -380,18 +367,18 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
double dz = target.posZ - posZ;
double dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist <= homingRange && dist > 0) {
if (dist <= getHomingRange() && dist > 0) {
// Calculate effective homing strength - increases when closer to commit to target
float effectiveStrength = homingStrength;
if (dist < homingRange * 0.3) {
effectiveStrength = Math.min(1.0f, homingStrength * 2.5f);
} else if (dist < homingRange * 0.6) {
effectiveStrength = Math.min(0.8f, homingStrength * 1.5f);
float effectiveStrength = getHomingStrength();
if (dist < getHomingRange() * 0.3) {
effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f);
} else if (dist < getHomingRange() * 0.6) {
effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f);
}
double desiredVX = (dx / dist) * speed;
double desiredVY = (dy / dist) * speed;
double desiredVZ = (dz / dist) * speed;
double desiredVX = (dx / dist) * getSpeed();
double desiredVY = (dy / dist) * getSpeed();
double desiredVZ = (dz / dist) * getSpeed();
motionX += (desiredVX - motionX) * effectiveStrength;
motionY += (desiredVY - motionY) * effectiveStrength;
@@ -399,15 +386,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ);
if (vLen > 0) {
motionX = (motionX / vLen) * speed;
motionY = (motionY / vLen) * speed;
motionZ = (motionZ / vLen) * speed;
motionX = (motionX / vLen) * getSpeed();
motionY = (motionY / vLen) * getSpeed();
motionZ = (motionZ / vLen) * getSpeed();
}
}
}
private void updateReturnToOwner() {
Entity owner = getOwner();
Entity owner = getOwnerEntity();
// If owner is gone (unloaded/dead), head back toward start position
double targetX, targetY, targetZ;
@@ -429,10 +416,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
if (dist > 0) {
// Stronger homing when returning
double returnStrength = Math.min(1.0, homingStrength * 2.5);
double desiredVX = (dx / dist) * speed;
double desiredVY = (dy / dist) * speed;
double desiredVZ = (dz / dist) * speed;
double returnStrength = Math.min(1.0, getHomingStrength() * 2.5);
double desiredVX = (dx / dist) * getSpeed();
double desiredVY = (dy / dist) * getSpeed();
double desiredVZ = (dz / dist) * getSpeed();
motionX += (desiredVX - motionX) * returnStrength;
motionY += (desiredVY - motionY) * returnStrength;
@@ -440,9 +427,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ);
if (vLen > 0) {
motionX = (motionX / vLen) * speed;
motionY = (motionY / vLen) * speed;
motionZ = (motionZ / vLen) * speed;
motionX = (motionX / vLen) * getSpeed();
motionY = (motionY / vLen) * getSpeed();
motionZ = (motionZ / vLen) * getSpeed();
}
}
}
@@ -455,7 +442,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
hasHit = true;
if (explosive) {
if (isExplosive()) {
posX = blockHit.hitVec.xCoord;
posY = blockHit.hitVec.yCoord;
posZ = blockHit.hitVec.zCoord;
@@ -482,7 +469,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
hasHit = true;
if (explosive) {
if (isExplosive()) {
doExplosion();
} else {
applyDamage(entity);
@@ -499,7 +486,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
private void updateCharging() {
chargeTick++;
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner == null || owner.isDead) {
setDead();
return;
@@ -541,14 +528,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
// ==================== GETTERS ====================
public float getSpeed() {
return speed;
}
public boolean isHoming() {
return homing;
}
public float getDiscRadius() {
return discRadius;
}
@@ -565,18 +544,37 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
return returning;
}
public boolean isVertical() {
return vertical;
}
/**
* Get the yaw angle (degrees) from motion vector for vertical disc orientation.
* During charging, uses owner's facing direction.
*/
public float getTravelYaw() {
if (isCharging()) {
Entity owner = previewMode ? previewOwner : getOwnerEntity();
if (owner != null) {
return owner.rotationYaw;
}
}
double speed = Math.sqrt(motionX * motionX + motionZ * motionZ);
if (speed > 0.001) {
return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI);
}
return 0.0f;
}
// ==================== NBT ====================
@Override
protected void readProjectileNBT(NBTTagCompound nbt) {
this.speed = nbt.hasKey("Speed") ? nbt.getFloat("Speed") : 0.5f;
this.homing = !nbt.hasKey("Homing") || nbt.getBoolean("Homing");
this.homingStrength = nbt.hasKey("HomingStrength") ? nbt.getFloat("HomingStrength") : 0.15f;
this.homingRange = nbt.hasKey("HomingRange") ? nbt.getFloat("HomingRange") : 20.0f;
this.boomerang = nbt.hasKey("Boomerang") && nbt.getBoolean("Boomerang");
this.boomerangDelay = nbt.hasKey("BoomerangDelay") ? nbt.getInteger("BoomerangDelay") : 40;
this.discRadius = nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f;
this.discThickness = nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f;
this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false;
this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning");
// Charging state
boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging");
@@ -586,19 +584,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0;
this.targetDiscRadius = nbt.hasKey("TargetDiscRadius") ? nbt.getFloat("TargetDiscRadius") : this.discRadius;
this.targetDiscThickness = nbt.hasKey("TargetDiscThickness") ? nbt.getFloat("TargetDiscThickness") : this.discThickness;
this.anchorData.readNBT(nbt);
}
@Override
protected void writeProjectileNBT(NBTTagCompound nbt) {
nbt.setFloat("Speed", speed);
nbt.setBoolean("Homing", homing);
nbt.setFloat("HomingStrength", homingStrength);
nbt.setFloat("HomingRange", homingRange);
nbt.setBoolean("Boomerang", boomerang);
nbt.setInteger("BoomerangDelay", boomerangDelay);
nbt.setFloat("DiscRadius", discRadius);
nbt.setFloat("DiscThickness", discThickness);
nbt.setBoolean("Vertical", vertical);
nbt.setBoolean("Returning", returning);
// Charging state
nbt.setBoolean("Charging", isCharging());
@@ -606,8 +600,5 @@ public class EntityAbilityDisc extends EntityAbilityProjectile {
nbt.setInteger("ChargeTick", chargeTick);
nbt.setFloat("TargetDiscRadius", targetDiscRadius);
nbt.setFloat("TargetDiscThickness", targetDiscThickness);
// Anchor data
this.anchorData.writeNBT(nbt);
}
}
@@ -1,9 +1,7 @@
package kamkeel.npcs.entity;
import kamkeel.npcs.controllers.data.ability.data.EnergyColorData;
import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
@@ -37,30 +35,70 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
// Direction (normalized)
private double dirX, dirY, dirZ;
// Lock vertical direction after firing (only update yaw, keep pitch fixed)
private boolean lockVerticalDirection = false;
// Track hit entities to avoid double-damage
private Set<Integer> hitEntities = new HashSet<>();
// End point for rendering
private double endX, endY, endZ;
// Charging state (during windup)
private boolean charging = false;
private int chargeDuration = 40;
private int chargeTick = 0;
private float targetSize = 1.0f; // Full size to grow to during charging
// Data watcher index for charging state (synced to clients)
private static final int DW_CHARGING = 20;
public EntityAbilityLaser(World world) {
super(world);
}
@Override
protected void entityInit() {
super.entityInit();
// Register data watcher for charging state
this.dataWatcher.addObject(DW_CHARGING, (byte) 0);
}
/**
* Check if orb is in charging state (synced via data watcher).
* In preview mode, uses local field since data watcher isn't synced.
*/
public boolean isCharging() {
if (previewMode) {
return this.charging;
}
return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1;
}
/**
* Set charging state (server only, synced to clients via data watcher).
*/
private void setCharging(boolean value) {
this.charging = value;
if (!worldObj.isRemote) {
this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0));
}
}
/**
* Full constructor with all parameters using data classes.
*/
public EntityAbilityLaser(World world, EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z,
float laserWidth,
EnergyColorData color, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan,
float expansionSpeed, int lingerTicks) {
double x, double y, double z,
float laserWidth,
EnergyDisplayData display, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan,
EnergyTrajectoryData trajectory, float expansionSpeed, int lingerTicks) {
super(world);
// Initialize base properties (laser doesn't rotate)
initProjectile(owner, target, x, y, z, laserWidth, color, combat, lightning, lifespan);
this.rotationSpeed = 0.0f;
initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan, trajectory);
this.displayData.rotationSpeed = 0.0f;
// Laser-specific properties
this.laserWidth = laserWidth;
@@ -70,7 +108,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
// Calculate direction toward target or forward
if (target != null) {
double dx = target.posX - x;
double dy = (target.posY + target.getEyeHeight()) - y;
double dy = (target.posY + target.getEyeHeight() - 0.4) - y;
double dz = target.posZ - z;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
@@ -93,6 +131,25 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
this.endZ = z;
}
/**
* Setup this orb in charging mode (for windup phase).
* The orb will grow from 0 to orbSize over chargeDuration ticks.
* Position follows the owner based on anchor point.
*/
public void setupCharging(EnergyAnchorData anchor, int chargeDuration) {
setCharging(true);
this.chargeDuration = chargeDuration;
this.chargeTick = 0;
this.anchorData = anchor;
this.targetSize = this.size;
this.size = 0.01f;
this.renderCurrentSize = 0.01f;
this.prevRenderSize = 0.01f;
this.motionX = 0;
this.motionY = 0;
this.motionZ = 0;
}
@Override
protected void updateRotation() {
// Laser doesn't rotate
@@ -106,12 +163,21 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
@Override
protected void updateProjectile() {
if (isCharging()) {
updateCharging();
return;
}
// Track owner's anchor position and rotation each tick
// so the laser follows the NPC's facing direction
updateLaserOriginAndDirection();
if (!fullyExtended) {
// Expand the laser
currentLength += expansionSpeed;
if (currentLength >= maxDistance) {
currentLength = maxDistance;
if (currentLength >= getMaxDistance()) {
currentLength = getMaxDistance();
fullyExtended = true;
}
@@ -128,12 +194,100 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
} else {
// Laser is fully extended, count down linger time
ticksSinceFullExtension++;
// Update end point during linger (origin/direction may still change)
endX = startX + dirX * currentLength;
endY = startY + dirY * currentLength;
endZ = startZ + dirZ * currentLength;
if (ticksSinceFullExtension >= lingerTicks) {
this.setDead();
}
}
}
/**
* Update laser origin and direction from the owner's current anchor position and rotation.
* Called each tick so the laser follows the NPC when tracking a target.
*/
private void updateLaserOriginAndDirection() {
Entity owner = getOwnerEntity();
if (owner == null || owner.isDead) return;
if (!(owner instanceof EntityLivingBase)) return;
EntityLivingBase livingOwner = (EntityLivingBase) owner;
// Update origin from anchor point
if (anchorData != null) {
Vec3 pos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData);
startX = pos.xCoord;
startY = pos.yCoord;
startZ = pos.zCoord;
} else {
startX = owner.posX;
startY = owner.posY + owner.height * 0.7;
startZ = owner.posZ;
}
// Update direction from owner's current rotation
float yaw = (float) Math.toRadians(owner.rotationYaw);
if (lockVerticalDirection) {
// Only update horizontal direction (yaw), keep vertical (pitch) fixed
double horizontalLen = Math.sqrt(dirX * dirX + dirZ * dirZ);
if (horizontalLen < 0.001) horizontalLen = 1.0;
dirX = -Math.sin(yaw) * horizontalLen;
dirZ = Math.cos(yaw) * horizontalLen;
} else {
float pitch = (float) Math.toRadians(owner.rotationPitch);
dirX = -Math.sin(yaw) * Math.cos(pitch);
dirY = -Math.sin(pitch);
dirZ = Math.cos(yaw) * Math.cos(pitch);
}
// Keep entity positioned at origin
prevPosX = startX;
prevPosY = startY;
prevPosZ = startZ;
setPosition(startX, startY, startZ);
}
public void startMoving(EntityLivingBase target) {
if (!isCharging()) return;
setCharging(false);
// Initialize from current anchor position
// updateLaserOriginAndDirection() will keep these updated each tick
startX = posX;
startY = posY;
startZ = posZ;
// Set initial direction from owner's rotation
Entity owner = getOwnerEntity();
if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
this.dirX = -Math.sin(yaw) * Math.cos(pitch);
this.dirY = -Math.sin(pitch);
this.dirZ = Math.cos(yaw) * Math.cos(pitch);
} else if (target != null) {
double dx = target.posX - startX;
double dy = (target.posY + target.getEyeHeight() - 0.4) - startY;
double dz = target.posZ - startZ;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
this.dirX = dx / len;
this.dirY = dy / len;
this.dirZ = dz / len;
}
}
// Initialize end point at start (will expand from here)
this.endX = startX;
this.endY = startY;
this.endZ = startZ;
}
private void checkBlockCollision() {
Vec3 start = Vec3.createVectorHelper(startX, startY, startZ);
Vec3 end = Vec3.createVectorHelper(endX, endY, endZ);
@@ -152,7 +306,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
endZ = blockHit.hitVec.zCoord;
fullyExtended = true;
if (explosive) {
if (isExplosive()) {
// Explode at hit point
double oldPosX = posX;
double oldPosY = posY;
@@ -168,15 +322,53 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
}
}
/**
* Update during charging state - follow owner based on anchor point.
*/
private void updateCharging() {
chargeTick++;
Entity owner = getOwnerEntity();
if (owner == null || owner.isDead) {
setDead();
return;
}
// Grow size based on charge progress
float progress = getChargeProgress();
this.size = targetSize * progress;
// Calculate position based on anchor point, offset downward by half size to center
if (owner instanceof EntityLivingBase) {
Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData);
setPosition(pos.xCoord, pos.yCoord, pos.zCoord);
}
}
/**
* Get the charge progress (0-1).
*/
public float getChargeProgress() {
if (chargeDuration <= 0) return 1.0f;
return Math.min(1.0f, (float) chargeTick / chargeDuration);
}
public float getInterpolatedChargeProgress(float partialTicks) {
if (chargeDuration <= 0) return 1.0f;
float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration);
float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration);
return prevProgress + (currProgress - prevProgress) * partialTicks;
}
private void checkEntityCollisionAlongLine() {
// Check collision along the entire laser line
// Use a slightly expanded AABB for the full line
double minX = Math.min(startX, endX) - laserWidth;
double minY = Math.min(startY, endY) - laserWidth;
double minZ = Math.min(startZ, endZ) - laserWidth;
double maxX = Math.max(startX, endX) + laserWidth;
double maxY = Math.max(startY, endY) + laserWidth;
double maxZ = Math.max(startZ, endZ) + laserWidth;
// Expand search AABB by entity sizes to ensure we find all potential targets
double expand = Math.max(laserWidth, 1.0);
double minX = Math.min(startX, endX) - expand;
double minY = Math.min(startY, endY) - expand;
double minZ = Math.min(startZ, endZ) - expand;
double maxX = Math.max(startX, endX) + expand;
double maxY = Math.max(startY, endY) + expand;
double maxZ = Math.max(startZ, endZ) + expand;
AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
@@ -187,7 +379,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
if (shouldIgnoreEntity(entity)) continue;
if (hitEntities.contains(entity.getEntityId())) continue;
// Check if entity is close to the laser line
// Check if entity's bounding box intersects with the laser line
if (isEntityOnLine(entity)) {
hitEntities.add(entity.getEntityId());
applyDamage(entity);
@@ -198,42 +390,64 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
}
/**
* Check if an entity intersects with the laser line.
* Check if an entity's bounding box intersects with the laser line.
* Uses separate XZ (horizontal) and Y (vertical) checks against
* the entity's full bounding box rather than just its center point.
*/
private boolean isEntityOnLine(EntityLivingBase entity) {
// Get entity center
double ex = entity.posX;
double ey = entity.posY + entity.height * 0.5;
double ez = entity.posZ;
// Vector from start to entity
// Project entity XZ position onto the laser line direction
double vx = ex - startX;
double vy = ey - startY;
double vz = ez - startZ;
// Project onto line direction
double dot = vx * dirX + vy * dirY + vz * dirZ;
// Clamp to line segment
// Project using horizontal direction components only
double dirLenXZ = Math.sqrt(dirX * dirX + dirZ * dirZ);
double dot;
if (dirLenXZ > 0.001) {
dot = (vx * dirX + vz * dirZ) / (dirLenXZ * dirLenXZ) * dirLenXZ;
// Remap to full 3D parameter
dot = (vx * dirX + vz * dirZ + (entity.posY + entity.height * 0.5 - startY) * dirY);
} else {
// Laser fires nearly straight up/down - use full 3D projection
dot = vx * dirX + (entity.posY + entity.height * 0.5 - startY) * dirY + vz * dirZ;
}
dot = Math.max(0, Math.min(dot, currentLength));
// Closest point on line
// Closest point on laser line at this parameter
double closestX = startX + dirX * dot;
double closestY = startY + dirY * dot;
double closestZ = startZ + dirZ * dot;
// Distance from entity to closest point
double distSq = (ex - closestX) * (ex - closestX) +
(ey - closestY) * (ey - closestY) +
(ez - closestZ) * (ez - closestZ);
// XZ distance check: entity center vs laser line point
// Use minimum collision width so visually thin lasers still hit reliably
double xzDistSq = (ex - closestX) * (ex - closestX) + (ez - closestZ) * (ez - closestZ);
double effectiveWidth = Math.max(laserWidth, 0.5);
double hitRadiusXZ = effectiveWidth * 0.5 + entity.width * 0.5;
if (xzDistSq > hitRadiusXZ * hitRadiusXZ) return false;
// Hit if within laser width + entity radius
double hitRadius = laserWidth * 0.5 + entity.width * 0.5;
return distSq <= hitRadius * hitRadius;
// Y overlap check: laser point vs entity's full height range
double entityMinY = entity.boundingBox.minY;
double entityMaxY = entity.boundingBox.maxY;
double laserHalfWidth = effectiveWidth * 0.5;
// Check if laser Y is within entity's height range (expanded by laser half-width)
if (closestY < entityMinY - laserHalfWidth) return false;
if (closestY > entityMaxY + laserHalfWidth) return false;
return true;
}
// ==================== GETTERS FOR RENDERER ====================
public void setLockVerticalDirection(boolean lock) {
this.lockVerticalDirection = lock;
}
public boolean isLockVerticalDirection() {
return lockVerticalDirection;
}
public float getLaserWidth() {
return laserWidth;
}
@@ -305,6 +519,14 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
this.endX = nbt.getDouble("EndX");
this.endY = nbt.getDouble("EndY");
this.endZ = nbt.getDouble("EndZ");
// Charging state
boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging");
this.charging = isCharging;
this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0));
this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40;
this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0;
this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size;
}
@Override
@@ -320,13 +542,19 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
nbt.setDouble("EndX", endX);
nbt.setDouble("EndY", endY);
nbt.setDouble("EndZ", endZ);
// Charging state
nbt.setBoolean("Charging", isCharging());
nbt.setInteger("ChargeDuration", chargeDuration);
nbt.setInteger("ChargeTick", chargeTick);
nbt.setFloat("TargetSize", targetSize);
}
/**
* Setup this laser in preview mode for GUI display.
* Laser doesn't have charging state - spawns at active phase and fires immediately.
*/
public void setupPreview(EntityLivingBase owner, float laserWidth, EnergyColorData color,
public void setupPreview(EntityLivingBase owner, float laserWidth, EnergyDisplayData display,
EnergyLightningData lightning, float expansionSpeed, float maxDistance) {
this.setPreviewMode(true);
this.setPreviewOwner(owner);
@@ -334,15 +562,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile {
// Set visual properties
this.laserWidth = laserWidth;
this.size = laserWidth;
this.innerColor = color.innerColor;
this.outerColor = color.outerColor;
this.outerColorEnabled = color.outerColorEnabled;
this.outerColorWidth = color.outerColorWidth;
this.displayData = display;
this.expansionSpeed = expansionSpeed;
this.maxDistance = Math.min(maxDistance, 5.0f); // Limit for GUI preview
this.lightningEffect = lightning.lightningEffect;
this.lightningDensity = lightning.lightningDensity;
this.lightningRadius = lightning.lightningRadius;
this.lifespanData.maxDistance = Math.min(maxDistance, 5.0f); // Limit for GUI preview
this.lightningData = lightning;
// Position at chest height
double x = owner.posX;
@@ -1,6 +1,5 @@
package kamkeel.npcs.entity;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.*;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
@@ -21,17 +20,10 @@ import java.util.List;
*/
public class EntityAbilityOrb extends EntityAbilityProjectile {
// Orb-specific movement properties
private float speed = 0.5f;
private boolean homing = true;
private float homingStrength = 0.35f; // Increased from 0.15 for better tracking
private float homingRange = 20.0f;
// Charging state (during windup)
private boolean charging = false;
private int chargeDuration = 40;
private int chargeTick = 0;
private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT);
private float targetSize = 1.0f; // Full size to grow to during charging
// Data watcher index for charging state (synced to clients)
@@ -74,19 +66,15 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
*/
public EntityAbilityOrb(World world, EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z, float orbSize,
EnergyColorData color, EnergyCombatData combat,
EnergyDisplayData display, EnergyCombatData combat,
EnergyHomingData homing, EnergyLightningData lightning,
EnergyLifespanData lifespan) {
EnergyLifespanData lifespan, EnergyTrajectoryData trajectory) {
super(world);
// Initialize base properties
initProjectile(owner, target, x, y, z, orbSize, color, combat, lightning, lifespan);
initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan, trajectory);
// Orb-specific properties
this.speed = homing.speed;
this.homing = homing.homing;
this.homingStrength = homing.homingStrength;
this.homingRange = homing.homingRange;
this.homingData = homing;
// Calculate initial velocity toward target
if (target != null) {
@@ -133,20 +121,13 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
* Follows anchor point and animations like in the real game.
* Can be fired when transitioning to active phase.
*/
public void setupPreview(EntityLivingBase owner, float orbSize, EnergyColorData color, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) {
public void setupPreview(EntityLivingBase owner, float orbSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) {
this.setPreviewMode(true);
this.setPreviewOwner(owner);
// Set visual properties
this.innerColor = color.innerColor;
this.outerColor = color.outerColor;
this.outerColorEnabled = color.outerColorEnabled;
this.outerColorWidth = color.outerColorWidth;
this.rotationSpeed = color.rotationSpeed;
this.lightningEffect = lightning.lightningEffect;
this.lightningDensity = lightning.lightningDensity;
this.lightningRadius = lightning.lightningRadius;
this.lightningFadeTime = lightning.lightningFadeTime;
this.displayData = display;
this.lightningData = lightning;
// Set charging state
this.setCharging(true);
@@ -195,16 +176,16 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
prevPosZ = posZ;
// Fire forward based on owner facing direction
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(0); // Fire horizontally
motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
motionY = -Math.sin(pitch) * speed;
motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
motionY = -Math.sin(pitch) * getSpeed();
motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
} else {
// Default: fire forward (positive X in model space)
motionX = speed;
motionX = getSpeed();
motionY = 0;
motionZ = 0;
}
@@ -225,7 +206,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
startZ = posZ;
// Calculate velocity toward target
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (target != null) {
double dx = target.posX - posX;
@@ -233,16 +214,16 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
double dz = target.posZ - posZ;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0) {
motionX = (dx / len) * speed;
motionY = (dy / len) * speed;
motionZ = (dz / len) * speed;
motionX = (dx / len) * getSpeed();
motionY = (dy / len) * getSpeed();
motionZ = (dz / len) * getSpeed();
}
} else if (owner != null) {
float yaw = (float) Math.toRadians(owner.rotationYaw);
float pitch = (float) Math.toRadians(owner.rotationPitch);
motionX = -Math.sin(yaw) * Math.cos(pitch) * speed;
motionY = -Math.sin(pitch) * speed;
motionZ = Math.cos(yaw) * Math.cos(pitch) * speed;
motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed();
motionY = -Math.sin(pitch) * getSpeed();
motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed();
}
}
@@ -264,7 +245,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
handleClientInterpolation();
} else {
// Server-side logic
updateHoming();
updateMovement();
checkBlockCollision();
checkEntityCollision();
this.moveEntity(motionX, motionY, motionZ);
@@ -274,7 +255,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
if (this.isCollidedHorizontally || this.isCollidedVertically) {
if (!worldObj.isRemote) {
hasHit = true;
if (explosive) {
if (isExplosive()) {
doExplosion();
}
}
@@ -292,10 +273,36 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
this.posZ += motionZ;
}
private void updateHoming() {
if (!homing) return;
private void updateMovement() {
if (!isTrajectoryConcluded()) {
updateTrajectory();
} else {
updateHoming();
}
}
Entity target = getTarget();
private void updateTrajectory() {
if (isTrajectoryConcluded()) return;
// i really fucking hate math
}
private boolean isTrajectoryConcluded() {
if (trajectoryData.isEmpty()) return true;
for (int i = 0; i < trajectoryData.size(); i++) {
if (!trajectoryData.getPath(i).isConcluded()) {
return false;
}
}
return true;
}
private void updateHoming() {
if (!isHoming()) return;
Entity target = getTargetEntity();
if (target == null || !target.isEntityAlive()) return;
double dx = target.posX - posX;
@@ -303,21 +310,21 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
double dz = target.posZ - posZ;
double dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist <= homingRange && dist > 0) {
if (dist <= getHomingRange() && dist > 0) {
// Calculate effective homing strength - increases when closer to commit to target
// This prevents orbiting behavior at close range
float effectiveStrength = homingStrength;
if (dist < homingRange * 0.3) {
float effectiveStrength = getHomingStrength();
if (dist < getHomingRange() * 0.3) {
// Within 30% of homing range, dramatically increase strength to commit
effectiveStrength = Math.min(1.0f, homingStrength * 2.5f);
} else if (dist < homingRange * 0.6) {
effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f);
} else if (dist < getHomingRange() * 0.6) {
// Within 60% of homing range, moderately increase strength
effectiveStrength = Math.min(0.8f, homingStrength * 1.5f);
effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f);
}
double desiredVX = (dx / dist) * speed;
double desiredVY = (dy / dist) * speed;
double desiredVZ = (dz / dist) * speed;
double desiredVX = (dx / dist) * getSpeed();
double desiredVY = (dy / dist) * getSpeed();
double desiredVZ = (dz / dist) * getSpeed();
motionX += (desiredVX - motionX) * effectiveStrength;
motionY += (desiredVY - motionY) * effectiveStrength;
@@ -326,9 +333,9 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
// Normalize to maintain speed
double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ);
if (vLen > 0) {
motionX = (motionX / vLen) * speed;
motionY = (motionY / vLen) * speed;
motionZ = (motionZ / vLen) * speed;
motionX = (motionX / vLen) * getSpeed();
motionY = (motionY / vLen) * getSpeed();
motionZ = (motionZ / vLen) * getSpeed();
}
}
}
@@ -341,7 +348,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
hasHit = true;
if (explosive) {
if (isExplosive()) {
posX = blockHit.hitVec.xCoord;
posY = blockHit.hitVec.yCoord;
posZ = blockHit.hitVec.zCoord;
@@ -366,7 +373,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
hasHit = true;
if (explosive) {
if (isExplosive()) {
doExplosion();
} else {
applyDamage(entity);
@@ -383,7 +390,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
private void updateCharging() {
chargeTick++;
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner == null || owner.isDead) {
setDead();
return;
@@ -420,22 +427,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
// ==================== GETTERS ====================
public float getSpeed() {
return speed;
}
public boolean isHoming() {
return homing;
}
public float getHomingStrength() {
return homingStrength;
}
public float getHomingRange() {
return homingRange;
}
// Legacy getter for renderer compatibility
public float getOrbSize() {
return size;
@@ -445,10 +436,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
@Override
protected void readProjectileNBT(NBTTagCompound nbt) {
this.speed = nbt.hasKey("OrbSpeed") ? nbt.getFloat("OrbSpeed") : 0.5f;
this.homing = !nbt.hasKey("Homing") || nbt.getBoolean("Homing");
this.homingStrength = nbt.hasKey("HomingStrength") ? nbt.getFloat("HomingStrength") : 0.15f;
this.homingRange = nbt.hasKey("HomingRange") ? nbt.getFloat("HomingRange") : 20.0f;
// Charging state
boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging");
this.charging = isCharging;
@@ -456,16 +443,10 @@ public class EntityAbilityOrb extends EntityAbilityProjectile {
this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40;
this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0;
this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size;
// Anchor data
this.anchorData.readNBT(nbt);
}
@Override
protected void writeProjectileNBT(NBTTagCompound nbt) {
nbt.setFloat("OrbSpeed", speed);
nbt.setBoolean("Homing", homing);
nbt.setFloat("HomingStrength", homingStrength);
nbt.setFloat("HomingRange", homingRange);
// Charging state
nbt.setBoolean("Charging", isCharging());
nbt.setInteger("ChargeDuration", chargeDuration);
@@ -4,11 +4,12 @@ import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.AbilityEffect;
import kamkeel.npcs.controllers.data.ability.data.EnergyColorData;
import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.IAbilityDamageHandler;
import kamkeel.npcs.controllers.data.ability.data.*;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
@@ -16,13 +17,16 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.NpcDamageSource;
import noppes.npcs.api.entity.IEnergyProjectile;
import noppes.npcs.api.entity.IEntity;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.scripted.NpcAPI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Base class for all ability projectiles (Orb, Disc, Beam, Laser).
@@ -30,55 +34,55 @@ import java.util.List;
*
* Design inspired by LouisXIV's energy attack system.
*/
public abstract class EntityAbilityProjectile extends Entity implements IEntityAdditionalSpawnData {
public abstract class EntityAbilityProjectile extends Entity implements IEnergyProjectile, IEntityAdditionalSpawnData {
// ==================== VISUAL PROPERTIES ====================
protected float size = 1.0f;
protected int innerColor = 0xFFFFFF;
protected int outerColor = 0x8888FF;
protected boolean outerColorEnabled = true;
protected float outerColorWidth = 0.4f; // Additive offset from inner size
protected float outerColorAlpha = 0.5f;
protected float rotationSpeed = 4.0f;
// ==================== COMBAT PROPERTIES ====================
protected float damage = 7.0f;
protected float knockback = 1.0f;
protected float knockbackUp = 0.1f;
protected EnergyCombatData combatData = new EnergyCombatData();
// ==================== EFFECT PROPERTIES ====================
protected List<AbilityEffect> effects = new ArrayList<>();
// ==================== EXPLOSION PROPERTIES ====================
protected boolean explosive = false;
protected float explosionRadius = 3.0f;
protected float explosionDamageFalloff = 0.5f;
// ==================== LIGHTNING EFFECT PROPERTIES ====================
protected boolean lightningEffect = false;
protected float lightningDensity = 0.15f; // Bolts spawned per tick (0.15 = ~15% chance per frame)
protected float lightningRadius = 0.5f; // Max distance lightning can arc from center
protected int lightningFadeTime = 6; // Ticks before lightning fades out
protected EnergyLightningData lightningData = new EnergyLightningData();
// Client-side lightning state (not saved to NBT)
@cpw.mods.fml.relauncher.SideOnly(cpw.mods.fml.relauncher.Side.CLIENT)
public transient Object lightningState; // Actually AttachedLightningRenderer.LightningState
// ==================== LIFESPAN ====================
protected float maxDistance = 30.0f;
protected int maxLifetime = 200;
// ==================== DISPLAY PROPERTIES ====================
protected EnergyDisplayData displayData = new EnergyDisplayData();
// ==================== ANCHOR PROPERTIES ====================
protected EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT);
// ==================== LIFESPAN PROPERTIES ====================
protected EnergyLifespanData lifespanData = new EnergyLifespanData();
protected long deathWorldTime = -1; // World time when entity should die (-1 = not set)
// ==================== HOMING PROPERTIES ====================
protected EnergyHomingData homingData = new EnergyHomingData();
// ==================== TRAJECTORY PROPERTIES ====================
protected EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData();
protected Map<Integer, Integer> pathDelays;
// ==================== TRACKING ====================
protected double startX, startY, startZ;
protected int ownerEntityId = -1;
protected int targetEntityId = -1;
protected int siblingEntityId = -1;
// ==================== STATE ====================
protected boolean hasHit = false;
protected boolean previewMode = false; // Client-side preview mode (no damage/effects)
protected EntityLivingBase previewOwner = null; // Direct reference for GUI preview (no world lookup)
/** The ability that spawned this projectile. Transient, not saved to NBT. */
protected transient Ability sourceAbility = null;
// ==================== ROTATION INTERPOLATION ====================
public float prevRotationValX, prevRotationValY, prevRotationValZ;
public float rotationValX, rotationValY, rotationValZ;
@@ -103,10 +107,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
/**
* Initialize common properties using data classes. Call from subclass constructors.
*/
protected void initProjectile(EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z, float size,
EnergyColorData color, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan) {
protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, EntityAbilityProjectile sibling,
double x, double y, double z, float size,
EnergyDisplayData display, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan,
EnergyTrajectoryData trajectory) {
this.setPosition(x, y, z);
this.startX = x;
this.startY = y;
@@ -114,42 +119,31 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
this.ownerEntityId = owner.getEntityId();
this.targetEntityId = target != null ? target.getEntityId() : -1;
this.siblingEntityId = sibling != null ? sibling.getEntityId() : -1;
// Visual
this.size = size;
this.innerColor = color.innerColor;
this.outerColor = color.outerColor;
this.outerColorEnabled = color.outerColorEnabled;
this.outerColorWidth = color.outerColorWidth;
this.outerColorAlpha = color.outerColorAlpha;
this.rotationSpeed = color.rotationSpeed;
// Combat
this.damage = combat.damage;
this.knockback = combat.knockback;
this.knockbackUp = combat.knockbackUp;
// Explosion
this.explosive = combat.explosive;
this.explosionRadius = combat.explosionRadius;
this.explosionDamageFalloff = combat.explosionDamageFalloff;
// Lifespan
this.maxDistance = lifespan.maxDistance;
this.maxLifetime = lifespan.maxLifetime;
// deathWorldTime will be set on first tick when world is available
// Lightning
this.lightningEffect = lightning.lightningEffect;
this.lightningDensity = lightning.lightningDensity;
this.lightningRadius = lightning.lightningRadius;
this.lightningFadeTime = lightning.lightningFadeTime;
this.displayData = display;
this.combatData = combat;
this.lifespanData = lifespan; // deathWorldTime will be set on first tick when world is available
this.lightningData = lightning;
this.trajectoryData = trajectory;
// Initialize render size
this.renderCurrentSize = size;
this.prevRenderSize = size;
}
// Initialize projectile without a sibling
protected void initProjectile(EntityLivingBase owner, EntityLivingBase target,
double x, double y, double z, float size,
EnergyDisplayData display, EnergyCombatData combat,
EnergyLightningData lightning, EnergyLifespanData lifespan,
EnergyTrajectoryData trajectory) {
initProjectile(owner, target, null, x, y, z, size, display, combat, lightning, lifespan, trajectory);
}
@Override
protected void entityInit() {
// No DataWatcher needed - using IEntityAdditionalSpawnData with NBT
@@ -192,9 +186,22 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
// Skip lifetime/distance checks in preview mode
if (!previewMode) {
// Failsafe: if owner entity is gone, dead, or NPC was killed/reset, self-destruct
if (ownerEntityId >= 0 && ticksExisted > 5) {
Entity owner = worldObj.getEntityByID(ownerEntityId);
if (owner == null || owner.isDead) {
this.setDead();
return;
}
if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) {
this.setDead();
return;
}
}
// Set death time on first tick if not already set (handles chunk load/unload)
if (deathWorldTime < 0 && worldObj != null) {
deathWorldTime = worldObj.getTotalWorldTime() + maxLifetime;
deathWorldTime = worldObj.getTotalWorldTime() + getMaxLifetime();
}
// Check lifespan using world time (survives chunk unload/reload)
@@ -223,9 +230,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
* Update rotation values. Override for custom rotation behavior.
*/
protected void updateRotation() {
this.rotationValX += rotationSpeed * 0.7f;
this.rotationValY += rotationSpeed;
this.rotationValZ += rotationSpeed * 0.5f;
this.rotationValX += getRotationSpeed() * 0.7f;
this.rotationValY += getRotationSpeed();
this.rotationValZ += getRotationSpeed() * 0.5f;
if (this.rotationValX > 360.0f) this.rotationValX -= 360.0f;
if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f;
@@ -242,7 +249,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
(posY - startY) * (posY - startY) +
(posZ - startZ) * (posZ - startZ)
);
return distTraveled >= maxDistance;
return distTraveled >= getMaxDistance();
}
/**
@@ -314,21 +321,37 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
protected void applyDamage(EntityLivingBase target) {
if (previewMode) return; // Skip damage in preview mode
applyDamage(target, this.damage, this.knockback);
applyDamage(target, this.getDamage(), this.getKnockback());
}
protected void applyDamage(EntityLivingBase target, float dmg, float kb) {
if (previewMode) return; // Skip damage in preview mode
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (owner instanceof EntityNPCInterface) {
target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg);
} else if (owner instanceof EntityPlayer) {
target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg);
} else if (owner instanceof EntityLivingBase) {
target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg);
} else {
target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg);
// Check for external damage handler (e.g., DBC Addon)
boolean handled = false;
if (sourceAbility != null && owner instanceof EntityLivingBase) {
IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler();
if (handler != null) {
double dx = target.posX - posX;
double dz = target.posZ - posZ;
float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f;
handled = handler.handleDamage(sourceAbility, (EntityLivingBase) owner, target,
dmg, kb, kbUp, dx, dz);
}
}
if (!handled) {
// Default damage path
if (owner instanceof EntityNPCInterface) {
target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg);
} else if (owner instanceof EntityPlayer) {
target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg);
} else if (owner instanceof EntityLivingBase) {
target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg);
} else {
target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg);
}
}
if (kb > 0) {
@@ -338,7 +361,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
if (len > 0) {
double kbX = (dx / len) * kb * 0.5;
double kbZ = (dz / len) * kb * 0.5;
double kbY = knockbackUp > 0 ? knockbackUp : 0.1;
double kbY = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1;
target.addVelocity(kbX, kbY, kbZ);
target.velocityChanged = true;
}
@@ -360,15 +383,30 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
this.effects = effects != null ? effects : new ArrayList<>();
}
/**
* Set the source ability that spawned this projectile.
* Used by external damage handlers to access ability-specific data.
*/
public void setSourceAbility(Ability ability) {
this.sourceAbility = ability;
}
/**
* Get the source ability that spawned this projectile.
*/
public Ability getSourceAbility() {
return sourceAbility;
}
protected void doExplosion() {
if (previewMode) return; // Skip explosion in preview mode
worldObj.playSoundEffect(posX, posY, posZ, "random.explode", 1.0f, 1.0f);
Entity owner = getOwner();
Entity owner = getOwnerEntity();
AxisAlignedBB explosionBox = AxisAlignedBB.getBoundingBox(
posX - explosionRadius, posY - explosionRadius, posZ - explosionRadius,
posX + explosionRadius, posY + explosionRadius, posZ + explosionRadius
posX - getExplosionRadius(), posY - getExplosionRadius(), posZ - getExplosionRadius(),
posX + getExplosionRadius(), posY + getExplosionRadius(), posZ + getExplosionRadius()
);
@SuppressWarnings("unchecked")
@@ -383,16 +421,16 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
Math.pow(target.posZ - posZ, 2)
);
if (dist <= explosionRadius) {
float falloff = 1.0f - (float) (dist / explosionRadius) * explosionDamageFalloff;
applyDamage(target, damage * falloff, knockback * falloff);
if (dist <= getExplosionRadius()) {
float falloff = 1.0f - (float) (dist / getExplosionRadius()) * getExplosionDamageFalloff();
applyDamage(target, getDamage() * falloff, getKnockback() * falloff);
}
}
}
// ==================== ENTITY HELPERS ====================
protected Entity getOwner() {
public Entity getOwnerEntity() {
// In preview mode, use direct reference (no world lookup)
if (previewMode && previewOwner != null) {
return previewOwner;
@@ -401,6 +439,18 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
return worldObj.getEntityByID(ownerEntityId);
}
@Override
public int getOwnerEntityId() {
return ownerEntityId;
}
@Override
public IEntity getOwner() {
if (previewMode) return null;
if (getOwnerEntity() == null) return null;
return NpcAPI.Instance().getIEntity(getOwnerEntity());
}
/**
* Set the preview owner for GUI preview mode.
* This allows anchor point calculations without world entity lookup.
@@ -409,16 +459,45 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
this.previewOwner = owner;
}
protected Entity getTarget() {
@Override
public int getTargetEntityId() {
return targetEntityId;
}
public Entity getTargetEntity() {
if (targetEntityId == -1) return null;
return worldObj.getEntityByID(targetEntityId);
}
@Override
public IEntity getTarget() {
if (getTargetEntity() == null) return null;
return NpcAPI.Instance().getIEntity(getTargetEntity());
}
@Override
public int getSiblingEntityId() {
return siblingEntityId;
}
@Override
public void setSiblingEntityId(int siblingEntityId) {
if (!(worldObj.getEntityByID(siblingEntityId) instanceof EntityAbilityProjectile)) return;
this.siblingEntityId = siblingEntityId;
}
@Override
public IEnergyProjectile getSibling() {
if (siblingEntityId == -1) return null;
return (EntityAbilityProjectile) worldObj.getEntityByID(siblingEntityId);
}
/**
* Check if an entity should be ignored for collision.
*/
protected boolean shouldIgnoreEntity(Entity entity) {
Entity owner = getOwner();
Entity owner = getOwnerEntity();
if (entity == owner) return true;
if (owner instanceof EntityNPCInterface && entity instanceof EntityNPCInterface) {
@@ -426,73 +505,170 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
EntityNPCInterface targetNpc = (EntityNPCInterface) entity;
if (ownerNpc.faction.id == targetNpc.faction.id) return true;
}
if (entity.getEntityId() == getSiblingEntityId())
return true;
return false;
}
// ==================== VISUAL GETTERS ====================
@Override
public float getSize() {
return size;
}
@Override
public int getInnerColor() {
return innerColor;
return displayData.getInnerColor();
}
@Override
public int getOuterColor() {
return outerColor;
return displayData.getOuterColor();
}
@Override
public boolean isOuterColorEnabled() {
return outerColorEnabled;
return displayData.isOuterColorEnabled();
}
@Override
public float getOuterColorWidth() {
return outerColorWidth;
return displayData.getOuterColorWidth();
}
@Override
public float getOuterColorAlpha() {
return outerColorAlpha;
return displayData.getOuterColorAlpha();
}
@Override
public float getRotationSpeed() {
return rotationSpeed;
return displayData.getRotationSpeed();
}
// ==================== ROTATION GETTERS ====================
@Override
public float getInterpolatedRotationX(float partialTicks) {
return this.prevRotationValX + (this.rotationValX - this.prevRotationValX) * partialTicks;
}
@Override
public float getInterpolatedRotationY(float partialTicks) {
return this.prevRotationValY + (this.rotationValY - this.prevRotationValY) * partialTicks;
}
@Override
public float getInterpolatedRotationZ(float partialTicks) {
return this.prevRotationValZ + (this.rotationValZ - this.prevRotationValZ) * partialTicks;
}
@Override
public float getInterpolatedSize(float partialTicks) {
return this.prevRenderSize + (this.renderCurrentSize - this.prevRenderSize) * partialTicks;
}
// ==================== LIGHTNING GETTERS ====================
@Override
public boolean hasLightningEffect() {
return lightningEffect;
return lightningData.isLightningEffect();
}
@Override
public float getLightningDensity() {
return lightningDensity;
return lightningData.getLightningDensity();
}
@Override
public float getLightningRadius() {
return lightningRadius;
return lightningData.getLightningRadius();
}
@Override
public int getLightningFadeTime() {
return lightningFadeTime;
return lightningData.getLightningFadeTime();
}
// ==================== LIFESPAN GETTERS ====================
@Override
public float getMaxDistance() { return lifespanData.getMaxDistance(); }
@Override
public int getMaxLifetime() { return lifespanData.getMaxLifetime(); }
// ==================== COMBAT GETTERS ====================
@Override
public float getDamage() { return combatData.getDamage(); }
@Override
public float getKnockback() { return combatData.knockback; }
@Override
public float getKnockbackUp() { return combatData.knockbackUp; }
@Override
public boolean isExplosive() { return combatData.isExplosive(); }
@Override
public float getExplosionRadius() { return combatData.explosionRadius; }
@Override
public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; }
// ==================== HOMING GETTERS ====================
@Override
public boolean isHoming() { return homingData.isHoming(); }
@Override
public float getHomingStrength() { return homingData.getHomingStrength(); }
@Override
public float getHomingRange() { return homingData.getHomingRange(); }
// ==================== TRAJECTORY GETTERS ====================
// ==================== ANCHOR GETTERS ====================
@Override
public float getSpeed() { return homingData.getSpeed(); }
public AnchorPoint getAnchorPoint() { return anchorData.getAnchorPoint(); }
@Override
public int getAnchor() { return anchorData.getAnchor(); }
@Override
public float getAnchorOffsetX() { return anchorData.getAnchorOffsetX(); }
@Override
public float getAnchorOffsetY() { return anchorData.getAnchorOffsetY(); }
@Override
public float getAnchorOffsetZ() { return anchorData.getAnchorOffsetZ(); }
// ==================== MOVEMENT GETTERS ====================
@Override public double getStartX() { return startX; }
@Override public double getStartY() { return startY; }
@Override public double getStartZ() { return startZ; }
@Override public double getMotionX() { return motionX; }
@Override public double getMotionY() { return motionY; }
@Override public double getMotionZ() { return motionZ; }
// ==================== BRIGHTNESS ====================
@Override
@@ -525,20 +701,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
*/
protected void readBaseNBT(NBTTagCompound nbt) {
this.size = nbt.getFloat("Size");
this.innerColor = nbt.getInteger("InnerColor");
this.outerColor = nbt.getInteger("OuterColor");
this.outerColorEnabled = !nbt.hasKey("OuterColorEnabled") || nbt.getBoolean("OuterColorEnabled");
this.outerColorAlpha = nbt.hasKey("OuterColorAlpha") ? nbt.getFloat("OuterColorAlpha") : 0.5f;
this.outerColorWidth = nbt.hasKey("OuterColorWidth") ? nbt.getFloat("OuterColorWidth") : 0.4f;
this.rotationSpeed = nbt.hasKey("RotationSpeed") ? nbt.getFloat("RotationSpeed") : 4.0f;
this.damage = nbt.getFloat("Damage");
this.knockback = nbt.getFloat("Knockback");
this.knockbackUp = nbt.getFloat("KnockbackUp");
this.explosive = nbt.getBoolean("Explosive");
this.explosionRadius = nbt.getFloat("ExplosionRadius");
this.explosionDamageFalloff = nbt.getFloat("ExplosionDamageFalloff");
// Read effects list
this.effects.clear();
@@ -549,8 +711,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
}
}
this.maxDistance = nbt.getFloat("MaxDistance");
this.maxLifetime = nbt.getInteger("MaxLifetime");
this.deathWorldTime = nbt.hasKey("DeathWorldTime") ? nbt.getLong("DeathWorldTime") : -1;
this.startX = nbt.getDouble("StartX");
@@ -559,21 +719,24 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
this.ownerEntityId = nbt.getInteger("OwnerId");
this.targetEntityId = nbt.getInteger("TargetId");
this.siblingEntityId = nbt.getInteger("SiblingId");
this.motionX = nbt.getDouble("MotionX");
this.motionY = nbt.getDouble("MotionY");
this.motionZ = nbt.getDouble("MotionZ");
// Lightning
this.lightningEffect = nbt.getBoolean("LightningEffect");
this.lightningDensity = nbt.hasKey("LightningDensity") ? nbt.getFloat("LightningDensity") : 0.15f;
this.lightningRadius = nbt.hasKey("LightningRadius") ? nbt.getFloat("LightningRadius") : 0.5f;
this.lightningFadeTime = nbt.hasKey("LightningFadeTime") ? nbt.getInteger("LightningFadeTime") : 6;
if (this.worldObj != null && this.worldObj.isRemote) {
this.renderCurrentSize = this.size;
this.prevRenderSize = this.size;
}
anchorData.readNBT(nbt);
combatData.readNBT(nbt);
displayData.readNBT(nbt);
homingData.readNBT(nbt);
lifespanData.readNBT(nbt);
lightningData.readNBT(nbt);
trajectoryData.readNBT(nbt);
}
/**
@@ -581,20 +744,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
*/
protected void writeBaseNBT(NBTTagCompound nbt) {
nbt.setFloat("Size", size);
nbt.setInteger("InnerColor", innerColor);
nbt.setInteger("OuterColor", outerColor);
nbt.setBoolean("OuterColorEnabled", outerColorEnabled);
nbt.setFloat("OuterColorWidth", outerColorWidth);
nbt.setFloat("OuterColorAlpha", outerColorAlpha);
nbt.setFloat("RotationSpeed", rotationSpeed);
nbt.setFloat("Damage", damage);
nbt.setFloat("Knockback", knockback);
nbt.setFloat("KnockbackUp", knockbackUp);
nbt.setBoolean("Explosive", explosive);
nbt.setFloat("ExplosionRadius", explosionRadius);
nbt.setFloat("ExplosionDamageFalloff", explosionDamageFalloff);
// Write effects list
if (!effects.isEmpty()) {
@@ -605,9 +754,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
nbt.setTag("Effects", effectsList);
}
nbt.setFloat("MaxDistance", maxDistance);
nbt.setLong("DeathWorldTime", deathWorldTime);
nbt.setInteger("MaxLifetime", maxLifetime);
nbt.setDouble("StartX", startX);
nbt.setDouble("StartY", startY);
@@ -615,16 +762,19 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA
nbt.setInteger("OwnerId", ownerEntityId);
nbt.setInteger("TargetId", targetEntityId);
nbt.setInteger("SiblingId", targetEntityId);
nbt.setDouble("MotionX", motionX);
nbt.setDouble("MotionY", motionY);
nbt.setDouble("MotionZ", motionZ);
// Lightning
nbt.setBoolean("LightningEffect", lightningEffect);
nbt.setFloat("LightningDensity", lightningDensity);
nbt.setFloat("LightningRadius", lightningRadius);
nbt.setInteger("LightningFadeTime", lightningFadeTime);
anchorData.writeNBT(nbt);
combatData.writeNBT(nbt);
displayData.writeNBT(nbt);
homingData.writeNBT(nbt);
lifespanData.writeNBT(nbt);
lightningData.writeNBT(nbt);
trajectoryData.writeNBT(nbt);
}
/**
@@ -4,7 +4,7 @@ import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.controllers.data.ability.data.EnergyColorData;
import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
@@ -60,6 +60,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa
private int maxTicks = 400;
private long deathWorldTime = -1;
// Preview mode
private boolean previewMode = false;
private EntityLivingBase previewOwner = null;
// Damage state
private transient int ticksSinceDamage = 0;
private transient Set<Integer> hitThisTick = new HashSet<>();
@@ -74,7 +78,7 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa
public EntityAbilitySweeper(World world, EntityLivingBase owner, EntityLivingBase target,
float beamLength, float beamWidth, float beamHeight,
EnergyColorData colorData,
EnergyDisplayData displayData,
float sweepSpeed, int numberOfRotations,
float damage, int damageInterval, boolean piercing,
boolean lockOnTarget) {
@@ -85,10 +89,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa
this.beamLength = beamLength;
this.beamWidth = beamWidth;
this.beamHeight = beamHeight;
this.innerColor = colorData.innerColor;
this.outerColor = colorData.outerColor;
this.outerColorEnabled = colorData.outerColorEnabled;
this.outerColorWidth = colorData.outerColorWidth;
this.innerColor = displayData.innerColor;
this.outerColor = displayData.outerColor;
this.outerColorEnabled = displayData.outerColorEnabled;
this.outerColorWidth = displayData.outerColorWidth;
this.sweepSpeed = sweepSpeed;
this.numberOfRotations = numberOfRotations;
this.damage = damage;
@@ -281,7 +285,16 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa
target.velocityChanged = true;
}
/**
* Set up preview mode. Owner is stored directly since world entity lookup won't work.
*/
public void setupPreview(EntityLivingBase owner) {
this.previewMode = true;
this.previewOwner = owner;
}
private Entity getOwner() {
if (previewMode && previewOwner != null) return previewOwner;
if (ownerEntityId == -1) return null;
return worldObj.getEntityByID(ownerEntityId);
}
@@ -108,6 +108,9 @@ import kamkeel.npcs.network.packets.request.bank.BankSavePacket;
import kamkeel.npcs.network.packets.request.bank.BanksGetPacket;
import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket;
import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket;
import kamkeel.npcs.network.packets.request.clone.CloneFolderCrudPacket;
import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket;
import kamkeel.npcs.network.packets.request.clone.CloneMovePacket;
import kamkeel.npcs.network.packets.request.clone.CloneListPacket;
import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket;
import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket;
@@ -325,6 +328,9 @@ public class PacketHandler {
REQUEST_PACKET.registerPacket(new CloneTagListPacket());
REQUEST_PACKET.registerPacket(new CloneAllTagsPacket());
REQUEST_PACKET.registerPacket(new CloneAllTagsShortPacket());
REQUEST_PACKET.registerPacket(new CloneFolderListPacket());
REQUEST_PACKET.registerPacket(new CloneFolderCrudPacket());
REQUEST_PACKET.registerPacket(new CloneMovePacket());
// Linked Packets
@@ -163,6 +163,9 @@ public enum EnumRequestPacket {
CloneAllTags,
CloneAllTagsShort,
ClonePreSave,
CloneFolderList,
CloneFolderCrud,
CloneMove,
EventScript,
PlayerScript,
@@ -16,7 +16,9 @@ import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.client.ScriptClientConfig;
import noppes.npcs.controllers.AuctionConfigSync;
import noppes.npcs.controllers.ScriptConfigSync;
import java.io.IOException;
import java.util.EnumMap;
@@ -65,6 +67,11 @@ public final class LoginPacket extends AbstractPacket {
NBTTagCompound auctionConfig = new NBTTagCompound();
AuctionConfigSync.writeToNBT(auctionConfig);
ByteBufUtils.writeNBT(out, auctionConfig);
// Send script config (server-side sync)
NBTTagCompound scriptConfig = new NBTTagCompound();
ScriptConfigSync.writeToNBT(scriptConfig);
ByteBufUtils.writeNBT(out, scriptConfig);
}
@SideOnly(Side.CLIENT)
@@ -88,6 +95,10 @@ public final class LoginPacket extends AbstractPacket {
NBTTagCompound auctionConfig = ByteBufUtils.readNBT(in);
AuctionClientConfig.readFromNBT(auctionConfig);
// Read script config
NBTTagCompound scriptConfig = ByteBufUtils.readNBT(in);
ScriptClientConfig.readFromNBT(scriptConfig);
PacketClient.sendClient(new SyncRevisionInfoPacket(
serverKey,
ClientCacheHandler.getLastServerKey(),
@@ -59,6 +59,16 @@ public final class SpecialKeyStatePacket extends AbstractPacket {
// Trigger ability activation on key press (rising edge)
if (keyDown && !wasDown) {
// Don't activate if player has a GUI open (not the default inventory)
if (player.openContainer != null && !(player.openContainer instanceof net.minecraft.inventory.ContainerPlayer)) {
return;
}
// Don't activate if player is riding an entity (mount)
if (player.ridingEntity != null) {
return;
}
data.abilityData.activateAbility(player);
}
}
@@ -0,0 +1,111 @@
package kamkeel.npcs.network.packets.request.clone;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.controllers.ServerCloneController;
import noppes.npcs.controllers.data.CloneFolder;
import java.io.IOException;
public final class CloneFolderCrudPacket extends AbstractPacket {
public static String packetName = "Request|CloneFolderCrud";
public static final byte ACTION_CREATE = 0;
public static final byte ACTION_RENAME = 1;
public static final byte ACTION_DELETE = 2;
private byte action;
private String name;
private String newName;
public CloneFolderCrudPacket() {
}
public CloneFolderCrudPacket(byte action, String name) {
this.action = action;
this.name = name;
this.newName = "";
}
public CloneFolderCrudPacket(byte action, String name, String newName) {
this.action = action;
this.name = name;
this.newName = newName;
}
@Override
public Enum getType() {
return EnumRequestPacket.CloneFolderCrud;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.REQUEST_PACKET;
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.NPC_CLONE;
}
@SideOnly(Side.CLIENT)
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeByte(action);
ByteBufUtils.writeString(out, name);
if (action == ACTION_RENAME) {
ByteBufUtils.writeString(out, newName);
}
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP))
return;
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER))
return;
byte action = in.readByte();
String name = ByteBufUtils.readString(in);
boolean success = false;
switch (action) {
case ACTION_CREATE:
if (CloneFolder.isValidName(name))
success = ServerCloneController.Instance.createFolder(name) != null;
break;
case ACTION_RENAME:
String newName = ByteBufUtils.readString(in);
if (CloneFolder.isValidName(newName))
success = ServerCloneController.Instance.renameFolder(name, newName);
break;
case ACTION_DELETE:
success = ServerCloneController.Instance.deleteFolder(name);
break;
}
NBTTagCompound compound = new NBTTagCompound();
compound.setBoolean("Success", success);
NBTTagList folderList = new NBTTagList();
for (CloneFolder folder : ServerCloneController.Instance.getFolderList()) {
folderList.appendTag(folder.writeNBT(new NBTTagCompound()));
}
compound.setTag("CloneFolders", folderList);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
}
}
@@ -0,0 +1,59 @@
package kamkeel.npcs.network.packets.request.clone;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.ServerCloneController;
import noppes.npcs.controllers.data.CloneFolder;
import java.io.IOException;
public final class CloneFolderListPacket extends AbstractPacket {
public static String packetName = "Request|CloneFolderList";
public CloneFolderListPacket() {
}
@Override
public Enum getType() {
return EnumRequestPacket.CloneFolderList;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.REQUEST_PACKET;
}
@SideOnly(Side.CLIENT)
@Override
public void sendData(ByteBuf out) throws IOException {
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP))
return;
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER))
return;
NBTTagCompound compound = new NBTTagCompound();
NBTTagList folderList = new NBTTagList();
for (CloneFolder folder : ServerCloneController.Instance.getFolderList()) {
folderList.appendTag(folder.writeNBT(new NBTTagCompound()));
}
compound.setTag("CloneFolders", folderList);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
}
}
@@ -23,9 +23,16 @@ public final class CloneListPacket extends AbstractPacket {
public static String packetName = "Request|CloneList";
private int tab;
private String folderName;
public CloneListPacket(int tab) {
this.tab = tab;
this.folderName = null;
}
public CloneListPacket(String folderName) {
this.tab = -1;
this.folderName = folderName;
}
public CloneListPacket() {
@@ -45,6 +52,9 @@ public final class CloneListPacket extends AbstractPacket {
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeInt(tab);
if (tab == -1) {
kamkeel.npcs.util.ByteBufUtils.writeString(out, folderName);
}
}
@Override
@@ -54,14 +64,26 @@ public final class CloneListPacket extends AbstractPacket {
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.MOUNTER, EnumItemPacketType.CLONER))
return;
NBTTagList list = new NBTTagList();
int tab = in.readInt();
for (String name : ServerCloneController.Instance.getClones(tab))
list.appendTag(new NBTTagString(name));
String folder = null;
if (tab == -1) {
folder = kamkeel.npcs.util.ByteBufUtils.readString(in);
}
NBTTagList list = new NBTTagList();
NBTTagList listDate = new NBTTagList();
for (String name : ServerCloneController.Instance.getClonesDate(tab))
listDate.appendTag(new NBTTagString(name));
if (folder != null) {
for (String name : ServerCloneController.Instance.getClones(folder))
list.appendTag(new NBTTagString(name));
for (String name : ServerCloneController.Instance.getClonesDate(folder))
listDate.appendTag(new NBTTagString(name));
} else {
for (String name : ServerCloneController.Instance.getClones(tab))
list.appendTag(new NBTTagString(name));
for (String name : ServerCloneController.Instance.getClonesDate(tab))
listDate.appendTag(new NBTTagString(name));
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("List", list);
@@ -0,0 +1,97 @@
package kamkeel.npcs.network.packets.request.clone;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.controllers.ServerCloneController;
import java.io.IOException;
public final class CloneMovePacket extends AbstractPacket {
public static String packetName = "Request|CloneMove";
private String cloneName;
private int fromTab;
private String fromFolder;
private int toTab;
private String toFolder;
public CloneMovePacket() {
}
public CloneMovePacket(String cloneName, int fromTab, String fromFolder, int toTab, String toFolder) {
this.cloneName = cloneName;
this.fromTab = fromTab;
this.fromFolder = fromFolder;
this.toTab = toTab;
this.toFolder = toFolder;
}
@Override
public Enum getType() {
return EnumRequestPacket.CloneMove;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.REQUEST_PACKET;
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.NPC_CLONE;
}
@SideOnly(Side.CLIENT)
@Override
public void sendData(ByteBuf out) throws IOException {
ByteBufUtils.writeString(out, cloneName);
out.writeInt(fromTab);
ByteBufUtils.writeString(out, fromFolder != null ? fromFolder : "");
out.writeInt(toTab);
ByteBufUtils.writeString(out, toFolder != null ? toFolder : "");
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP))
return;
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER))
return;
String cloneName = ByteBufUtils.readString(in);
int fromTab = in.readInt();
String fromFolder = ByteBufUtils.readString(in);
if (fromFolder.isEmpty()) fromFolder = null;
int toTab = in.readInt();
String toFolder = ByteBufUtils.readString(in);
if (toFolder.isEmpty()) toFolder = null;
boolean success = false;
if (fromFolder != null && toFolder != null) {
success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder);
} else if (fromFolder != null) {
success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab);
} else if (toFolder != null) {
success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder);
} else {
success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setBoolean("MoveSuccess", success);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
}
}
@@ -24,6 +24,7 @@ public final class ClonePreSavePacket extends AbstractPacket {
private String name;
private int tab;
private String folderName;
public ClonePreSavePacket() {
}
@@ -31,6 +32,13 @@ public final class ClonePreSavePacket extends AbstractPacket {
public ClonePreSavePacket(String name, int tab) {
this.name = name;
this.tab = tab;
this.folderName = null;
}
public ClonePreSavePacket(String name, String folderName) {
this.name = name;
this.tab = -1;
this.folderName = folderName;
}
@Override
@@ -53,6 +61,9 @@ public final class ClonePreSavePacket extends AbstractPacket {
public void sendData(ByteBuf out) throws IOException {
ByteBufUtils.writeString(out, this.name);
out.writeInt(tab);
if (tab == -1) {
ByteBufUtils.writeString(out, this.folderName);
}
}
@Override
@@ -62,7 +73,15 @@ public final class ClonePreSavePacket extends AbstractPacket {
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER))
return;
boolean bo = ServerCloneController.Instance.getCloneData(null, ByteBufUtils.readString(in), in.readInt()) != null;
String name = ByteBufUtils.readString(in);
int tab = in.readInt();
boolean bo;
if (tab == -1) {
String folder = ByteBufUtils.readString(in);
bo = ServerCloneController.Instance.getCloneData(null, name, folder) != null;
} else {
bo = ServerCloneController.Instance.getCloneData(null, name, tab) != null;
}
NBTTagCompound compound = new NBTTagCompound();
compound.setBoolean("NameExists", bo);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
@@ -25,6 +25,7 @@ public final class CloneRemovePacket extends AbstractPacket {
public static String packetName = "Request|CloneRemove";
private int tab;
private String folderName;
private String name;
public CloneRemovePacket() {
@@ -32,6 +33,13 @@ public final class CloneRemovePacket extends AbstractPacket {
public CloneRemovePacket(int tab, String name) {
this.tab = tab;
this.folderName = null;
this.name = name;
}
public CloneRemovePacket(String folderName, String name) {
this.tab = -1;
this.folderName = folderName;
this.name = name;
}
@@ -54,6 +62,9 @@ public final class CloneRemovePacket extends AbstractPacket {
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeInt(tab);
if (tab == -1) {
ByteBufUtils.writeString(out, this.folderName);
}
ByteBufUtils.writeString(out, this.name);
}
@@ -65,16 +76,28 @@ public final class CloneRemovePacket extends AbstractPacket {
return;
int tab = in.readInt();
ServerCloneController.Instance.removeClone(ByteBufUtils.readString(in), tab);
String folder = null;
if (tab == -1) {
folder = ByteBufUtils.readString(in);
}
String cloneName = ByteBufUtils.readString(in);
NBTTagList list = new NBTTagList();
for (String name : ServerCloneController.Instance.getClones(tab))
list.appendTag(new NBTTagString(name));
NBTTagList listDate = new NBTTagList();
for (String name : ServerCloneController.Instance.getClonesDate(tab))
listDate.appendTag(new NBTTagString(name));
if (folder != null) {
ServerCloneController.Instance.removeClone(cloneName, folder);
for (String name : ServerCloneController.Instance.getClones(folder))
list.appendTag(new NBTTagString(name));
for (String name : ServerCloneController.Instance.getClonesDate(folder))
listDate.appendTag(new NBTTagString(name));
} else {
ServerCloneController.Instance.removeClone(cloneName, tab);
for (String name : ServerCloneController.Instance.getClones(tab))
list.appendTag(new NBTTagString(name));
for (String name : ServerCloneController.Instance.getClonesDate(tab))
listDate.appendTag(new NBTTagString(name));
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("List", list);
@@ -25,6 +25,7 @@ public final class CloneSavePacket extends AbstractPacket {
private String name;
private int tab;
private String folderName;
private NBTTagCompound tagExtra;
private NBTTagCompound tagCompound;
@@ -34,6 +35,15 @@ public final class CloneSavePacket extends AbstractPacket {
public CloneSavePacket(String name, int tab, NBTTagCompound tagExtra, NBTTagCompound tagCompound) {
this.name = name;
this.tab = tab;
this.folderName = null;
this.tagExtra = tagExtra;
this.tagCompound = tagCompound;
}
public CloneSavePacket(String name, String folderName, NBTTagCompound tagExtra, NBTTagCompound tagCompound) {
this.name = name;
this.tab = -1;
this.folderName = folderName;
this.tagExtra = tagExtra;
this.tagCompound = tagCompound;
}
@@ -58,6 +68,9 @@ public final class CloneSavePacket extends AbstractPacket {
public void sendData(ByteBuf out) throws IOException {
ByteBufUtils.writeString(out, this.name);
out.writeInt(tab);
if (tab == -1) {
ByteBufUtils.writeString(out, this.folderName);
}
ByteBufUtils.writeNBT(out, this.tagExtra);
ByteBufUtils.writeNBT(out, this.tagCompound);
}
@@ -75,11 +88,20 @@ public final class CloneSavePacket extends AbstractPacket {
String name = ByteBufUtils.readString(in);
int tab = in.readInt();
String folder = null;
if (tab == -1) {
folder = ByteBufUtils.readString(in);
}
NBTTagCompound tagExtra = ByteBufUtils.readNBT(in);
NBTTagCompound tagCompound = ByteBufUtils.readNBT(in);
NBTTagList tagList = tagCompound.getTagList("TagUUIDs", 8);
data.cloned.setTag("TagUUIDs", tagList);
ServerCloneController.Instance.addClone(data.cloned, name, tab, tagExtra);
if (folder != null) {
ServerCloneController.Instance.addClone(data.cloned, name, folder, tagExtra);
} else {
ServerCloneController.Instance.addClone(data.cloned, name, tab, tagExtra);
}
}
}
@@ -13,6 +13,7 @@ import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import kamkeel.npcs.util.ByteBufUtils;
import noppes.npcs.controllers.ServerTagMapController;
import noppes.npcs.controllers.data.TagMap;
@@ -22,9 +23,16 @@ public final class CloneTagListPacket extends AbstractPacket {
public static String packetName = "Request|CloneTagList";
private int tab;
private String folderName;
public CloneTagListPacket(int tab) {
this.tab = tab;
this.folderName = null;
}
public CloneTagListPacket(String folderName) {
this.tab = -1;
this.folderName = folderName;
}
public CloneTagListPacket() {
@@ -44,6 +52,9 @@ public final class CloneTagListPacket extends AbstractPacket {
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeInt(tab);
if (tab == -1) {
ByteBufUtils.writeString(out, folderName);
}
}
@Override
@@ -54,7 +65,13 @@ public final class CloneTagListPacket extends AbstractPacket {
return;
int tab = in.readInt();
TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab);
TagMap tagMap;
if (tab == -1) {
String folder = ByteBufUtils.readString(in);
tagMap = ServerTagMapController.Instance.getTagMap(folder);
} else {
tagMap = ServerTagMapController.Instance.getTagMap(tab);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("CloneTags", tagMap.writeNBT());
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
@@ -31,6 +31,7 @@ public class MobSpawnerPacket extends AbstractPacket {
private String selectedName;
private int tab;
private String folderName;
private NBTTagCompound compound;
@@ -44,6 +45,17 @@ public class MobSpawnerPacket extends AbstractPacket {
this.posz = posz;
this.selectedName = selectedName;
this.tab = tab;
this.folderName = null;
}
public MobSpawnerPacket(Action type, int posX, int posY, int posz, String selectedName, String folderName) {
this.type = type;
this.posX = posX;
this.posY = posY;
this.posz = posz;
this.selectedName = selectedName;
this.tab = -1;
this.folderName = folderName;
}
public MobSpawnerPacket(Action type, int posX, int posY, int posz, NBTTagCompound compound) {
@@ -58,6 +70,10 @@ public class MobSpawnerPacket extends AbstractPacket {
PacketClient.sendClient(new MobSpawnerPacket(Action.Server, x, y, z, name, tab));
}
public static void ServerFolder(int x, int y, int z, String name, String folderName) {
PacketClient.sendClient(new MobSpawnerPacket(Action.Server, x, y, z, name, folderName));
}
public static void Client(int x, int y, int z, NBTTagCompound compound) {
PacketClient.sendClient(new MobSpawnerPacket(Action.Client, x, y, z, compound));
}
@@ -88,6 +104,9 @@ public class MobSpawnerPacket extends AbstractPacket {
if (type == Action.Server) {
ByteBufUtils.writeString(out, this.selectedName);
out.writeInt(this.tab);
if (this.tab == -1) {
ByteBufUtils.writeString(out, this.folderName);
}
} else {
ByteBufUtils.writeNBT(out, this.compound);
}
@@ -107,10 +126,18 @@ public class MobSpawnerPacket extends AbstractPacket {
int z = in.readInt();
NBTTagCompound compound;
if (requestedAction == Action.Server)
compound = ServerCloneController.Instance.getCloneData(player, ByteBufUtils.readString(in), in.readInt());
else
if (requestedAction == Action.Server) {
String name = ByteBufUtils.readString(in);
int tab = in.readInt();
if (tab == -1) {
String folder = ByteBufUtils.readString(in);
compound = ServerCloneController.Instance.getCloneData(player, name, folder);
} else {
compound = ServerCloneController.Instance.getCloneData(player, name, tab);
}
} else {
compound = ByteBufUtils.readNBT(in);
}
if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) {
return;
@@ -37,6 +37,7 @@ public class SpawnMobPacket extends AbstractPacket {
private String selectedName;
private int tab;
private String folderName;
private NBTTagCompound compound;
@@ -50,6 +51,17 @@ public class SpawnMobPacket extends AbstractPacket {
this.posz = posz;
this.selectedName = selectedName;
this.tab = tab;
this.folderName = null;
}
public SpawnMobPacket(Action type, int posX, int posY, int posz, String selectedName, String folderName) {
this.type = type;
this.posX = posX;
this.posY = posY;
this.posz = posz;
this.selectedName = selectedName;
this.tab = -1;
this.folderName = folderName;
}
public SpawnMobPacket(Action type, int posX, int posY, int posz, NBTTagCompound compound) {
@@ -64,6 +76,10 @@ public class SpawnMobPacket extends AbstractPacket {
PacketClient.sendClient(new SpawnMobPacket(Action.Server, x, y, z, name, tab));
}
public static void ServerFolder(int x, int y, int z, String name, String folderName) {
PacketClient.sendClient(new SpawnMobPacket(Action.Server, x, y, z, name, folderName));
}
public static void Client(int x, int y, int z, NBTTagCompound compound) {
PacketClient.sendClient(new SpawnMobPacket(Action.Client, x, y, z, compound));
}
@@ -94,6 +110,9 @@ public class SpawnMobPacket extends AbstractPacket {
if (type == Action.Server) {
ByteBufUtils.writeString(out, this.selectedName);
out.writeInt(this.tab);
if (this.tab == -1) {
ByteBufUtils.writeString(out, this.folderName);
}
} else {
ByteBufUtils.writeNBT(out, this.compound);
}
@@ -113,10 +132,18 @@ public class SpawnMobPacket extends AbstractPacket {
int z = in.readInt();
NBTTagCompound compound;
if (requestedAction == Action.Server)
compound = ServerCloneController.Instance.getCloneData(player, ByteBufUtils.readString(in), in.readInt());
else
if (requestedAction == Action.Server) {
String name = ByteBufUtils.readString(in);
int tab = in.readInt();
if (tab == -1) {
String folder = ByteBufUtils.readString(in);
compound = ServerCloneController.Instance.getCloneData(player, name, folder);
} else {
compound = ServerCloneController.Instance.getCloneData(player, name, tab);
}
} else {
compound = ByteBufUtils.readNBT(in);
}
if (compound == null)
return;
@@ -13,6 +13,7 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.NBTTags;
import noppes.npcs.client.ScriptClientConfig;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.controllers.ScriptController;
@@ -39,7 +40,7 @@ public final class ScriptFilesPacket extends AbstractPacket {
@Override
public PacketChannel getChannel() {
return PacketHandler.DATA_PACKET;
return PacketHandler.REQUEST_PACKET;
}
@Override
@@ -47,7 +48,6 @@ public final class ScriptFilesPacket extends AbstractPacket {
return CustomNpcsPermissions.SCRIPT_GLOBAL;
}
@SideOnly(Side.CLIENT)
@Override
public void sendData(ByteBuf out) throws IOException {
ByteBufUtils.writeNBT(out, getScriptsNbt(lang));
@@ -70,8 +70,8 @@ public final class ScriptFilesPacket extends AbstractPacket {
}
//Set client side configs
ConfigScript.ScriptingEnabled = compound.getBoolean("ScriptingEnabled");
ConfigScript.RunLoadedScriptsFirst = compound.getBoolean("LoadedFirst");
ScriptClientConfig.setScriptingEnabled(compound.getBoolean("ScriptingEnabled"));
ScriptClientConfig.setRunLoadedScriptsFirst(compound.getBoolean("LoadedFirst"));
ScriptController.Instance.globalRevision = compound.getInteger("GlobalRevision");
}
@@ -100,9 +100,12 @@ public class AnchorPointHelper {
break;
}
x += anchorX * scale;
y += anchorY * scale;
z += anchorZ * scale;
// Rotate offsets relative to entity's body yaw
// +X = entity's right, +Y = up, +Z = entity's forward
Vec3 rotatedOffset = rotateOffsetByYaw(anchorX * scale, anchorY * scale, anchorZ * scale, bodyYaw);
x += rotatedOffset.xCoord;
y += rotatedOffset.yCoord;
z += rotatedOffset.zCoord;
return Vec3.createVectorHelper(x, y, z);
}
@@ -229,9 +232,8 @@ public class AnchorPointHelper {
double blockZ = modelZ * MODEL_SCALE * scale;
// Apply body yaw rotation
// Renderer uses glRotate(180 - yaw), so: cos(180-yaw) = -cos(yaw), sin(180-yaw) = sin(yaw)
// Y-axis rotation: x' = x*cos + z*sin, z' = -x*sin + z*cos
// Substituting: x' = -x*cos(yaw) + z*sin(yaw), z' = -x*sin(yaw) - z*cos(yaw)
// Renderer applies glRotatef(180 - yaw) then glScalef(-1, -1, 1).
// Combined transform: x' = mx*cos(yaw) + mz*sin(yaw), z' = mx*sin(yaw) - mz*cos(yaw)
float bodyYaw = (float) Math.toRadians(entity.renderYawOffset);
double cosYaw = Math.cos(bodyYaw);
double sinYaw = Math.sin(bodyYaw);
@@ -247,9 +249,11 @@ public class AnchorPointHelper {
double worldY = entity.posY + shoulderHeight - blockY;
double worldZ = entity.posZ + worldOffsetZ;
worldX += anchor.anchorOffsetX * scale;
worldY += anchor.anchorOffsetY * scale;
worldZ += anchor.anchorOffsetZ * scale;
// Rotate offsets relative to entity's body yaw
Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw);
worldX += rotatedOffset.xCoord;
worldY += rotatedOffset.yCoord;
worldZ += rotatedOffset.zCoord;
return Vec3.createVectorHelper(worldX, worldY, worldZ);
}
@@ -318,9 +322,11 @@ public class AnchorPointHelper {
double y = entity.posY + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset;
double z = entity.posZ + lateralZ + forwardZ;
x += anchor.anchorOffsetX * scale;
y += anchor.anchorOffsetY * scale;
z += anchor.anchorOffsetZ * scale;
// Rotate offsets relative to entity's body yaw
Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw);
x += rotatedOffset.xCoord;
y += rotatedOffset.yCoord;
z += rotatedOffset.zCoord;
return Vec3.createVectorHelper(x, y, z);
}
@@ -345,4 +351,17 @@ public class AnchorPointHelper {
return FRONT_HEIGHT;
}
}
/**
* Rotate an offset vector by the entity's body yaw so offsets are entity-relative.
* +X = entity's right, +Y = up, +Z = entity's forward.
* @param bodyYawRad body yaw in radians
*/
private static Vec3 rotateOffsetByYaw(double offsetX, double offsetY, double offsetZ, float bodyYawRad) {
double cos = Math.cos(bodyYawRad);
double sin = Math.sin(bodyYawRad);
double worldX = -offsetX * cos - offsetZ * sin;
double worldZ = -offsetX * sin + offsetZ * cos;
return Vec3.createVectorHelper(worldX, offsetY, worldZ);
}
}
@@ -33,6 +33,8 @@ public class BukkitUtil {
private static Method getPluginManager;
private static Method isPluginEnabled;
private static Method getPlugin;
/**
* Initializes Bukkit integration using reflection.
* Should be called during FMLServerStartedEvent to ensure Bukkit is fully loaded.
@@ -63,6 +65,7 @@ public class BukkitUtil {
Class<?> pluginManagerClass = Class.forName("org.bukkit.plugin.PluginManager");
isPluginEnabled = pluginManagerClass.getMethod("isPluginEnabled", String.class);
getPlugin = pluginManagerClass.getMethod("getPlugin", String.class);
bukkitEnabled = true;
logger.info("Bukkit integration enabled");
@@ -95,7 +98,6 @@ public class BukkitUtil {
/**
* Checks if a specific Bukkit plugin is enabled.
*
* @param pluginName the plugin name to check
* @return true if the plugin is enabled
*/
@@ -113,7 +115,6 @@ public class BukkitUtil {
/**
* Gets a Bukkit OfflinePlayer by name.
*
* @param playerName the player name
* @return the OfflinePlayer object, or null if not available
*/
@@ -130,7 +131,6 @@ public class BukkitUtil {
/**
* Gets a Bukkit Player by name (online players only).
*
* @param playerName the player name
* @return the Player object, or null if not online or not available
*/
@@ -147,7 +147,6 @@ public class BukkitUtil {
/**
* Gets a service provider from Bukkit's ServicesManager.
*
* @param serviceClass the service class to get
* @return the service provider, or null if not available
*/
@@ -186,4 +185,13 @@ public class BukkitUtil {
public static Class<?> getPlayerClass() {
return playerClass;
}
public static Object getPlugin(String plugin) {
try {
return getPlugin.invoke(getPluginManager.invoke(null), plugin);
} catch (Throwable ignored) {
}
return null;
}
}
@@ -0,0 +1,131 @@
package kamkeel.npcs.util;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import noppes.npcs.LogWriter;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
import java.util.*;
import java.util.function.Supplier;
public class Register<T> {
public static final Map<String, List<String>> REGISTERED_NAMESPACES = new LinkedHashMap<>();
public static final Map<String, String> NAMESPACE_DISPLAY_NAMES = new LinkedHashMap<>();
private final String registryKey;
protected final String namespace;
protected final Map<String, Supplier<T>> entries = new LinkedHashMap<>();
private Register(String registryKey, String namespace) {
this.registryKey = registryKey;
this.namespace = namespace;
}
public T register(String factoryName, Supplier<T> factory) {
entries.put(registryKey + "." + namespace + "." + factoryName, factory);
return factory.get();
}
public static boolean isEmpty(String registryKey) {
if (REGISTERED_NAMESPACES.isEmpty()) return true;
List<String> list = REGISTERED_NAMESPACES.get(registryKey);
if (list == null || list.isEmpty()) return true;
return false;
}
public List<T> catalogue() {
List<T> list = new ArrayList<>();
for (String regKey : REGISTERED_NAMESPACES.keySet()) {
List<String> nameSp = REGISTERED_NAMESPACES.get(regKey);
for (String name : nameSp) {
List<T> nameSpContent = catalogue(regKey, name);
list.addAll(nameSpContent);
}
}
return list;
}
public List<T> catalogue(String namespace) {
return catalogue(registryKey, namespace);
}
public List<T> catalogue(String registryKey, String namespace) {
List<T> list = new ArrayList<>();
for (Map.Entry<String, Supplier<T>> entry : entries.entrySet()) {
if (entry.getKey().startsWith(registryKey + "." + namespace + ":"))
list.add(entry.getValue().get());
}
return list;
}
public static class Abilities extends Register<Ability> {
private Abilities(String namespace) {
super("ability", namespace);
}
public void register() {
for (Map.Entry<String, Supplier<Ability>> entry : entries.entrySet()) {
AbilityController.Instance.registerType(entry.getValue().get().getTypeId(), entry.getValue());
}
}
public static Register.Abilities create(String namespace, String displayName) {
if (!REGISTERED_NAMESPACES.containsKey("ability"))
REGISTERED_NAMESPACES.put("ability", new ArrayList<>());
if (REGISTERED_NAMESPACES.get("ability").contains(namespace)) {
LogWriter.error("REGISTER ABILITIES: Namespace " + namespace + " already registered!");
}
REGISTERED_NAMESPACES.get("ability").add(namespace);
NAMESPACE_DISPLAY_NAMES.put(namespace, displayName);
return new Register.Abilities(namespace);
}
}
public static class Animations extends Register<Animation> {
private final Class<?> modClass;
private final String animationsPath;
private Animations(Class<?> modClass, String animationsPath, String namespace) {
super("animation", namespace);
this.animationsPath = animationsPath;
this.modClass = modClass;
}
@Override
public Animation register(String factoryName, Supplier<Animation> factory) {
return super.register(factoryName, factory);
}
public void register() {
try {
String path = "/assets/" + namespace + "/" + animationsPath;
for (Map.Entry<String, Supplier<Animation>> entry : entries.entrySet()) {
String name = entry.getKey().substring(entry.getKey().indexOf(namespace + ".") + 1);
AnimationController.Instance.loadBuiltInAnimation(modClass, path, name);
}
} catch (Exception e) {
LogWriter.error("Error scanning built-in animations folder", e);
}
}
public static Register.Animations create(Class<?> modClass, String animationsPath, String namespace) {
if (!REGISTERED_NAMESPACES.containsKey("animation"))
REGISTERED_NAMESPACES.put("animation", new ArrayList<>());
if (REGISTERED_NAMESPACES.get("animation").contains(namespace)) {
LogWriter.error("REGISTER ANIMATIONS: Namespace " + namespace + " already registered!");
}
REGISTERED_NAMESPACES.get("animation").add(namespace);
return new Register.Animations(modClass, animationsPath, namespace);
}
}
}
+17 -37
View File
@@ -75,8 +75,12 @@ public class VaultUtil {
}
// Load Vault classes
economyClass = Class.forName("net.milkbowl.vault.economy.Economy");
economyResponseClass = Class.forName("net.milkbowl.vault.economy.EconomyResponse");
Object vault = BukkitUtil.getPlugin("Vault");
if (vault == null)
return;
ClassLoader vaultLoader = vault.getClass().getClassLoader();
economyClass = vaultLoader.loadClass("net.milkbowl.vault.economy.Economy");
economyResponseClass = vaultLoader.loadClass("net.milkbowl.vault.economy.EconomyResponse");
// Get Economy methods (using deprecated String methods for broader compatibility)
isEnabled = economyClass.getMethod("isEnabled");
@@ -174,7 +178,6 @@ public class VaultUtil {
/**
* Checks if a player has an account in the economy system.
*
* @param player the player to check
* @return true if the player has an account
*/
@@ -184,7 +187,6 @@ public class VaultUtil {
/**
* Checks if a player has an account in the economy system.
*
* @param playerName the player name to check
* @return true if the player has an account
*/
@@ -205,7 +207,6 @@ public class VaultUtil {
/**
* Gets the balance of a player.
*
* @param player the player
* @return the player's balance, or 0 if not available
*/
@@ -215,7 +216,6 @@ public class VaultUtil {
/**
* Gets the balance of a player by name.
*
* @param playerName the player name
* @return the player's balance, or 0 if not available
*/
@@ -236,7 +236,6 @@ public class VaultUtil {
/**
* Checks if a player has at least the specified amount.
*
* @param player the player
* @param amount the amount to check
* @return true if the player has at least the specified amount
@@ -247,9 +246,8 @@ public class VaultUtil {
/**
* Checks if a player has at least the specified amount.
*
* @param playerName the player name
* @param amount the amount to check
* @param amount the amount to check
* @return true if the player has at least the specified amount
*/
public static boolean has(String playerName, double amount) {
@@ -269,7 +267,6 @@ public class VaultUtil {
/**
* Withdraws money from a player's account.
*
* @param player the player
* @param amount the amount to withdraw
* @return true if the transaction was successful
@@ -280,9 +277,8 @@ public class VaultUtil {
/**
* Withdraws money from a player's account.
*
* @param playerName the player name
* @param amount the amount to withdraw
* @param amount the amount to withdraw
* @return true if the transaction was successful
*/
public static boolean withdrawMoney(String playerName, double amount) {
@@ -305,7 +301,6 @@ public class VaultUtil {
/**
* Adds money to a player's account (deposit).
*
* @param player the player
* @param amount the amount to add
* @return true if the transaction was successful
@@ -316,9 +311,8 @@ public class VaultUtil {
/**
* Adds money to a player's account (deposit).
*
* @param playerName the player name
* @param amount the amount to add
* @param amount the amount to add
* @return true if the transaction was successful
*/
public static boolean addMoney(String playerName, double amount) {
@@ -342,7 +336,6 @@ public class VaultUtil {
/**
* Sets a player's balance to the specified amount.
* This withdraws all money first, then deposits the new amount.
*
* @param player the player
* @param amount the new balance
* @return true if the transaction was successful
@@ -354,9 +347,8 @@ public class VaultUtil {
/**
* Sets a player's balance to the specified amount.
* This withdraws all money first, then deposits the new amount.
*
* @param playerName the player name
* @param amount the new balance
* @param amount the new balance
* @return true if the transaction was successful
*/
public static boolean setBalance(String playerName, double amount) {
@@ -376,7 +368,6 @@ public class VaultUtil {
/**
* Formats an amount according to the economy plugin's settings.
*
* @param amount the amount to format
* @return the formatted string, or the raw number as string if not available
*/
@@ -393,7 +384,6 @@ public class VaultUtil {
/**
* Gets the plural currency name (e.g., "Dollars").
*
* @return the plural currency name, or "coins" if not available
*/
public static String getCurrencyNamePlural() {
@@ -409,7 +399,6 @@ public class VaultUtil {
/**
* Gets the singular currency name (e.g., "Dollar").
*
* @return the singular currency name, or "coin" if not available
*/
public static String getCurrencyNameSingular() {
@@ -425,7 +414,6 @@ public class VaultUtil {
/**
* Creates an account for the player if one doesn't exist.
*
* @param player the player
* @return true if the account was created or already exists
*/
@@ -435,7 +423,6 @@ public class VaultUtil {
/**
* Creates an account for the player if one doesn't exist.
*
* @param playerName the player name
* @return true if the account was created or already exists
*/
@@ -472,7 +459,6 @@ public class VaultUtil {
/**
* Gets a list of all bank names.
*
* @return list of bank names, or empty list if not available
*/
@SuppressWarnings("unchecked")
@@ -489,7 +475,6 @@ public class VaultUtil {
/**
* Gets the balance of a bank.
*
* @param bankName the bank name
* @return the bank balance, or 0 if not available
*/
@@ -507,9 +492,8 @@ public class VaultUtil {
/**
* Checks if a bank has at least the specified amount.
*
* @param bankName the bank name
* @param amount the amount to check
* @param amount the amount to check
* @return true if the bank has at least the specified amount
*/
public static boolean bankHas(String bankName, double amount) {
@@ -526,9 +510,8 @@ public class VaultUtil {
/**
* Withdraws money from a bank.
*
* @param bankName the bank name
* @param amount the amount to withdraw
* @param amount the amount to withdraw
* @return true if the transaction was successful
*/
public static boolean bankWithdraw(String bankName, double amount) {
@@ -545,9 +528,8 @@ public class VaultUtil {
/**
* Deposits money into a bank.
*
* @param bankName the bank name
* @param amount the amount to deposit
* @param amount the amount to deposit
* @return true if the transaction was successful
*/
public static boolean bankDeposit(String bankName, double amount) {
@@ -564,9 +546,8 @@ public class VaultUtil {
/**
* Transfers money from one player to another.
*
* @param from the player to take money from
* @param to the player to give money to
* @param from the player to take money from
* @param to the player to give money to
* @param amount the amount to transfer
* @return true if the transfer was successful
*/
@@ -576,10 +557,9 @@ public class VaultUtil {
/**
* Transfers money from one player to another.
*
* @param fromPlayerName the player name to take money from
* @param toPlayerName the player name to give money to
* @param amount the amount to transfer
* @param toPlayerName the player name to give money to
* @param amount the amount to transfer
* @return true if the transfer was successful
*/
public static boolean transfer(String fromPlayerName, String toPlayerName, double amount) {
@@ -43,6 +43,7 @@ import noppes.npcs.containers.ContainerNpcQuestReward;
import noppes.npcs.containers.ContainerNpcQuestTypeItem;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.entity.EntityNPCInterface;
public class CommonProxy implements IGuiHandler {
@@ -220,4 +221,24 @@ public class CommonProxy implements IGuiHandler {
public void buildPackageIndex() {
}
public boolean isScriptingEnabled() {
return ConfigScript.ScriptingEnabled;
}
public boolean isRunLoadedScriptsFirst() {
return ConfigScript.RunLoadedScriptsFirst;
}
public boolean isGlobalPlayerScripts() {
return ConfigScript.GlobalPlayerScripts;
}
public boolean isGlobalForgeScripts() {
return ConfigScript.GlobalForgeScripts;
}
public boolean isGlobalNPCScripts() {
return ConfigScript.GlobalNPCScripts;
}
}
+7 -1
View File
@@ -158,7 +158,13 @@ public class CustomNpcs {
@SideOnly(Side.CLIENT)
private static IDynamicCompiler clientJaninoCompiler;
@SideOnly(Side.CLIENT)
private final static Set<Consumer<AdvancedClassFilter>> clientClassFilterConsumer = new HashSet<>();
private static Set<Consumer<AdvancedClassFilter>> clientClassFilterConsumer;
static {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
clientClassFilterConsumer = new HashSet<>();
}
}
@SideOnly(Side.CLIENT)
public static void addClassesToClientClassFilter(Consumer<AdvancedClassFilter> consumer) {
@@ -66,8 +66,8 @@ public class CustomNpcsPermissions {
public static final Permission GLOBAL_NATURALSPAWN = new Permission("customnpcs.global.naturalspawn");
public static final Permission GLOBAL_TAG = new Permission("customnpcs.global.tag");
public static final Permission GLOBAL_ANIMATION = new Permission("customnpcs.global.animation");
public static final Permission GLOBAL_ABILITY = new Permission("customnpcs.global.ability");
public static final Permission GLOBAL_MAGIC = new Permission("customnpcs.global.magic");
public static final Permission GLOBAL_ABILITY = new Permission("customnpcs.global.ability");
public static final Permission GLOBAL_EFFECT = new Permission("customnpcs.global.effect");
public static final Permission SPAWNER_MOB = new Permission("customnpcs.spawner.mob");
@@ -111,9 +111,6 @@ public class CustomNpcsPermissions {
public static final Permission PROFILE_REGION_BYPASS = new Permission("customnpcs.profile.region-bypass");
public static final Permission PROFILE_MAX = new Permission("customnpcs.profile.max.*");
// Auction
public static final Permission AUCTION_TRADES_MAX = new Permission("customnpcs.auction.trades.*");
public static CustomNpcsPermissions Instance;
private Method hasPermission;
+348 -53
View File
@@ -18,6 +18,7 @@ import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.AbilityEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -43,7 +44,7 @@ public class DataAbilities {
/**
* Whether the ability system is enabled for this NPC
*/
public boolean enabled = false;
public boolean enabled = true;
/**
* Minimum cooldown ticks between abilities (global minimum)
@@ -89,6 +90,24 @@ public class DataAbilities {
private transient float lockedRenderYawOffset = 0;
private transient float lockedPitch = 0;
/**
* Locked position values for movement lock.
* Stored when entering a locked phase, applied after super.onLivingUpdate()
* to override any position changes from AI/physics.
*/
private transient boolean positionLocked = false;
private transient double lockedPosX = 0;
private transient double lockedPosY = 0;
private transient double lockedPosZ = 0;
/**
* Hit scan state - forces NPC to face target.
* Set during tickCurrentAbility(), applied after super.onLivingUpdate()
* to override AI look helper rotation.
*/
private transient boolean hitScanActive = false;
private transient EntityLivingBase hitScanTarget = null;
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════════════
@@ -106,10 +125,33 @@ public class DataAbilities {
* Should be called every tick from onLivingUpdate().
*/
public void tick() {
if (!enabled || npc.worldObj.isRemote || npc.isKilled()) {
if (npc.worldObj.isRemote) {
return;
}
// Force-stop any running ability when NPC is killed or abilities are disabled
if (!enabled || npc.isKilled()) {
if (currentAbility != null) {
removeTelegraph(currentAbility);
stopAbilityAnimation();
releaseRotationControl();
releaseLockedPosition();
currentAbility = null;
lastTarget = null;
} else {
// No ability but locks could be orphaned
if (rotationLocked || hitScanActive) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
}
return;
}
// Safety: release orphaned locks if no ability is actively executing
if (currentAbility == null || !currentAbility.isExecuting()) {
if (rotationLocked || hitScanActive) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
}
// Tick current ability if executing
if (currentAbility != null && currentAbility.isExecuting()) {
tickCurrentAbility();
@@ -132,11 +174,23 @@ public class DataAbilities {
// Handle phase-specific logic
switch (currentAbility.getPhase()) {
case WINDUP:
if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) {
// Burst replay: re-enter windup - set up telegraph, sound, animation, locks
if (currentAbility.isRotationLockedDuringWindup()) {
captureLockedRotation();
}
if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) {
captureLockedPosition();
}
spawnTelegraph(currentAbility, target);
playAbilitySound(currentAbility.getWindUpSound());
playAbilityAnimation(currentAbility.getWindUpAnimation());
}
currentAbility.onWindUpTick(npc, target, npc.worldObj, currentAbility.getCurrentTick());
break;
case ACTIVE:
if (phaseChanged && oldPhase == AbilityPhase.WINDUP) {
if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) {
// Just entered ACTIVE phase - lock telegraph position if it was following
// This commits the ability to its current target position
TelegraphInstance telegraph = currentAbility.getTelegraphInstance();
@@ -147,16 +201,38 @@ public class DataAbilities {
// Remove telegraph - it has served its purpose
removeTelegraph(currentAbility);
// Lock rotation if movement is locked during ACTIVE phase
// Capture current rotation values to force them every tick
if (currentAbility.isMovementLockedDuringActive()) {
captureLockedRotation();
// Handle rotation control transition from WINDUP to ACTIVE
if (currentAbility.isRotationLockedDuringActive()) {
if (!rotationLocked) {
captureLockedRotation();
}
} else if (rotationLocked) {
releaseRotationControl();
}
// Handle position lock transition from WINDUP to ACTIVE
if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) {
if (!positionLocked) {
captureLockedPosition();
}
} else if (positionLocked) {
releaseLockedPosition();
}
// Burst re-fire without replay: let entity-spawning abilities spawn+fire in one step
if (oldPhase == AbilityPhase.BURST_DELAY && !currentAbility.isBurstReplayAnimations()) {
currentAbility.onBurstRefire(npc, target, npc.worldObj);
}
// Play active sound and animation
playAbilitySound(currentAbility.getActiveSound());
playAbilityAnimation(currentAbility.getActiveAnimation());
// Snap NPC to face target before execute so startMoving() reads correct rotation
if (currentAbility.isHitScanForCurrentPhase() && target != null) {
faceTarget(target);
}
// Fire execute event (cancelable)
AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent(
npc.wrappedNPC, currentAbility, target);
@@ -181,6 +257,31 @@ public class DataAbilities {
handleAbilityCompletion(target);
return;
}
// Auto-complete for burst overlap mode (entities fly independently)
// This allows entity-spawning abilities to immediately chain next burst
// without each type needing to check burst state in their onActiveTick()
// Wait until all staggered projectiles have been fired before auto-completing
if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap()
&& currentAbility.getBurstIndex() < currentAbility.getBurstAmount()
&& currentAbility.getPhase() == AbilityPhase.ACTIVE
&& currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) {
currentAbility.signalCompletion();
}
// Check if ability entered burst delay during onActiveTick or overlap auto-complete
if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) {
// Release all locks - free movement/rotation during delay
if (rotationLocked) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
if (hitScanActive) releaseRotationControl();
}
break;
case BURST_DELAY:
// Free movement and rotation during burst delay
if (rotationLocked) releaseRotationControl();
if (positionLocked) releaseLockedPosition();
break;
case DAZED:
@@ -193,6 +294,15 @@ public class DataAbilities {
break;
}
// Update hit scan state - actual facing is deferred to applyRotationControl()
// which runs AFTER super.onLivingUpdate() to override AI look helper
if (currentAbility != null && currentAbility.isExecuting()
&& currentAbility.isHitScanForCurrentPhase() && target != null) {
enableHitScan(target);
} else if (hitScanActive) {
releaseRotationControl();
}
// Apply movement control if ability is still executing
if (currentAbility != null && currentAbility.isExecuting()) {
applyMovementControl();
@@ -237,8 +347,9 @@ public class DataAbilities {
npc.wrappedNPC, currentAbility, target);
NpcAPI.EVENT_BUS.post(completeEvent);
// Release rotation lock before cleanup
releaseLockedRotation();
// Release locks before cleanup
releaseRotationControl();
releaseLockedPosition();
// Clean up and roll cooldown (this sets currentAbility to null)
onAbilityComplete();
@@ -253,8 +364,9 @@ public class DataAbilities {
// Stop any ability animation
stopAbilityAnimation();
// Release rotation lock
releaseLockedRotation();
// Release locks
releaseRotationControl();
releaseLockedPosition();
// Calculate cooldown: random(min, max) + ability offset
int abilityCooldownOffset = currentAbility.getCooldownTicks();
@@ -343,6 +455,11 @@ public class DataAbilities {
* Check if a specific ability is eligible for use.
*/
private boolean isAbilityEligible(Ability ability, EntityLivingBase target) {
// Check UserType allows NPCs
if (!ability.getAllowedBy().allowsNpc()) {
return false;
}
// Check enabled
if (!ability.isEnabled()) {
return false;
@@ -385,18 +502,58 @@ public class DataAbilities {
lastTarget = target;
ability.start(target);
// Spawn telegraph and send to clients
spawnTelegraph(ability, target);
// Play wind up sound if configured
playAbilitySound(ability.getWindUpSound());
// Play wind up animation if configured
playAbilityAnimation(ability.getWindUpAnimation());
if (ability.getPhase() == AbilityPhase.ACTIVE) {
// Windup was 0 — skip telegraph/windup and go straight to active
executeImmediate(ability, target);
} else {
// Normal windup flow
if (ability.isRotationLockedDuringWindup()) {
captureLockedRotation();
}
if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) {
captureLockedPosition();
}
spawnTelegraph(ability, target);
playAbilitySound(ability.getWindUpSound());
playAbilityAnimation(ability.getWindUpAnimation());
}
return true;
}
/**
* Execute an ability immediately (no windup).
* Called when windUpTicks is 0.
*/
private void executeImmediate(Ability ability, EntityLivingBase target) {
// Lock rotation if rotation is locked during ACTIVE phase
if (ability.isRotationLockedDuringActive()) {
captureLockedRotation();
}
if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) {
captureLockedPosition();
}
// Play active sound and animation
playAbilitySound(ability.getActiveSound());
playAbilityAnimation(ability.getActiveAnimation());
// Fire execute event (cancelable)
AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent(
npc.wrappedNPC, ability, target);
if (NpcAPI.EVENT_BUS.post(executeEvent)) {
return;
}
// Call onExecute
ability.onExecute(npc, target, npc.worldObj);
// Check if ability completed during onExecute
if (ability.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(target);
}
}
/**
* Play a sound at the NPC's location.
*/
@@ -429,6 +586,14 @@ public class DataAbilities {
playAbilityAnimation((Animation) AnimationController.Instance.get(animation));
}
public void playAbilityAnimation(String animation) {
if (animation.isEmpty()) return;
if (AnimationController.Instance == null) return;
if (AnimationController.Instance.get(animation, true) == null) return;
playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true));
}
/**
* Stop any currently playing ability animation.
*/
@@ -501,18 +666,12 @@ public class DataAbilities {
// Track hit for hit count condition
recordHit();
// Check if currently executing a Guard ability and notify it of damage taken
if (currentAbility instanceof AbilityGuard) {
AbilityGuard guard = (AbilityGuard) currentAbility;
if (guard.isGuarding() && source.getEntity() instanceof EntityLivingBase) {
guard.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount);
}
}
if (currentAbility == null || !currentAbility.isExecuting()) {
return false;
}
currentAbility.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount);
if (currentAbility.canInterrupt(source)) {
interruptCurrentAbility(source, amount);
return true;
@@ -583,8 +742,9 @@ public class DataAbilities {
// Stop any ability animation
stopAbilityAnimation();
// Release rotation lock
releaseLockedRotation();
// Release locks
releaseRotationControl();
releaseLockedPosition();
// Fire interrupt event
AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent(
@@ -606,7 +766,8 @@ public class DataAbilities {
if (currentAbility != null) {
removeTelegraph(currentAbility);
stopAbilityAnimation();
releaseLockedRotation();
releaseRotationControl();
releaseLockedPosition();
currentAbility.interrupt();
currentAbility = null;
lastTarget = null;
@@ -626,6 +787,11 @@ public class DataAbilities {
return false;
}
// Check UserType allows NPCs
if (!ability.getAllowedBy().allowsNpc()) {
return false;
}
// Stop any currently executing ability
stopCurrentAbility();
@@ -898,12 +1064,15 @@ public class DataAbilities {
}
// ═══════════════════════════════════════════════════════════════════
// ROTATION LOCKING
// ROTATION CONTROL
// ═══════════════════════════════════════════════════════════════════
/** Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15 */
private static final int ROTATION_CONTROLLED_FLAG = 16;
/**
* Capture current rotation values to lock NPC's look direction.
* Called when entering ACTIVE phase with movement locked during active.
* Called when entering a LOCKED rotation phase.
*/
private void captureLockedRotation() {
lockedYaw = npc.rotationYaw;
@@ -911,44 +1080,170 @@ public class DataAbilities {
lockedRenderYawOffset = npc.renderYawOffset;
lockedPitch = npc.rotationPitch;
rotationLocked = true;
npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG);
}
/**
* Release the rotation lock.
* Called when leaving ACTIVE phase or ability completes.
* Release rotation control (both locked and hit scan).
*/
private void releaseLockedRotation() {
private void releaseRotationControl() {
rotationLocked = false;
hitScanActive = false;
hitScanTarget = null;
npc.setBoolFlag(false, ROTATION_CONTROLLED_FLAG);
}
/**
* Apply locked rotation values to the NPC.
* Called AFTER super.onLivingUpdate() in EntityNPCInterface to override
* any rotation changes made by the look helper or AI tasks.
* Enable hit scan tracking for the given target.
*/
public void applyLockedRotation() {
if (!rotationLocked) {
private void enableHitScan(EntityLivingBase target) {
if (!hitScanActive) {
hitScanActive = true;
npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG);
}
hitScanTarget = target;
}
/**
* Snap the NPC to face the target instantly.
*/
private void faceTarget(EntityLivingBase target) {
double dx = target.posX - npc.posX;
double dz = target.posZ - npc.posZ;
double dy = (target.posY + target.getEyeHeight() * 0.5) - (npc.posY + npc.getEyeHeight());
double distXZ = Math.sqrt(dx * dx + dz * dz);
float yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI);
float pitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI);
npc.rotationYaw = yaw;
npc.rotationYawHead = yaw;
npc.renderYawOffset = yaw;
npc.rotationPitch = pitch;
npc.prevRotationYaw = yaw;
npc.prevRotationYawHead = yaw;
npc.prevRenderYawOffset = yaw;
npc.prevRotationPitch = pitch;
}
/**
* Apply rotation control after super.onLivingUpdate() and super.onUpdate().
* Handles both LOCKED (freeze at captured values) and TRACK (face target) modes.
*
* Server: computes the correct rotation (locked values or target facing).
* Client: trusts the server-synced rotation values and prevents body smoothing override.
*/
public void applyRotationControl() {
if (npc.worldObj.isRemote) {
// Client: check single flag for any rotation control
if (!npc.getBoolFlag(ROTATION_CONTROLLED_FLAG)) {
rotationLocked = false;
return;
}
// Trust server rotation, prevent body smoothing from overriding
npc.prevRotationYaw = npc.rotationYaw;
npc.prevRotationYawHead = npc.rotationYawHead;
npc.renderYawOffset = npc.rotationYawHead;
npc.prevRenderYawOffset = npc.rotationYawHead;
npc.prevRotationPitch = npc.rotationPitch;
return;
}
// Force rotation back to locked values
npc.rotationYaw = lockedYaw;
npc.rotationYawHead = lockedYawHead;
npc.renderYawOffset = lockedRenderYawOffset;
npc.rotationPitch = lockedPitch;
// Also set prev values to prevent interpolation jitter
npc.prevRotationYaw = lockedYaw;
npc.prevRotationYawHead = lockedYawHead;
npc.prevRenderYawOffset = lockedRenderYawOffset;
npc.prevRotationPitch = lockedPitch;
// Server: apply the appropriate rotation
if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) {
faceTarget(hitScanTarget);
} else if (rotationLocked) {
npc.rotationYaw = lockedYaw;
npc.rotationYawHead = lockedYawHead;
npc.renderYawOffset = lockedRenderYawOffset;
npc.rotationPitch = lockedPitch;
npc.prevRotationYaw = lockedYaw;
npc.prevRotationYawHead = lockedYawHead;
npc.prevRenderYawOffset = lockedRenderYawOffset;
npc.prevRotationPitch = lockedPitch;
}
}
/**
* Check if rotation is currently locked.
* Check if rotation is currently controlled (locked or tracking target).
* Used by AI tasks to determine if they should try to change NPC look direction.
*/
public boolean isRotationLocked() {
return rotationLocked;
return rotationLocked || hitScanActive;
}
// ═══════════════════════════════════════════════════════════════════
// POSITION LOCKING
// ═══════════════════════════════════════════════════════════════════
/** Bit flag for position lock in data watcher slot 15 */
private static final int POSITION_LOCKED_FLAG = 32;
/**
* Capture current position to lock NPC in place.
* Called when entering a phase with movement lock.
*/
private void captureLockedPosition() {
lockedPosX = npc.posX;
lockedPosY = npc.posY;
lockedPosZ = npc.posZ;
positionLocked = true;
npc.setBoolFlag(true, POSITION_LOCKED_FLAG);
}
/**
* Release the position lock.
* Called when leaving the locked phase or ability completes.
*/
private void releaseLockedPosition() {
positionLocked = false;
npc.setBoolFlag(false, POSITION_LOCKED_FLAG);
}
/**
* Apply locked position values to the NPC.
* Called AFTER super.onLivingUpdate() in EntityNPCInterface to override
* any position changes from AI pathfinding, physics, or entity collisions.
* Runs on both client and server.
*/
public void applyLockedPosition() {
if (npc.worldObj.isRemote) {
// Client-side: check flag via data watcher
boolean flagActive = npc.getBoolFlag(POSITION_LOCKED_FLAG);
if (!flagActive) {
positionLocked = false;
return;
}
// First tick the flag is active: capture current position
if (!positionLocked) {
lockedPosX = npc.posX;
lockedPosY = npc.posY;
lockedPosZ = npc.posZ;
positionLocked = true;
}
// Snap position back and set prev to prevent interpolation jitter
npc.setPosition(lockedPosX, lockedPosY, lockedPosZ);
npc.prevPosX = lockedPosX;
npc.prevPosY = lockedPosY;
npc.prevPosZ = lockedPosZ;
npc.motionX = 0;
npc.motionY = 0;
npc.motionZ = 0;
return;
}
// Server-side: use stored locked values
if (!positionLocked) {
return;
}
npc.setPosition(lockedPosX, lockedPosY, lockedPosZ);
npc.prevPosX = lockedPosX;
npc.prevPosY = lockedPosY;
npc.prevPosZ = lockedPosZ;
npc.motionX = 0;
npc.motionY = 0;
npc.motionZ = 0;
}
// ═══════════════════════════════════════════════════════════════════
@@ -2,6 +2,8 @@ package noppes.npcs;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.data.ParticlePacket;
import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket;
@@ -748,7 +750,7 @@ public class NoppesUtilServer {
public static void sendAbilityTypesInfo(EntityPlayerMP player) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
kamkeel.npcs.controllers.data.ability.AbilityController controller = kamkeel.npcs.controllers.data.ability.AbilityController.Instance;
AbilityController controller = AbilityController.Instance;
if (controller != null) {
int index = 0;
for (String typeId : controller.getTypes()) {
@@ -764,6 +766,9 @@ public class NoppesUtilServer {
if (controller != null) {
int index = 0;
for (String uuid : controller.getCustomAbilityIds()) {
Ability ability = controller.getCustomAbility(uuid);
if (ability == null || !ability.getAllowedBy().allowsNpc()) continue;
String name = controller.getCustomAbilityName(uuid);
if (name == null || name.isEmpty()) name = uuid;
map.put(name + "\t" + uuid, index++);
@@ -1,6 +1,7 @@
package noppes.npcs.ai;
import kamkeel.npcs.addon.DBCAddon;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
@@ -80,13 +81,14 @@ public class CombatHandler {
}
// Handle guard counter before interruption
if (npc.abilities.getCurrentAbility() instanceof kamkeel.npcs.controllers.data.ability.type.AbilityGuard) {
kamkeel.npcs.controllers.data.ability.type.AbilityGuard guard =
(kamkeel.npcs.controllers.data.ability.type.AbilityGuard) npc.abilities.getCurrentAbility();
if (guard.isGuarding() && e instanceof EntityLivingBase) {
guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount);
}
}
// 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);
@@ -93,7 +93,9 @@ public class EntityAIAmbushTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!this.theEntity.abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
}
private Vec3 findHidingSpot() {
@@ -118,7 +118,9 @@ public class EntityAIAttackTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F);
if (!this.npc.abilities.isRotationLocked()) {
this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F);
}
// Skip pathfinding updates if ability is controlling movement
if (!navOverride && !this.npc.abilities.isAbilityControllingMovement() && --this.field_75445_i <= 0) {
@@ -63,7 +63,7 @@ public class EntityAIDodgeShoot extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
if (this.entity.getAttackTarget() != null)
if (this.entity.getAttackTarget() != null && !this.entity.abilities.isRotationLocked())
this.entity.getLookHelper().setLookPositionWithEntity(this.entity.getAttackTarget(), 30.0F, 30.0F);
}
}
@@ -55,7 +55,9 @@ public class EntityAIFollow extends EntityAIBase {
if (updateTick < 10)
return;
updateTick = 0;
this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed());
if (!this.npc.abilities.isRotationLocked()) {
this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed());
}
double speed = 1 + distance / 150;
if (speed > 3)
@@ -26,7 +26,7 @@ public class EntityAILook extends EntityAIBase {
*/
@Override
public boolean shouldExecute() {
return !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive();
return !npc.abilities.isRotationLocked() && !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive();
}
/**
@@ -91,7 +91,9 @@ public class EntityAIOrbitTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!this.theEntity.abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
if (this.theEntity.getNavigator().noPath() && this.tick >= 0) {
if (this.theEntity.onGround && !this.theEntity.isInWater()) {
double d0 = this.targetDistance * (double) (MathHelper.cos(angle / 180.0F * (float) Math.PI));
@@ -100,7 +100,9 @@ public class EntityAIRangedAttack extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F);
if (!this.entityHost.abilities.isRotationLocked()) {
this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F);
}
double var1 = this.entityHost.getDistanceSq(this.attackTarget.posX, this.attackTarget.boundingBox.minY, this.attackTarget.posZ);
float field_82642_h = this.entityHost.stats.rangedRange * this.entityHost.stats.rangedRange;
@@ -68,7 +68,9 @@ public class EntityAIStalkTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!this.theEntity.abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
if (this.theEntity.getNavigator().noPath() || this.overRide) {
if (this.isLookingAway()) {
@@ -31,7 +31,7 @@ public class EntityAIWatchClosest extends EntityAIBase {
*/
@Override
public boolean shouldExecute() {
if (this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) {
if (this.theWatcher.abilities.isRotationLocked() || this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) {
return false;
} else {
if (this.theWatcher.getAttackTarget() != null) {
@@ -8,6 +8,7 @@ import net.minecraft.pathfinding.PathPoint;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import noppes.npcs.constants.AiMutex;
import noppes.npcs.entity.EntityNPCInterface;
public class EntityAIZigZagTarget extends EntityAIBase {
private EntityCreature theEntity;
@@ -82,6 +83,8 @@ public class EntityAIZigZagTarget extends EntityAIBase {
* Updates the task
*/
public void updateTask() {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
if (!(this.theEntity instanceof EntityNPCInterface) || !((EntityNPCInterface) this.theEntity).abilities.isRotationLocked()) {
this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F);
}
}
}
@@ -19,6 +19,8 @@ import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderLivingEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import noppes.npcs.client.gui.player.AuctionTooltipHandler;
import noppes.npcs.client.gui.customoverlay.OverlayCustom;
import noppes.npcs.client.gui.hud.ClientHudManager;
import noppes.npcs.client.gui.hud.CompassHudComponent;
@@ -75,6 +77,11 @@ public class ClientEventHandler {
}
}
@SubscribeEvent
public void onItemTooltip(ItemTooltipEvent event) {
AuctionTooltipHandler.onItemTooltip(event);
}
@SubscribeEvent
public void onMouse(MouseEvent event) {
if (Minecraft.getMinecraft().currentScreen != null)
@@ -76,6 +76,7 @@ import noppes.npcs.client.gui.GuiBorderBlock;
import noppes.npcs.client.gui.GuiMerchantAdd;
import noppes.npcs.client.gui.GuiNpcDimension;
import noppes.npcs.client.gui.GuiNpcMobSpawner;
import noppes.npcs.client.gui.GuiNpcMobSpawnerFullscreen;
import noppes.npcs.client.gui.GuiNpcMobSpawnerMounter;
import noppes.npcs.client.gui.GuiNpcPather;
import noppes.npcs.client.gui.GuiNpcRedstoneBlock;
@@ -191,6 +192,7 @@ import noppes.npcs.client.renderer.items.ItemShortLampRenderer;
import noppes.npcs.client.renderer.items.ItemTallLampRenderer;
import noppes.npcs.client.renderer.items.ItemToolRenderer;
import noppes.npcs.client.renderer.items.ScriptedBlockItemRenderer;
import noppes.npcs.client.ScriptClientConfig;
import noppes.npcs.config.ConfigClient;
import noppes.npcs.config.ConfigItem;
import noppes.npcs.config.ConfigMain;
@@ -333,7 +335,6 @@ public class ClientProxy extends CommonProxy {
ClientCloneController.Instance = new ClientCloneController();
ClientTagMapController.Instance = new ClientTagMapController();
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
// Telegraph rendering system
@@ -472,7 +473,7 @@ public class ClientProxy extends CommonProxy {
animNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png";
save = false;
}
return new GuiNPCManageAnimations(animNpc, save);
return new GuiNPCManageAnimations(animNpc, save, npc != null);
} else if (gui == EnumGuiType.ManageLinked)
return new GuiNPCManageLinked(npc);
@@ -507,8 +508,10 @@ public class ClientProxy extends CommonProxy {
} else {
abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld);
abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png";
abilityNpc.height = 1.8f;
abilityNpc.width = 0.6f;
}
return new GuiNpcManageAbilities(abilityNpc);
return new GuiNpcManageAbilities(abilityNpc, npc != null);
}
else if (gui == EnumGuiType.MainMenuGlobal)
@@ -602,7 +605,9 @@ public class ClientProxy extends CommonProxy {
return new GuiNpcRedstoneBlock(x, y, z);
else if (gui == EnumGuiType.Cloner)
return new GuiNpcMobSpawner(x, y, z);
return GuiNpcMobSpawner.isFullscreen
? new GuiNpcMobSpawnerFullscreen(x, y, z)
: new GuiNpcMobSpawner(x, y, z);
else if (gui == EnumGuiType.MobSpawnerMounter)
return new GuiNpcMobSpawnerMounter(x, y, z);
@@ -818,6 +823,31 @@ public class ClientProxy extends CommonProxy {
}
}
@Override
public boolean isScriptingEnabled() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isScriptingEnabled();
}
@Override
public boolean isRunLoadedScriptsFirst() {
return ScriptClientConfig.isRunLoadedScriptsFirst();
}
@Override
public boolean isGlobalPlayerScripts() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalPlayerScripts();
}
@Override
public boolean isGlobalForgeScripts() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalForgeScripts();
}
@Override
public boolean isGlobalNPCScripts() {
return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalNPCScripts();
}
public static class FontContainer {
public StringCache textFont = null;
public boolean useCustomFont = true;
@@ -0,0 +1,61 @@
package noppes.npcs.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.nbt.NBTTagCompound;
/**
* Client-side cache for script configuration synced from server.
* Prevents client from using local ConfigScript which may differ from server settings.
*
* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in
* ScriptConfigSync to avoid @SideOnly crashes on dedicated servers.
*/
@SideOnly(Side.CLIENT)
public class ScriptClientConfig {
// Cached values from server
private static boolean scriptingEnabled = true;
private static boolean runLoadedScriptsFirst = true;
private static boolean globalPlayerScripts = true;
private static boolean globalForgeScripts = true;
private static boolean globalNPCScripts = false;
/**
* Update cached config from server NBT data.
* Called when receiving login packet or script sync packets.
*/
public static void readFromNBT(NBTTagCompound compound) {
if (compound == null) return;
scriptingEnabled = compound.getBoolean("ScriptingEnabled");
runLoadedScriptsFirst = compound.getBoolean("RunLoadedScriptsFirst");
globalPlayerScripts = compound.getBoolean("GlobalPlayerScripts");
globalForgeScripts = compound.getBoolean("GlobalForgeScripts");
globalNPCScripts = compound.getBoolean("GlobalNPCScripts");
}
/**
* Reset to defaults (called on disconnect).
*/
public static void reset() {
scriptingEnabled = true;
runLoadedScriptsFirst = true;
globalPlayerScripts = true;
globalForgeScripts = true;
globalNPCScripts = false;
}
// Setters for individual packet updates
public static void setScriptingEnabled(boolean value) { scriptingEnabled = value; }
public static void setRunLoadedScriptsFirst(boolean value) { runLoadedScriptsFirst = value; }
public static void setGlobalPlayerScripts(boolean value) { globalPlayerScripts = value; }
public static void setGlobalForgeScripts(boolean value) { globalForgeScripts = value; }
public static void setGlobalNPCScripts(boolean value) { globalNPCScripts = value; }
// Getters
public static boolean isScriptingEnabled() { return scriptingEnabled; }
public static boolean isRunLoadedScriptsFirst() { return runLoadedScriptsFirst; }
public static boolean isGlobalPlayerScripts() { return globalPlayerScripts; }
public static boolean isGlobalForgeScripts() { return globalForgeScripts; }
public static boolean isGlobalNPCScripts() { return globalNPCScripts; }
}
@@ -41,6 +41,26 @@ public class ClientCloneController extends ServerCloneController {
return true;
}
@Override
public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) {
HashSet<UUID> tagUUIDs = new HashSet<>();
if (nbttagcompound.hasKey("TagUUIDs")) {
NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8);
for (int i = 0; i < nbtTagList.tagCount(); i++) {
tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i)));
}
}
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
if (!tagUUIDs.isEmpty()) {
tagMap.putClone(name, tagUUIDs);
} else {
tagMap.removeClone(name);
}
ClientTagMapController.Instance.saveTagMap(tagMap);
return true;
}
@Override
public boolean removeFromTagMap(String name, int tab) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab);
@@ -51,4 +71,43 @@ public class ClientCloneController extends ServerCloneController {
return false;
}
@Override
public boolean removeFromTagMap(String name, String folderName) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
if (tagMap.removeClone(name)) {
ClientTagMapController.Instance.saveTagMap(tagMap);
return true;
}
return false;
}
@Override
protected HashSet<UUID> getTagUUIDsFromTab(String cloneName, int tab) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab);
HashSet<UUID> uuids = tagMap.getUUIDs(cloneName);
return uuids != null ? new HashSet<>(uuids) : new HashSet<>();
}
@Override
protected HashSet<UUID> getTagUUIDsFromFolder(String cloneName, String folderName) {
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
HashSet<UUID> uuids = tagMap.getUUIDs(cloneName);
return uuids != null ? new HashSet<>(uuids) : new HashSet<>();
}
@Override
protected void setTagUUIDsForTab(String cloneName, int tab, HashSet<UUID> tagUUIDs) {
if (tagUUIDs == null || tagUUIDs.isEmpty()) return;
TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab);
tagMap.putClone(cloneName, tagUUIDs);
ClientTagMapController.Instance.saveTagMap(tagMap);
}
@Override
protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet<UUID> tagUUIDs) {
if (tagUUIDs == null || tagUUIDs.isEmpty()) return;
TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName);
tagMap.putClone(cloneName, tagUUIDs);
ClientTagMapController.Instance.saveTagMap(tagMap);
}
}
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket;
import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket;
import kamkeel.npcs.network.packets.request.clone.CloneListPacket;
import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket;
import kamkeel.npcs.network.packets.request.clone.CloneTagListPacket;
@@ -26,6 +27,8 @@ import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IClonerGui;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.controllers.data.TagMap;
@@ -38,52 +41,84 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData, ICustomScrollListener, IClonerGui {
// ==================== STATIC STATE (persists across GUI opens, shared with fullscreen) ====================
public static boolean isFullscreen = false;
public static int activeTab = 1;
public static String activeFolder = null;
public static int showingClones = 0; // 0=Clones, 1=Entities, 2=Server, 3=Filters
public static String search = "";
public static String tagSearch = "";
public static HashMap<UUID, Tag> tags = new HashMap<>();
public static HashMap<String, UUID> tagNames = new HashMap<>();
public static HashSet<String> tagFilters = new HashSet<>();
public static byte displayTags = 0;
// 0 - Any, 1 - All, 2 - Not Any, 3 - Not All
public static byte filterCondition = 0;
public static byte ascending = 0;
// 0 - By Name, 1 - By Date
public static byte sortType = 0;
public TagMap tagMap;
// Scroll position preservation (shared with fullscreen)
public static int savedContentScrollY = 0;
public static int savedNavScrollY = 0;
// ==================== INSTANCE STATE ====================
public TagMap tagMap;
private final GuiCustomScrollCloner scroll = new GuiCustomScrollCloner(this, 0);
private final GuiCustomScroll filterScroll = new GuiCustomScroll(this, 1);
private int posX, posY, posZ;
public int posX, posY, posZ;
private List<String> list;
private List<String> rawList;
private List<String> tagList;
private static int showingClones = 0;
private static String search = "";
private static String tagSearch = "";
private int activeTab = 1;
// ==================== CONSTRUCTOR ====================
public GuiNpcMobSpawner(int i, int j, int k) {
super();
xSize = 354;
posX = i;
posY = j;
posZ = k;
this.closeOnEsc = true;
closeOnEsc = true;
xSize = 354;
setBackground("menubg.png");
PacketClient.sendClient(new CloneAllTagsPacket());
if (showingClones == 2) {
PacketClient.sendClient(new CloneFolderListPacket());
}
// Minimized view doesn't support folders — ensure we're on a tab
if (activeFolder != null) {
if (activeTab < 1 || activeTab > 15) {
activeTab = 1;
}
activeFolder = null;
}
}
// ==================== IClonerGui ====================
@Override
public int getShowingClones() {
return showingClones;
}
@Override
public HashMap<UUID, Tag> getTags() {
return tags;
}
@Override
public TagMap getTagMap() {
return tagMap;
}
// ==================== INIT GUI ====================
public void initGui() {
// Save scroll position before clear
savedContentScrollY = scroll.scrollY;
super.initGui();
guiTop += 10;
guiLeft += 30;
@@ -92,6 +127,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
scroll.setSize(293, 188);
scroll.guiLeft = guiLeft + 4;
scroll.guiTop = guiTop + 26;
filterScroll.clear();
filterScroll.setSize(140, 166);
filterScroll.guiLeft = guiLeft + 4;
@@ -99,112 +135,133 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
filterScroll.multipleSelection = true;
filterScroll.setSelectedList(tagFilters);
GuiMenuTopButton button;
addTopButton(button = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones"));
button.active = showingClones == 0;
addTopButton(button = new GuiMenuTopButton(5, button, "gui.server"));
button.active = showingClones == 2;
addTopButton(button = new GuiMenuTopButton(4, button, "spawner.entities"));
button.active = showingClones == 1;
addTopButton(button = new GuiMenuTopButton(16, guiLeft + (xSize - 67), guiTop - 17, "gui.filters"));
button.active = showingClones == 3;
addTopButton(button = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"));
// Top buttons — build right-to-left to avoid overlap
GuiMenuTopButton closeBtn = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X");
addTopButton(closeBtn);
// Position "+" dynamically to the left of "X"
int plusX = closeBtn.xPosition - (fontRendererObj.getStringWidth("+") + 12) - 2;
GuiMenuTopButton fullscreenBtn = new GuiMenuTopButton(61, plusX, guiTop - 17, "+");
addTopButton(fullscreenBtn);
// Position "Filters" dynamically to the left of "+"
int filterBtnW = fontRendererObj.getStringWidth(StatCollector.translateToLocal("gui.filters")) + 12;
int filterX = fullscreenBtn.xPosition - filterBtnW - 2;
GuiMenuTopButton filterBtn = new GuiMenuTopButton(16, filterX, guiTop - 17, "gui.filters");
filterBtn.active = showingClones == 3;
addTopButton(filterBtn);
// Mode buttons from left
GuiMenuTopButton btn;
addTopButton(btn = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones"));
btn.active = showingClones == 0;
addTopButton(btn = new GuiMenuTopButton(5, btn, "gui.server"));
btn.active = showingClones == 2;
addTopButton(btn = new GuiMenuTopButton(4, btn, "spawner.entities"));
btn.active = showingClones == 1;
if (showingClones < 3) {
addScroll(scroll);
addTextField(new GuiNpcTextField(1, this, fontRendererObj, guiLeft + 4, guiTop + 4, 293, 20, search));
addButton(new GuiNpcButton(1, guiLeft + 298, guiTop + 6, 52, 20, "item.monsterPlacer.name"));
addButton(new GuiNpcButton(2, guiLeft + 298, guiTop + 140, 52, 20, "spawner.mobspawner"));
if (showingClones == 0 || showingClones == 2) {
addSideButton(new GuiMenuSideButton(21, guiLeft - 70, this.guiTop + 2, 70, 22, "1"));
addSideButton(new GuiMenuSideButton(22, guiLeft - 70, this.guiTop + 23, 70, 22, "2"));
addSideButton(new GuiMenuSideButton(23, guiLeft - 70, this.guiTop + 44, 70, 22, "3"));
addSideButton(new GuiMenuSideButton(24, guiLeft - 70, this.guiTop + 65, 70, 22, "4"));
addSideButton(new GuiMenuSideButton(25, guiLeft - 70, this.guiTop + 86, 70, 22, "5"));
addSideButton(new GuiMenuSideButton(26, guiLeft - 70, this.guiTop + 107, 35, 22, "6"));
addSideButton(new GuiMenuSideButton(27, guiLeft - 35, this.guiTop + 107, 35, 22, "7"));
addSideButton(new GuiMenuSideButton(28, guiLeft - 70, this.guiTop + 128, 35, 22, "8"));
addSideButton(new GuiMenuSideButton(29, guiLeft - 35, this.guiTop + 128, 35, 22, "9"));
addSideButton(new GuiMenuSideButton(30, guiLeft - 70, this.guiTop + 149, 35, 22, "10"));
addSideButton(new GuiMenuSideButton(31, guiLeft - 35, this.guiTop + 149, 35, 22, "11"));
addSideButton(new GuiMenuSideButton(32, guiLeft - 70, this.guiTop + 170, 35, 22, "12"));
addSideButton(new GuiMenuSideButton(33, guiLeft - 35, this.guiTop + 170, 35, 22, "13"));
addSideButton(new GuiMenuSideButton(34, guiLeft - 70, this.guiTop + 191, 35, 22, "14"));
addSideButton(new GuiMenuSideButton(35, guiLeft - 35, this.guiTop + 191, 35, 22, "15"));
addButton(new GuiNpcButton(6, guiLeft + 298, guiTop + 190, 52, 20, "gui.remove"));
getSideButton(20 + activeTab).active = true;
initTabSideButtons();
showClones();
// Restore scroll position
scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY));
} else {
showEntities();
scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY));
}
} else {
// Show Filters
addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), guiLeft + 7, guiTop + 7));
addScroll(filterScroll);
addTextField(new GuiNpcTextField(2, this, fontRendererObj, guiLeft + 4, guiTop + 190, 140, 20, tagSearch));
addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), guiLeft + 150, guiTop + 27));
addButton(new GuiNpcButton(12, guiLeft + 215, guiTop + 20, new String[]{"display.show", "display.all", "display.hide"}, displayTags));
addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), guiLeft + 150, guiTop + 50));
addButton(new GuiNpcButton(13, guiLeft + 215, guiTop + 43, new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition));
addButton(new GuiNpcButton(11, guiLeft + 150, guiTop + 66, 130, 20, "gui.deselectAll"));
addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), guiLeft + 150, guiTop + 112));
addButton(new GuiNpcButton(14, guiLeft + 215, guiTop + 105, new String[]{"cloner.ascending", "cloner.descending"}, ascending));
addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), guiLeft + 150, guiTop + 135));
addButton(new GuiNpcButton(15, guiLeft + 215, guiTop + 128, new String[]{"cloner.name", "cloner.date"}, sortType));
getButton(12).width = 65;
getButton(12).height = 20;
getButton(13).width = 65;
getButton(13).height = 20;
getButton(14).width = 65;
getButton(14).height = 20;
getButton(15).width = 65;
getButton(15).height = 20;
showFilters();
showFiltersPage();
}
}
public int getShowingClones() {
return showingClones;
private void initTabSideButtons() {
// Tabs 1-5: full width (70px)
addSideButton(new GuiMenuSideButton(21, guiLeft - 70, guiTop + 2, 70, 22, "1"));
addSideButton(new GuiMenuSideButton(22, guiLeft - 70, guiTop + 23, 70, 22, "2"));
addSideButton(new GuiMenuSideButton(23, guiLeft - 70, guiTop + 44, 70, 22, "3"));
addSideButton(new GuiMenuSideButton(24, guiLeft - 70, guiTop + 65, 70, 22, "4"));
addSideButton(new GuiMenuSideButton(25, guiLeft - 70, guiTop + 86, 70, 22, "5"));
// Tabs 6-15: half width (35px), 2-column grid
addSideButton(new GuiMenuSideButton(26, guiLeft - 70, guiTop + 107, 35, 22, "6"));
addSideButton(new GuiMenuSideButton(27, guiLeft - 35, guiTop + 107, 35, 22, "7"));
addSideButton(new GuiMenuSideButton(28, guiLeft - 70, guiTop + 128, 35, 22, "8"));
addSideButton(new GuiMenuSideButton(29, guiLeft - 35, guiTop + 128, 35, 22, "9"));
addSideButton(new GuiMenuSideButton(30, guiLeft - 70, guiTop + 149, 35, 22, "10"));
addSideButton(new GuiMenuSideButton(31, guiLeft - 35, guiTop + 149, 35, 22, "11"));
addSideButton(new GuiMenuSideButton(32, guiLeft - 70, guiTop + 170, 35, 22, "12"));
addSideButton(new GuiMenuSideButton(33, guiLeft - 35, guiTop + 170, 35, 22, "13"));
addSideButton(new GuiMenuSideButton(34, guiLeft - 70, guiTop + 191, 35, 22, "14"));
addSideButton(new GuiMenuSideButton(35, guiLeft - 35, guiTop + 191, 35, 22, "15"));
if (activeTab >= 1 && activeTab <= 15) {
GuiMenuSideButton active = getSideButton(20 + activeTab);
if (active != null) active.active = true;
}
}
public void showFilters() {
// ==================== FILTERS PAGE ====================
private void showFiltersPage() {
int baseY = guiTop;
addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"),
guiLeft + 7, baseY + 7));
filterScroll.clear();
filterScroll.setSize(140, 166);
filterScroll.guiLeft = guiLeft + 4;
filterScroll.guiTop = baseY + 19;
filterScroll.multipleSelection = true;
filterScroll.setSelectedList(tagFilters);
addScroll(filterScroll);
addTextField(new GuiNpcTextField(2, this, fontRendererObj,
guiLeft + 4, baseY + 190, 140, 20, tagSearch));
addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"),
guiLeft + 150, baseY + 27));
addButton(new GuiNpcButton(12, guiLeft + 215, baseY + 20,
new String[]{"display.show", "display.all", "display.hide"}, displayTags));
addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"),
guiLeft + 150, baseY + 50));
addButton(new GuiNpcButton(13, guiLeft + 215, baseY + 43,
new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition));
addButton(new GuiNpcButton(11, guiLeft + 150, baseY + 66, 130, 20, "gui.deselectAll"));
addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"),
guiLeft + 150, baseY + 112));
addButton(new GuiNpcButton(14, guiLeft + 215, baseY + 105,
new String[]{"cloner.ascending", "cloner.descending"}, ascending));
addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"),
guiLeft + 150, baseY + 135));
addButton(new GuiNpcButton(15, guiLeft + 215, baseY + 128,
new String[]{"cloner.name", "cloner.date"}, sortType));
getButton(12).width = 65;
getButton(12).height = 20;
getButton(13).width = 65;
getButton(13).height = 20;
getButton(14).width = 65;
getButton(14).height = 20;
getButton(15).width = 65;
getButton(15).height = 20;
filterScroll.setList(getTagList());
}
private void showEntities() {
Map<?, ?> data = EntityList.stringToClassMapping;
ArrayList<String> list = new ArrayList<String>();
for (Object name : data.keySet()) {
Class<?> c = (Class<?>) data.get(name);
try {
if (EntityLiving.class.isAssignableFrom(c) && c.getConstructor(new Class[]{World.class}) != null && !Modifier.isAbstract(c.getModifiers()))
list.add(name.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
}
}
this.list = list;
this.rawList = new ArrayList<String>(this.list);
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
// ==================== CLONE / ENTITY DISPLAY ====================
private void showClones() {
if (showingClones == 2) {
PacketClient.sendClient(new CloneTagListPacket(activeTab));
@@ -219,16 +276,41 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
this.tagMap = ClientTagMapController.Instance.getTagMap(activeTab);
populateRawListWithTags();
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
private void showEntities() {
Map<?, ?> data = EntityList.stringToClassMapping;
ArrayList<String> list = new ArrayList<String>();
for (Object name : data.keySet()) {
Class<?> c = (Class<?>) data.get(name);
try {
if (EntityLiving.class.isAssignableFrom(c)
&& c.getConstructor(new Class[]{World.class}) != null
&& !Modifier.isAbstract(c.getModifiers()))
list.add(name.toString());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
}
}
this.list = list;
this.rawList = new ArrayList<String>(this.list);
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
private void populateRawListWithTags() {
this.rawList = new ArrayList<>(this.list);
if (this.tagMap != null) {
if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) {
if (displayTags == 0 || displayTags == 1) {
for (int i = 0; i < this.list.size(); i++) {
StringBuilder npcName = new StringBuilder(list.get(i));
if (this.tagMap.hasClone(list.get(i))) {
for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) {
Tag tag = tags.get(tagUUID);
if (tag != null) {
if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) {
if (displayTags == 1 || !tag.getIsHidden()) {
npcName.append(" [" + tag.name + "]");
}
}
@@ -238,27 +320,26 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
}
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(1) != null) {
if (search.equals(getTextField(1).getText()))
return;
search = getTextField(1).getText().toLowerCase();
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
if (getTextField(2) != null) {
if (tagSearch.equals(getTextField(2).getText()))
return;
tagSearch = getTextField(2).getText().toLowerCase();
filterScroll.setList(getTagList());
}
private NBTTagCompound getCompound() {
String sel = scroll.getSelected();
if (sel == null)
return null;
if (showingClones == 0) {
return ClientCloneController.Instance.getCloneData(player, sel, activeTab);
} else {
Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld);
if (entity == null)
return null;
NBTTagCompound compound = new NBTTagCompound();
entity.writeToNBTOptional(compound);
return compound;
}
}
// ==================== SEARCH / FILTER ====================
private List<String> getSearchList() {
if (this.list == null) {
this.list = new ArrayList<String>();
@@ -269,10 +350,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
// No Filters - or - Entities
if (tagFilters.size() == 0 || showingClones == 1) {
// No Search
if (search.isEmpty())
return new ArrayList<String>(this.list);
// Yes Search
else {
List<String> list = new ArrayList<String>();
for (int i = 0; i < this.list.size(); i++) {
@@ -284,10 +363,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
////////////////////////
//// WITH FILTERS
// No Search
// With Filters
if (search.isEmpty()) {
List<String> list = new ArrayList<String>();
for (String name : this.list) {
@@ -300,7 +376,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
return list;
}
// Yes Search
List<String> list = new ArrayList<String>();
for (int i = 0; i < this.list.size(); i++) {
if (this.rawList.get(i).toLowerCase().contains(search)) {
@@ -311,7 +386,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
}
}
return list;
}
@@ -346,7 +420,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
}
}
return conditionMet;
}
@@ -354,10 +427,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
if (this.tagList == null) {
this.tagList = new ArrayList<String>();
}
// No Search // No Filters - or - Entities
if (tagSearch.isEmpty())
return new ArrayList<String>(tagNames.keySet());
// Yes Search // No Filters - or - Entities
List<String> list = new ArrayList<String>();
for (String name : this.tagList) {
@@ -367,125 +438,162 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
return list;
}
private NBTTagCompound getCompound() {
String sel = scroll.getSelected();
if (sel == null)
return null;
if (showingClones == 0) {
return ClientCloneController.Instance.getCloneData(player, sel, activeTab);
} else {
Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld);
if (entity == null)
return null;
NBTTagCompound compound = new NBTTagCompound();
entity.writeToNBTOptional(compound);
return compound;
}
// ==================== MOUSE / KEYBOARD EVENTS ====================
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
}
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
GuiNpcTextField searchField = getTextField(1);
if (searchField != null) {
String newText = searchField.getText().toLowerCase();
if (!search.equals(newText)) {
search = newText;
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
}
GuiNpcTextField tagSearchField = getTextField(2);
if (tagSearchField != null) {
String newText = tagSearchField.getText().toLowerCase();
if (!tagSearch.equals(newText)) {
tagSearch = newText;
filterScroll.setList(getTagList());
}
}
}
// ==================== BUTTON ACTIONS ====================
@Override
protected void actionPerformed(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0) {
close();
}
if (id == 1) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null)
return;
SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null)
return;
SpawnMobPacket.Client(posX, posY, posZ, compound);
close();
}
}
if (id == 2) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null)
return;
MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null)
return;
MobSpawnerPacket.Client(posX, posY, posZ, compound);
close();
}
// Tab side buttons (IDs 21-35)
if (id >= 21 && id <= 35) {
activeTab = id - 20;
activeFolder = null;
initGui();
return;
}
// Mode buttons
if (id == 3) {
savedContentScrollY = 0;
showingClones = 0;
initGui();
}
if (id == 4) {
savedContentScrollY = 0;
showingClones = 1;
initGui();
}
if (id == 5) {
savedContentScrollY = 0;
showingClones = 2;
PacketClient.sendClient(new CloneFolderListPacket());
initGui();
}
if (id == 16) {
savedContentScrollY = 0;
showingClones = 3;
initGui();
}
if (id == 17) {
close();
}
// Open fullscreen GUI
if (id == 61) {
isFullscreen = true;
Minecraft.getMinecraft().displayGuiScreen(
new GuiNpcMobSpawnerFullscreen(posX, posY, posZ));
}
// Spawn
if (id == 1) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null) return;
SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null) return;
SpawnMobPacket.Client(posX, posY, posZ, compound);
close();
}
}
// Mob Spawner
if (id == 2) {
if (showingClones == 2) {
String sel = scroll.getSelected();
if (sel == null) return;
MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab);
close();
} else {
NBTTagCompound compound = getCompound();
if (compound == null) return;
MobSpawnerPacket.Client(posX, posY, posZ, compound);
close();
}
}
// Remove
if (id == 6) {
if (scroll.getSelected() != null) {
int prevSelected = scroll.selected;
if (showingClones == 2) {
PacketClient.sendClient(new CloneRemovePacket(activeTab, scroll.getSelected()));
return;
}
ClientCloneController.Instance.removeClone(scroll.getSelected(), activeTab);
scroll.selected = -1;
initGui();
if (scroll.list != null && !scroll.list.isEmpty()) {
scroll.selected = Math.min(prevSelected, scroll.list.size() - 1);
} else {
scroll.selected = -1;
}
}
}
// Filter controls
if (id == 11) {
tagFilters = new HashSet<>();
filterScroll.setSelectedList(tagFilters);
initGui();
}
if (id == 12) {
GuiNpcButton button = (GuiNpcButton) guibutton;
displayTags = (byte) button.getValue();
displayTags = (byte) ((GuiNpcButton) guibutton).getValue();
}
if (id == 13) {
GuiNpcButton button = (GuiNpcButton) guibutton;
filterCondition = (byte) button.getValue();
filterCondition = (byte) ((GuiNpcButton) guibutton).getValue();
}
if (id == 14) {
GuiNpcButton button = (GuiNpcButton) guibutton;
ascending = (byte) button.getValue();
ascending = (byte) ((GuiNpcButton) guibutton).getValue();
}
if (id == 15) {
GuiNpcButton button = (GuiNpcButton) guibutton;
sortType = (byte) button.getValue();
}
if (id > 20) {
activeTab = id - 20;
initGui();
sortType = (byte) ((GuiNpcButton) guibutton).getValue();
}
}
// ==================== DATA FROM SERVER ====================
@Override
public void save() {
}
@Override
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("CloneTags")) {
if (compound.hasKey("CloneFolders")) {
// Minimized doesn't use folders, but still handle the packet
initGui();
} else if (compound.hasKey("CloneTags")) {
this.tagMap = new TagMap(activeTab);
NBTTagCompound cloneTags = compound.getCompoundTag("CloneTags");
this.tagMap.readNBT(cloneTags);
@@ -521,29 +629,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData {
}
this.list = list;
this.rawList = new ArrayList<String>(this.list);
if (this.tagMap != null) {
if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) {
for (int i = 0; i < this.list.size(); i++) {
StringBuilder npcName = new StringBuilder(list.get(i));
if (this.tagMap.hasClone(list.get(i))) {
for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) {
Tag tag = tags.get(tagUUID);
if (tag != null) {
if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) {
npcName.append(" [" + tag.name + "]");
}
}
}
}
this.rawList.set(i, npcName.toString());
}
}
}
populateRawListWithTags();
scroll.setList(getSearchList(), ascending == 0, sortType == 0);
}
}
}
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket;
import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket;
import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket;
import kamkeel.npcs.network.packets.request.clone.CloneSavePacket;
import net.minecraft.client.Minecraft;
@@ -22,12 +23,14 @@ import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.CloneFolder;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ISubGuiListener {
@@ -35,9 +38,16 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
private Entity toClone;
private NBTTagCompound compound;
private static boolean serverSide = false;
private static int saveMode = 0; // 0=Tab, 1=Folder
private static int tab = 1;
private static String folder = null;
public boolean isNPC = false;
// Client-side folder names
private ArrayList<String> clientFolderNames = new ArrayList<>();
// Server-side folder names (populated via CloneFolderListPacket)
private static ArrayList<String> serverFolderNames = new ArrayList<>();
// Selected Tags to Add
public static NBTTagList tagsCompound;
public static HashSet<String> addTags;
@@ -68,6 +78,37 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
if (isNPC) {
PacketClient.sendClient(new CloneAllTagsShortPacket());
}
buildClientFolderNames();
// Request server folders if in server mode
if (serverSide) {
PacketClient.sendClient(new CloneFolderListPacket());
}
// Validate saved folder selection
validateFolder();
}
private void buildClientFolderNames() {
clientFolderNames.clear();
if (ClientCloneController.Instance != null) {
for (CloneFolder f : ClientCloneController.Instance.getFolderList()) {
clientFolderNames.add(f.name);
}
}
}
private List<String> getActiveFolderList() {
return serverSide ? serverFolderNames : clientFolderNames;
}
private void validateFolder() {
if (saveMode == 1 && folder != null) {
if (!getActiveFolderList().contains(folder)) {
folder = null;
}
}
}
@Override
@@ -77,61 +118,138 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
addLabel(new GuiNpcLabel(0, "Save as", guiLeft + 4, guiTop + 6));
addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 4, guiTop + 18, 200, 20, name));
// Tab/Folder toggle
addButton(new GuiNpcButton(6, guiLeft + 4, guiTop + 45, 50, 20,
new String[]{"Tab", "Folder"}, saveMode));
addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50));
addButton(new GuiButtonBiDirectional(2, guiLeft + 40, guiTop + 45, 60, 20, new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}, tab - 1));
// Destination selector based on saveMode
if (saveMode == 0) {
// Tab selector: 1-15
String[] tabLabels = new String[15];
for (int i = 0; i < 15; i++) tabLabels[i] = String.valueOf(i + 1);
int selectedTab = (tab >= 1 && tab <= 15) ? tab - 1 : 0;
addButton(new GuiButtonBiDirectional(2, guiLeft + 56, guiTop + 45, 90, 20, tabLabels, selectedTab));
} else {
// Folder selector button — opens SubGuiFolderSelect
String btnText = folder != null ? folder : "Select a Folder";
addButton(new GuiNpcButton(2, guiLeft + 56, guiTop + 45, 148, 20, btnText));
}
addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0));
addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50));
addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save"));
// Save / Cancel
GuiNpcButton saveBtn = new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save");
if (saveMode == 1 && folder == null) {
saveBtn.enabled = false;
}
addButton(saveBtn);
addButton(new GuiNpcButton(1, guiLeft + 86, guiTop + 70, 80, 20, "gui.cancel"));
// Client / Server toggle
addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0));
if (isNPC) {
addButton(new GuiNpcButton(4, guiLeft + 4, guiTop + 120, 99, 20, "cloner.wandTags"));
addButton(new GuiNpcButton(5, guiLeft + 106, guiTop + 120, 99, 20, "cloner.npcTags"));
if (addTags.size() > 0) {
addLabel(new GuiNpcLabel(6, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160));
addLabel(new GuiNpcLabel(8, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160));
}
}
}
private void updateDestinationFromSelector() {
if (saveMode == 0) {
GuiNpcButton selector = getButton(2);
if (selector == null) return;
tab = selector.getValue() + 1;
folder = null;
}
// In folder mode, folder is already set via SubGuiFolderSelect
}
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
// Save
if (id == 0) {
updateDestinationFromSelector();
String name = getTextField(0).getText();
if (name.isEmpty())
return;
int tab = ((GuiNpcButton) guibutton).getValue() + 1;
if (saveMode == 1 && folder == null)
return;
if (!serverSide) {
if (ClientCloneController.Instance.getCloneData(null, name, tab) != null)
boolean exists;
if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) {
exists = ClientCloneController.Instance.getCloneData(null, name, folder) != null;
} else {
exists = ClientCloneController.Instance.getCloneData(null, name, tab) != null;
}
if (exists)
displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1));
else
confirmClicked(true, 0);
} else
PacketClient.sendClient(new ClonePreSavePacket(name, tab));
} else {
if (saveMode == 1 && folder != null) {
PacketClient.sendClient(new ClonePreSavePacket(name, folder));
} else {
PacketClient.sendClient(new ClonePreSavePacket(name, tab));
}
}
}
// Cancel
if (id == 1) {
close();
}
// Destination selector
if (id == 2) {
tab = ((GuiNpcButton) guibutton).getValue() + 1;
if (saveMode == 0) {
// Tab mode — update from BiDirectional
updateDestinationFromSelector();
} else {
// Folder mode — open folder selector Sub GUI
List<String> folders = getActiveFolderList();
setSubGui(new SubGuiFolderSelect(folders, folder));
}
}
// Client / Server toggle
if (id == 3) {
boolean wasServerSide = serverSide;
serverSide = ((GuiNpcButton) guibutton).getValue() == 1;
if (serverSide && !wasServerSide) {
// Switching to server mode — request fresh folder list
PacketClient.sendClient(new CloneFolderListPacket());
}
// Validate folder exists on the new side
validateFolder();
initGui();
}
// Wand Tags
if (id == 4) {
if (isNPC) {
this.setSubGui(new SubGuiClonerQuickTags(this));
}
}
// NPC Tags
if (id == 5) {
if (isNPC) {
this.setSubGui(new SubGuiClonerNPCTags((EntityNPCInterface) toClone, this));
}
}
}
// Tab/Folder mode toggle
if (id == 6) {
saveMode = ((GuiNpcButton) guibutton).getValue();
initGui();
}
}
@Override
public void confirmClicked(boolean confirm, int id) {
@@ -145,13 +263,21 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
if (isNPC) {
compound.setTag("TagUUIDs", tagsCompound);
}
ClientCloneController.Instance.addClone(compound, name, tab, extraTags);
if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) {
ClientCloneController.Instance.addClone(compound, name, folder, extraTags);
} else {
ClientCloneController.Instance.addClone(compound, name, tab, extraTags);
}
} else {
NBTTagCompound compounder = new NBTTagCompound();
if (isNPC) {
compounder.setTag("TagUUIDs", tagsCompound);
}
PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder));
if (saveMode == 1 && folder != null) {
PacketClient.sendClient(new CloneSavePacket(name, folder, extraTags, compounder));
} else {
PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder));
}
}
close();
@@ -159,7 +285,6 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
displayGuiScreen(this);
}
@Override
public void save() {
}
@@ -171,6 +296,17 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1));
else
confirmClicked(true, 0);
} else if (compound.hasKey("CloneFolders")) {
// Server folder list arrived
NBTTagList folderList = compound.getTagList("CloneFolders", 10);
serverFolderNames.clear();
for (int i = 0; i < folderList.tagCount(); i++) {
CloneFolder f = new CloneFolder();
f.readNBT(folderList.getCompoundTagAt(i));
serverFolderNames.add(f.name);
}
validateFolder();
initGui();
} else if (compound.hasKey("ShortTags")) {
NBTTagList validTags = compound.getTagList("ShortTags", 10);
tagMap.clear();
@@ -193,6 +329,12 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiFolderSelect) {
SubGuiFolderSelect sel = (SubGuiFolderSelect) subgui;
if (sel.selectedFolder != null) {
folder = sel.selectedFolder;
}
}
initGui();
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,67 @@
package noppes.npcs.client.gui;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.CloneFolder;
public class SubGuiCloneFolderName extends SubGuiInterface {
private String originalName;
public boolean cancelled = true;
private String folderName = "";
public SubGuiCloneFolderName(String existingName) {
this.originalName = existingName;
this.folderName = existingName;
xSize = 200;
ySize = 80;
this.closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
String title = isRename() ? "Rename Folder" : "New Folder";
addLabel(new GuiNpcLabel(0, title, guiLeft + 5, guiTop + 5));
addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 5, guiTop + 20, 190, 20, folderName));
addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 50, 90, 20, "gui.done"));
addButton(new GuiNpcButton(1, guiLeft + 100, guiTop + 50, 90, 20, "gui.cancel"));
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
// Done
folderName = getTextField(0).getText().trim();
if (CloneFolder.isValidName(folderName)) {
cancelled = false;
close();
}
}
if (guibutton.id == 1) {
// Cancel
cancelled = true;
close();
}
}
public boolean isRename() {
return originalName != null && !originalName.isEmpty();
}
public String getFolderName() {
return folderName;
}
public String getOriginalName() {
return originalName;
}
@Override
public void save() {
}
}
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more