Merge branch 'dev' into syntax-highlighter-unified

This commit is contained in:
Kam committed 2026-03-01 03:34:56 -05:00
commit aa53d0588c
157 files changed
+3922 -1792

No files matched your search

@@ -20,12 +20,12 @@ import org.lwjgl.opengl.GL12;
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderEnergyAbility extends Render {
public abstract class RenderEnergy extends Render {
protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
protected static final int HIDE_INITIAL_ACTIVE_TICKS = 1;
public RenderEnergyAbility() {
public RenderEnergy() {
this.shadowSize = 0.0f;
}
@@ -2,20 +2,20 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityEnergyBarrier;
/**
* Intermediate renderer base for energy barrier entities (Dome, Panel).
* Provides shared hit flash alpha computation.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderEnergyBarrier extends RenderEnergyAbility {
public abstract class RenderEnergyBarrier extends RenderEnergy {
/**
* Compute the alpha boost from a hit flash effect.
* Flash value decays from 4 to 0, producing alpha from 0.3 to 0.
*/
protected float computeFlashAlpha(EntityAbilityBarrier barrier) {
protected float computeFlashAlpha(EntityEnergyBarrier barrier) {
byte flash = barrier.getHitFlash();
if (flash <= 0) return 0.0f;
return flash / 4.0f * 0.3f;
@@ -23,7 +23,7 @@ import java.util.List;
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityBeam extends RenderEnergyAbility {
public class RenderEnergyBeam extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
@@ -15,7 +15,7 @@ import org.lwjgl.opengl.GL11;
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityDisc extends RenderEnergyAbility {
public class RenderEnergyDisc extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
@@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityEnergyDome;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
@@ -10,17 +10,16 @@ import org.lwjgl.opengl.GL11;
/**
* Renders the Dome entity as a translucent sphere.
* Inner layer solid, outer layer translucent glow.
* Optional skybox texture rendered on the interior surface.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityDome extends RenderEnergyBarrier {
public class RenderEnergyDome extends RenderEnergyBarrier {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityDome dome = (EntityAbilityDome) entity;
EntityEnergyDome dome = (EntityEnergyDome) entity;
float radius = dome.getDomeRadius();
float healthPercent = dome.getHealthPercent();
@@ -44,14 +43,9 @@ public class RenderAbilityDome extends RenderEnergyBarrier {
float outerScale = 1.0f + dome.getOuterColorWidth() * 0.1f;
float outerAlpha = dome.getOuterColorAlpha() * healthPercent;
GL11.glDepthMask(false);
renderSphere(dome.getOuterColor(), outerAlpha + flashAlpha, radius * outerScale, 8);
renderSphere(dome.getOuterColor(), outerAlpha + (dome.getOuterColorAlpha() > 0 ? flashAlpha : 0), radius * outerScale, 8);
}
// TODO: Skybox Feature
// if (dome.isSkyboxEnabled() && !dome.getSkyboxTexture().isEmpty()) {
// renderSkyboxSphere(dome.getSkyboxTexture(), radius, radius * 0.94f, 32, x, y, z);
// }
GL11.glDepthMask(true);
// Render inner dome (depth write enabled so inner sphere properly occludes)
renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8);
@@ -114,5 +108,4 @@ public class RenderAbilityDome extends RenderEnergyBarrier {
tess.draw();
}
// TODO: Skybox Feature — renderSkyboxSphere method removed
}
@@ -12,7 +12,7 @@ import org.lwjgl.opengl.GL11;
* Draws expanding cubic shells with a short fade-out.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyExplosion extends RenderEnergyAbility {
public class RenderEnergyExplosion extends RenderEnergy {
private static final float MAX_OUTER_ALPHA = 0.85f;
private static final float MAX_INNER_ALPHA = 1.0f;
@@ -17,7 +17,7 @@ import java.util.Map;
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityLaser extends RenderEnergyAbility {
public class RenderEnergyLaser extends RenderEnergy {
private final Map<Integer, AttachedLightningRenderer.LightningState> tipLightningStates = new HashMap<>();
@@ -13,7 +13,7 @@ import org.lwjgl.opengl.GL11;
* Minecraft-style blocky appearance using Tessellator.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityOrb extends RenderEnergyAbility {
public class RenderEnergyOrb extends RenderEnergy {
private static final int LIGHTNING_FADE_TICKS = 6;
@@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityEnergyPanel;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
@@ -13,14 +13,14 @@ import org.lwjgl.opengl.GL11;
* Voxel-blocky style with inner/outer layers.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityPanel extends RenderEnergyBarrier {
public class RenderEnergyPanel extends RenderEnergyBarrier {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityPanel panel = (EntityAbilityPanel) entity;
EntityEnergyPanel panel = (EntityEnergyPanel) entity;
float width = panel.getPanelData().panelWidth;
float height = panel.getPanelData().panelHeight;
@@ -67,7 +67,7 @@ public class RenderAbilityPanel extends RenderEnergyBarrier {
float outerScale = 1.0f + panel.getOuterColorWidth() * 0.15f;
float outerAlpha = panel.getOuterColorAlpha() * healthPercent;
GL11.glDepthMask(false);
renderPanel(panel.getOuterColor(), outerAlpha + flashAlpha,
renderPanel(panel.getOuterColor(), outerAlpha + (panel.getOuterColorAlpha() > 0 ? flashAlpha : 0),
width * 0.5f * outerScale, height * 0.5f * outerScale, panelThickness * 1.5f);
GL11.glDepthMask(true);
}
@@ -13,7 +13,7 @@ import org.lwjgl.opengl.GL11;
* Inner solid core with outer translucent glow.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergySlicer extends RenderEnergyAbility {
public class RenderEnergySlicer extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
@@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergySweeper;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
@@ -15,11 +15,11 @@ import org.lwjgl.opengl.GL11;
* Uses similar rendering style to the Beam trail for visual consistency.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilitySweeper extends Render {
public class RenderSweeper extends Render {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilitySweeper sweeper = (EntityAbilitySweeper) entity;
EntityEnergySweeper sweeper = (EntityEnergySweeper) entity;
setupRenderState();
@@ -114,7 +114,7 @@ public class RenderAbilitySweeper extends Render {
/**
* Render a beam segment as a 3D rectangular prism with independent width and height.
* Uses the same approach as RenderAbilityBeam.renderBeamRectangle.
* Uses the same approach as RenderEnergyBeam.renderBeamRectangle.
*/
private void renderBeamSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
@@ -23,7 +23,7 @@ import java.util.Map;
import java.util.Random;
@SideOnly(Side.CLIENT)
public class RenderAbilityZone extends Render {
public class RenderZone extends Render {
private static final int CIRCLE_SEGMENTS = 32;
private static final int ACCENT_LINE_COUNT = 12;
@@ -99,7 +99,9 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
playerdata.questData.finishedQuests.put(quest.id, completeTime);
}
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
&& (quest.profileOptions.completeControl == EnumProfileSync.Shared
|| quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
;
@@ -115,7 +115,9 @@ public class QuestCommand extends CommandKamkeelBase {
playerdata.questData.finishedQuests.put(quest.id, completeTime);
}
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
&& (quest.profileOptions.completeControl == EnumProfileSync.Shared
|| quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
playerdata.save();
@@ -17,9 +17,12 @@ import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.extender.IAbilityExtender;
import kamkeel.npcs.controllers.data.ability.gui.IAbilityFieldProvider;
import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider;
import kamkeel.npcs.controllers.data.ability.CustomAbility;
import kamkeel.npcs.controllers.data.ability.type.AbilityCharge;
import kamkeel.npcs.controllers.data.ability.type.AbilityCutter;
import kamkeel.npcs.controllers.data.ability.type.AbilityDash;
import kamkeel.npcs.controllers.data.ability.type.AbilityCounter;
import kamkeel.npcs.controllers.data.ability.type.AbilityDodge;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.ability.type.AbilityHazard;
import kamkeel.npcs.controllers.data.ability.type.AbilityEffect;
@@ -37,11 +40,15 @@ import kamkeel.npcs.controllers.data.ability.type.energy.AbilityOrb;
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityShield;
import kamkeel.npcs.controllers.data.ability.type.energy.AbilitySweeper;
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityWall;
import net.minecraftforge.common.util.Constants;
import noppes.npcs.controllers.data.AbilityScript;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import noppes.npcs.api.ability.IChainedAbility;
import noppes.npcs.api.handler.IAbilityHandler;
import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.data.PlayerData;
@@ -52,7 +59,6 @@ import java.io.File;
import java.util.*;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
public class AbilityController implements IAbilityHandler {
@@ -64,6 +70,10 @@ public class AbilityController implements IAbilityHandler {
private final Map<String, Ability> customAbilities = new LinkedHashMap<>(); // name → Ability
private final Map<String, Ability> customAbilitiesById = new LinkedHashMap<>(); // UUID → Ability
// ── Script Handlers ────────────────────────────────────────────────────
public final HashMap<String, AbilityScript> abilityScriptHandlers = new HashMap<>();
public final HashMap<String, ChainedAbilityScript> chainedAbilityScriptHandlers = new HashMap<>();
// ── Extension Points ─────────────────────────────────────────────────────
private final Map<String, List<AbilityVariant>> externalVariants = new LinkedHashMap<>();
private final List<IAbilityFieldProvider> fieldProviders = new ArrayList<>();
@@ -72,11 +82,6 @@ public class AbilityController implements IAbilityHandler {
private final Map<String, Supplier<AbilityCondition>> conditionTypes = new HashMap<>();
private final List<Predicate<EntityPlayer>> flightCheckers = new ArrayList<>();
// ── Legacy Migration ─────────────────────────────────────────────────────
private static final Pattern UUID_PATTERN =
Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
Pattern.CASE_INSENSITIVE);
// ── Chained Abilities ──────────────────────────────────────────────────
private final Map<String, ChainedAbility> chainedAbilities = new LinkedHashMap<>(); // name → ChainedAbility
private final Map<String, ChainedAbility> chainedAbilitiesById = new LinkedHashMap<>(); // UUID → ChainedAbility
@@ -97,7 +102,7 @@ public class AbilityController implements IAbilityHandler {
// TYPE REGISTRATION
// ═══════════════════════════════════════════════════════════════════════════
public void registerType(String factoryKey, Supplier<Ability> factory) {
public void registerType(Supplier<Ability> factory) {
Ability temp = factory.get();
String typeId = temp.getTypeId();
if (abilityTypes.containsKey(typeId)) {
@@ -132,36 +137,37 @@ public class AbilityController implements IAbilityHandler {
}
private void registerBuiltinTypes() {
registerType("cnpc:slam", AbilitySlam::new);
registerType("cnpc:charge", AbilityCharge::new);
registerType(CustomAbility::new);
registerType("cnpc:heavy_hit", AbilityHeavyHit::new);
registerType("cnpc:cutter", AbilityCutter::new);
registerType(AbilitySlam::new);
registerType(AbilityCharge::new);
// registerType("cnpc:projectile", AbilityProjectile::new);
registerType(AbilityHeavyHit::new);
registerType(AbilityCutter::new);
registerType("cnpc:sweeper", AbilitySweeper::new);
registerType("cnpc:orb", AbilityOrb::new);
registerType("cnpc:disc", AbilityDisc::new);
registerType("cnpc:laser_shot", AbilityLaser::new);
registerType("cnpc:beam", AbilityBeam::new);
// registerType("cnpc:slicer", AbilitySlicer::new);
registerType(AbilitySweeper::new);
registerType(AbilityOrb::new);
registerType(AbilityDisc::new);
registerType(AbilityLaser::new);
registerType(AbilityBeam::new);
registerType("cnpc:dash", AbilityDash::new);
registerType("cnpc:teleport", AbilityTeleport::new);
registerType(AbilityDash::new);
registerType(AbilityTeleport::new);
registerType("cnpc:vortex", AbilityVortex::new);
registerType("cnpc:shockwave", AbilityShockwave::new);
registerType(AbilityVortex::new);
registerType(AbilityShockwave::new);
registerType("cnpc:guard", AbilityGuard::new);
registerType("cnpc:effect", AbilityEffect::new);
registerType(AbilityGuard::new);
registerType(AbilityCounter::new);
registerType(AbilityDodge::new);
registerType(AbilityEffect::new);
registerType("cnpc:hazard", AbilityHazard::new);
registerType("cnpc:trap", AbilityTrap::new);
registerType(AbilityHazard::new);
registerType(AbilityTrap::new);
registerType("cnpc:dome", AbilityDome::new);
registerType("cnpc:wall", AbilityWall::new);
registerType("cnpc:shield", AbilityShield::new);
registerType(AbilityDome::new);
registerType(AbilityWall::new);
registerType(AbilityShield::new);
}
private void registerBuiltinConditionTypes() {
@@ -193,7 +199,7 @@ public class AbilityController implements IAbilityHandler {
public Ability getAbilityByDisplayName(String displayName) {
for (Ability ability : builtAbilities.values()) {
if (ability.getName().equals(displayName)) {
if (ability.getDisplayName().equals(displayName)) {
return ability;
}
}
@@ -214,8 +220,6 @@ public class AbilityController implements IAbilityHandler {
public void load() {
customAbilities.clear();
customAbilitiesById.clear();
int migrated = 0;
Map<String, String> migratedAbilityNames = new HashMap<String, String>();
File dir = getDir();
File[] files = dir.exists() ? dir.listFiles() : null;
@@ -230,59 +234,29 @@ public class AbilityController implements IAbilityHandler {
Ability ability = fromNBT(nbt);
if (ability == null) continue;
// Skip built-in abilities that were erroneously saved as custom files
if (ability.isBuiltIn()) {
file.delete();
LogWriter.info("Removed stale built-in ability file: " + filename);
continue;
}
String storedName = ability.getName();
String preferredName;
if (UUID_PATTERN.matcher(fileKey).matches()) {
preferredName = (storedName != null && !storedName.isEmpty()) ? storedName : fileKey;
} else {
preferredName = fileKey;
}
String name = FileNameHelper.sanitizeName(preferredName, "Ability");
String name = FileNameHelper.sanitizeName(fileKey, "Ability");
name = makeUniqueNameForLoad(customAbilities, dir, file, name, fileKey);
boolean dirty = false;
if (!name.equals(fileKey)) {
File renamedFile = new File(dir, name + ".json");
if (file.renameTo(renamedFile)) {
LogWriter.info("Migrated ability file: " + fileKey + ".json -> " + name + ".json");
file = renamedFile;
migrated++;
dirty = true;
} else {
LogWriter.error("Failed to rename ability file: " + fileKey + ".json -> " + name + ".json");
}
}
ability.setName(name);
if (storedName != null && !storedName.equals(name)) {
dirty = true;
if (!storedName.isEmpty()) {
migratedAbilityNames.put(storedName, name);
}
}
if (!fileKey.equals(name)) {
migratedAbilityNames.put(fileKey, name);
}
// Ensure ability has a UUID; generate one for legacy abilities
String uuid = ability.getId();
if (uuid == null || uuid.isEmpty() || uuid.equals(fileKey) || uuid.equals(name)) {
// Legacy: id was the name or empty — generate a real UUID
if (uuid == null || uuid.isEmpty()) {
uuid = UUID.randomUUID().toString();
ability.setId(uuid);
migrated++;
dirty = true;
}
if (dirty) {
NBTJsonUtil.SaveFile(file, ability.writeNBT());
NBTJsonUtil.SaveFile(file, ability.writeNBT(true));
}
customAbilities.put(name, ability);
@@ -294,12 +268,9 @@ public class AbilityController implements IAbilityHandler {
}
customAbilityRevision++;
if (migrated > 0) {
LogWriter.info("Migrated " + migrated + " abilities (filename normalization / UUID repair)");
}
LogWriter.info("Loaded " + customAbilities.size() + " custom abilities");
loadChainedAbilities(migratedAbilityNames);
loadChainedAbilities();
}
private boolean nameFileExists(File dir, String name, File ignoredFile) {
@@ -325,32 +296,6 @@ public class AbilityController implements IAbilityHandler {
return candidate;
}
private boolean remapChainEntryReferences(ChainedAbility chain, Map<String, String> migratedAbilityNames) {
if (chain == null || migratedAbilityNames == null || migratedAbilityNames.isEmpty()) return false;
boolean changed = false;
for (ChainedAbilityEntry entry : chain.getEntries()) {
if (entry == null || !entry.isReference()) continue;
String ref = entry.getAbilityReference();
if (ref == null || ref.isEmpty()) continue;
String mapped = migratedAbilityNames.get(ref);
if (mapped == null) {
for (Map.Entry<String, String> e : migratedAbilityNames.entrySet()) {
if (e.getKey().equalsIgnoreCase(ref)) {
mapped = e.getValue();
break;
}
}
}
if (mapped != null && !mapped.equals(ref)) {
entry.setAbilityReference(mapped);
changed = true;
}
}
return changed;
}
public boolean saveCustomAbility(Ability ability) {
if (ability == null) return false;
if (ability.isBuiltIn()) return false;
@@ -396,7 +341,8 @@ public class AbilityController implements IAbilityHandler {
File fileCurrent = new File(dir, name + ".json");
try {
NBTTagCompound nbt = ability.writeNBT();
NBTTagCompound nbt = ability.writeNBT(true);
NBTJsonUtil.SaveFile(fileNew, nbt);
if (fileCurrent.exists()) {
@@ -434,10 +380,11 @@ public class AbilityController implements IAbilityHandler {
}
if (removed == null) return false;
// Also remove from UUID index
// Also remove from UUID index and script handler
String uuid = removed.getId();
if (uuid != null && !uuid.isEmpty()) {
customAbilitiesById.remove(uuid);
abilityScriptHandlers.remove(uuid);
}
File dir = getDir();
@@ -459,6 +406,9 @@ public class AbilityController implements IAbilityHandler {
pData.abilityData.lockAbility(name);
changed = true;
}
if (changed) {
pData.save();
}
}
}
}
@@ -516,10 +466,9 @@ public class AbilityController implements IAbilityHandler {
// CHAINED ABILITIES
// ═══════════════════════════════════════════════════════════════════════════
private void loadChainedAbilities(Map<String, String> migratedAbilityNames) {
private void loadChainedAbilities() {
chainedAbilities.clear();
chainedAbilitiesById.clear();
int migrated = 0;
File dir = getChainedDir();
File[] files = dir.exists() ? dir.listFiles() : null;
@@ -534,7 +483,6 @@ public class AbilityController implements IAbilityHandler {
ChainedAbility chain = new ChainedAbility();
chain.readNBT(nbt);
String storedName = chain.getName();
String name = FileNameHelper.sanitizeName(fileKey, "Chain");
name = makeUniqueNameForLoad(chainedAbilities, dir, file, name, fileKey);
@@ -542,33 +490,22 @@ public class AbilityController implements IAbilityHandler {
if (!name.equals(fileKey)) {
File renamedFile = new File(dir, name + ".json");
if (file.renameTo(renamedFile)) {
LogWriter.info("Migrated chained ability file: " + fileKey + ".json -> " + name + ".json");
file = renamedFile;
dirty = true;
} else {
LogWriter.error("Failed to rename chained ability file: " + fileKey + ".json -> " + name + ".json");
}
}
chain.setName(name);
if (storedName != null && !storedName.equals(name)) {
dirty = true;
}
if (remapChainEntryReferences(chain, migratedAbilityNames)) {
dirty = true;
}
String uuid = chain.getId();
if (uuid == null || uuid.isEmpty() || uuid.equals(fileKey) || uuid.equals(name)) {
if (uuid == null || uuid.isEmpty()) {
uuid = UUID.randomUUID().toString();
chain.setId(uuid);
dirty = true;
}
if (dirty) {
NBTJsonUtil.SaveFile(file, chain.writeNBT());
migrated++;
NBTJsonUtil.SaveFile(file, chain.writeNBT(true));
}
chainedAbilities.put(name, chain);
@@ -580,9 +517,6 @@ public class AbilityController implements IAbilityHandler {
}
chainedAbilityRevision++;
if (migrated > 0) {
LogWriter.info("Migrated " + migrated + " chained abilities");
}
LogWriter.info("Loaded " + chainedAbilities.size() + " chained abilities");
}
@@ -626,7 +560,8 @@ public class AbilityController implements IAbilityHandler {
File fileCurrent = new File(dir, name + ".json");
try {
NBTTagCompound nbt = chain.writeNBT();
NBTTagCompound nbt = chain.writeNBT(true);
NBTJsonUtil.SaveFile(fileNew, nbt);
if (fileCurrent.exists()) {
@@ -667,6 +602,7 @@ public class AbilityController implements IAbilityHandler {
String uuid = removed.getId();
if (uuid != null && !uuid.isEmpty()) {
chainedAbilitiesById.remove(uuid);
chainedAbilityScriptHandlers.remove(uuid);
}
File dir = getChainedDir();
@@ -775,7 +711,7 @@ public class AbilityController implements IAbilityHandler {
}
@Override
public boolean saveChainedAbility(noppes.npcs.api.ability.IChainedAbility chain) {
public boolean saveChainedAbility(IChainedAbility chain) {
if (chain instanceof ChainedAbility) {
return saveChainedAbility((ChainedAbility) chain);
}
@@ -818,48 +754,36 @@ public class AbilityController implements IAbilityHandler {
Ability byUuid = customAbilitiesById.get(key);
if (byUuid != null) return byUuid.deepCopy();
// Built-in: exact name
// Built-in: exact key
Ability builtIn = builtAbilities.get(key);
if (builtIn != null) return builtIn.deepCopy();
// Built-in: case-insensitive map key
// Built-in: case-insensitive key
String lowerKey = key.toLowerCase();
for (Map.Entry<String, Ability> entry : builtAbilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
if (entry.getKey().equalsIgnoreCase(lowerKey)) {
return entry.getValue().deepCopy();
}
}
// Built-in: by ability name (name may differ from map key, e.g. "Ki Fist" vs "ki_fist")
// Built-in: by ID (case-insensitive)
for (Ability ability : builtAbilities.values()) {
if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) {
if (key.equalsIgnoreCase(ability.getId())) {
return ability.deepCopy();
}
}
// Built-in: registry key / ID
for (Ability ability : builtAbilities.values()) {
if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) {
return ability.deepCopy();
}
}
// Custom: exact name (fallback for legacy references)
// Custom: exact name
Ability custom = customAbilities.get(key);
if (custom != null) return custom.deepCopy();
// Custom: case-insensitive name
for (Ability ability : customAbilities.values()) {
if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) {
return ability.deepCopy();
for (Map.Entry<String, Ability> entry : customAbilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue().deepCopy();
}
}
String sanitizedKey = FileNameHelper.sanitizeTextInput(key);
if (!sanitizedKey.equals(key)) {
Ability sanitized = customAbilities.get(sanitizedKey);
if (sanitized != null) return sanitized.deepCopy();
}
return null;
}
@@ -904,14 +828,8 @@ public class AbilityController implements IAbilityHandler {
}
public boolean hasAbility(String key) {
if (builtAbilities.containsKey(key) || customAbilities.containsKey(key)
|| customAbilitiesById.containsKey(key)) {
return true;
}
String sanitized = FileNameHelper.sanitizeTextInput(key);
return !sanitized.equals(key)
&& (builtAbilities.containsKey(sanitized) || customAbilities.containsKey(sanitized)
|| customAbilitiesById.containsKey(sanitized));
return builtAbilities.containsKey(key) || customAbilities.containsKey(key)
|| customAbilitiesById.containsKey(key);
}
public Ability getCustomAbilityByUUID(String uuid) {
@@ -919,12 +837,30 @@ public class AbilityController implements IAbilityHandler {
}
public Ability getCustomAbilityByName(String name) {
Ability ability = customAbilities.get(name);
if (ability != null) return ability;
String sanitized = FileNameHelper.sanitizeTextInput(name);
if (!sanitized.equals(name)) {
return customAbilities.get(sanitized);
return customAbilities.get(name);
}
/**
* Resolve an ability by key and return the live (non-copied) reference.
* For validation/permission checks only — do NOT expose or modify the returned ability.
* Uses the same lookup chain as {@link #resolveAbility(String)}.
*/
public Ability peekAbility(String key) {
if (key == null || key.isEmpty()) return null;
Ability byUuid = customAbilitiesById.get(key);
if (byUuid != null) return byUuid;
Ability builtIn = builtAbilities.get(key);
if (builtIn != null) return builtIn;
for (Ability ability : builtAbilities.values()) {
if (key.equals(ability.getId())) return ability;
}
Ability custom = customAbilities.get(key);
if (custom != null) return custom;
return null;
}
@@ -935,33 +871,20 @@ public class AbilityController implements IAbilityHandler {
public boolean canResolveAbility(String key) {
if (key == null || key.isEmpty()) return false;
// Custom: UUID lookup (most common for persistent references)
// Custom: UUID lookup
if (customAbilitiesById.containsKey(key)) return true;
// Built-in: exact name
// Built-in: exact key
if (builtAbilities.containsKey(key)) return true;
// Built-in: case-insensitive name
for (String name : builtAbilities.keySet()) {
if (name.equalsIgnoreCase(key)) return true;
}
// Built-in: registry key / ID
// Built-in: by ID
for (Ability ability : builtAbilities.values()) {
if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) return true;
if (key.equals(ability.getId())) return true;
}
// Custom: exact name (fallback for legacy references)
// Custom: exact name
if (customAbilities.containsKey(key)) return true;
// Custom: case-insensitive name
for (Ability ability : customAbilities.values()) {
if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) return true;
}
String sanitizedKey = FileNameHelper.sanitizeTextInput(key);
if (!sanitizedKey.equals(key) && customAbilities.containsKey(sanitizedKey)) return true;
return false;
}
@@ -523,6 +523,7 @@ public class ProfileController implements IProfileHandler {
// overwrite the destination slot with stale data.
saveSlotData(profile.player, profile, prevSlot);
loadSlotData(profile.player, profile, newSlotId);
syncSharedQuestsToPlayer(profile.player);
EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true);
} else {
@@ -860,6 +861,9 @@ public class ProfileController implements IProfileHandler {
}
}
// Update the profile cache
profile.sharedQuestTimestamps = universalFinished;
// Push the universal shared completion times into every slot.
for (ISlot slot : profile.getSlots().values()) {
IPlayerData data = getSlotPlayerData(player, slot.getId());
@@ -872,21 +876,29 @@ public class ProfileController implements IProfileHandler {
}
}
public void syncSharedQuestsToPlayer(EntityPlayer player) {
Profile profile = getProfile(player);
if (profile == null || profile.sharedQuestTimestamps.isEmpty()) {
return;
}
PlayerQuestData questData = PlayerData.get(player).questData;
for (Map.Entry<Integer, Long> entry : profile.sharedQuestTimestamps.entrySet()) {
Long existing = questData.finishedQuests.get(entry.getKey());
if (existing == null || entry.getValue() > existing) {
questData.finishedQuests.put(entry.getKey(), entry.getValue());
}
}
}
public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) {
Profile profile = getProfile(player);
if (profile == null) {
return;
}
for (ISlot slot : profile.getSlots().values()) {
IPlayerData playerData = getSlotPlayerData(player, slot.getId());
if (playerData != null) {
PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData();
Long existing = questData.finishedQuests.get(questId);
if (existing == null || completeTime > existing) {
questData.finishedQuests.put(questId, completeTime);
}
playerData.save();
}
Long existing = profile.sharedQuestTimestamps.get(questId);
if (existing == null || completeTime > existing) {
profile.sharedQuestTimestamps.put(questId, completeTime);
}
save(player, profile);
}
@@ -337,7 +337,7 @@ public class SyncController {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Map.Entry<String, Ability> entry : AbilityController.Instance.getCustomAbilities().entrySet()) {
NBTTagCompound abilityNBT = entry.getValue().writeNBT();
NBTTagCompound abilityNBT = entry.getValue().writeNBT(false);
abilityNBT.setString("CustomAbilityId", entry.getKey());
list.appendTag(abilityNBT);
}
@@ -358,7 +358,7 @@ public class SyncController {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Map.Entry<String, ChainedAbility> entry : AbilityController.Instance.getChainedAbilities().entrySet()) {
NBTTagCompound chainNBT = entry.getValue().writeNBT();
NBTTagCompound chainNBT = entry.getValue().writeNBT(false);
chainNBT.setString("ChainedAbilityId", entry.getKey());
list.appendTag(chainNBT);
}
@@ -19,9 +19,9 @@ import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.util.FileNameHelper;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
@@ -36,23 +36,20 @@ import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import noppes.npcs.DataAbilities;
import noppes.npcs.NpcDamageSource;
import noppes.npcs.api.INbt;
import noppes.npcs.api.ability.IAbility;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.Frame;
import noppes.npcs.controllers.data.PlayerDataScript;
import noppes.npcs.controllers.data.AbilityScript;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.EventHooks;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.AbilityEvent;
import noppes.npcs.scripted.event.player.PlayerAbilityEvent;
import java.util.ArrayList;
import java.util.Collections;
@@ -139,6 +136,48 @@ public abstract class Ability implements IAbility, IAbilityAction {
protected transient boolean builtIn = false;
protected transient String registryKey;
// Default icon layers (set in subclass constructors, NOT persisted)
protected transient DefaultIconLayer[] defaultIconLayers = null;
protected transient int defaultIconWidth = 48;
protected transient int defaultIconHeight = 48;
/**
* A single layer of a default ability icon. Each layer has a texture,
* an optional dynamic color source, and optional per-state texture variants.
*/
public static class DefaultIconLayer {
public final String texture;
public final String[] stateTextures;
public final java.util.function.IntSupplier colorSource;
public DefaultIconLayer(String texture, String[] stateTextures, java.util.function.IntSupplier colorSource) {
this.texture = texture;
this.stateTextures = stateTextures;
this.colorSource = colorSource;
}
public DefaultIconLayer(String texture, java.util.function.IntSupplier colorSource) {
this(texture, null, colorSource);
}
/** Layer with no color tinting (renders as white). */
public DefaultIconLayer(String texture) {
this(texture, null, null);
}
/** Resolve texture for a given toggle state. Falls back to base texture. */
public String getTextureForState(int state) {
if (state > 0 && stateTextures != null && state - 1 < stateTextures.length) {
return stateTextures[state - 1];
}
return texture;
}
public int getColor() {
return colorSource != null ? colorSource.getAsInt() : 0xFFFFFF;
}
}
// ═══════════════════════════════════════════════════════════════════
// TOGGLE CONFIGURATION (saved to NBT for custom abilities)
// ═══════════════════════════════════════════════════════════════════
@@ -295,28 +334,14 @@ public abstract class Ability implements IAbility, IAbilityAction {
// ═══════════════════════════════════════════════════════════════════
/**
* Called when this toggle ability is first activated (state goes from 0 to any active state).
* Override to apply effects (e.g., set a DBC flag, apply a buff).
*/
public void onToggleOn(EntityLivingBase caster) {
}
/**
* Called when this toggle ability is fully deactivated (state goes to 0).
* Override to remove effects (e.g., clear a DBC flag, remove a buff).
*/
public void onToggleOff(EntityLivingBase caster) {
}
/**
* Called whenever the toggle state changes (including on/off transitions and mid-cycling).
* For multi-state toggles, this fires on every state transition.
* Called whenever the toggle state changes (activation, deactivation, or mid-cycling).
* Override to apply/remove effects based on state transitions.
*
* @param caster The entity
* @param oldState Previous state (0 = was off)
* @param newState New state (0 = now off, 1+ = active state)
*/
public void onToggleStateChanged(EntityLivingBase caster, int oldState, int newState) {
public void onToggle(EntityLivingBase caster, int oldState, int newState) {
}
/**
@@ -365,11 +390,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
* Unlike {@link #cleanup()}, this does NOT kill spawned entities (they may
* still be in flight for overlap mode).
*/
public void resetForBurst() {
}
public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) {
}
public void resetForBurst() {}
/**
* Apply damage to an entity with ability hit event support.
@@ -432,39 +453,15 @@ public abstract class Ability implements IAbility, IAbilityAction {
private boolean applyAbilityDamageInternal(EntityLivingBase caster, EntityLivingBase hitEntity,
float damage, float knockback, float knockbackUp,
double knockbackDirX, double knockbackDirZ) {
// Fire hit event for NPC casters (NPC event system)
if (caster instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) caster;
DataAbilities dataAbilities = npc.abilities;
AbilityEvent.HitEvent event = dataAbilities.fireHitEvent(
this, currentTarget, hitEntity, damage, knockback, knockbackUp);
if (event == null) {
return false; // Cancelled
}
damage = event.getDamage();
knockback = event.getKnockback();
knockbackUp = event.getKnockbackUp();
}
// Fire hit event for Player casters (Player event system)
else if (caster instanceof EntityPlayer && ScriptController.Instance != null) {
EntityPlayer player = (EntityPlayer) caster;
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
if (handler != null) {
IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player);
PlayerAbilityEvent.HitEvent event = new PlayerAbilityEvent.HitEvent(
iPlayer, this, currentTarget, hitEntity, damage, knockback, knockbackUp);
if (noppes.npcs.EventHooks.onPlayerAbilityHit(handler, event)) {
return false; // Cancelled
}
damage = event.getDamage();
knockback = event.getKnockback();
knockbackUp = event.getKnockbackUp();
}
// Fire hit event (unified — works for both NPC and Player casters)
AbilityEvent.HitEvent hitEvent = new AbilityEvent.HitEvent(
caster, this, currentTarget, hitEntity, damage, knockback, knockbackUp);
if (EventHooks.onAbilityHit(this, hitEvent)) {
return false; // Cancelled
}
damage = hitEvent.getDamage();
knockback = hitEvent.getKnockback();
knockbackUp = hitEvent.getKnockbackUp();
// Save velocity before damage to cancel vanilla knockback when ability knockback is zero
double prevMotionX = hitEntity.motionX;
@@ -809,23 +806,35 @@ public abstract class Ability implements IAbility, IAbilityAction {
}
}
// ── Icon tab (native) ─────────────────────────────────────
// ── Icon section (Effects tab) ───────────────────────────
if (!isNpcInlineEdit()) {
AbilityIconData icon = AbilityIconData.fromAbility(this);
defs.add(FieldDef.stringField("gui.texture", icon::getTexture, icon::setTexture)
.tab("Icon"));
defs.add(FieldDef.section("ability.icon.section.uv").tab("Icon"));
defs.add(FieldDef.intField("ability.icon.x", icon::getIconX, icon::setIconX)
.tab("Icon").range(0, 4096));
defs.add(FieldDef.intField("ability.icon.y", icon::getIconY, icon::setIconY)
.tab("Icon").range(0, 4096));
defs.add(FieldDef.section("gui.size").tab("Icon"));
defs.add(FieldDef.intField("gui.width", icon::getWidth, icon::setWidth)
.tab("Icon").range(1, 256));
defs.add(FieldDef.intField("gui.height", icon::getHeight, icon::setHeight)
.tab("Icon").range(1, 256));
java.util.function.BooleanSupplier isCustom = icon::isEnabled;
defs.add(FieldDef.section("ability.section.icon").tab("Effects"));
defs.add(FieldDef.boolField("ability.hasIcon", icon::isEnabled, icon::setEnabled)
.tab("Effects"));
defs.add(FieldDef.row(
FieldDef.intField("gui.width", icon::getWidth, icon::setWidth).range(1, 256),
FieldDef.intField("gui.height", icon::getHeight, icon::setHeight).range(1, 256)
).tab("Effects").visibleWhen(isCustom));
defs.add(FieldDef.floatField("gui.scale", icon::getScale, icon::setScale)
.tab("Icon").range(0.1f, 10.0f));
.tab("Effects").range(0.1f, 10.0f).visibleWhen(isCustom));
defs.add(FieldDef.intField("ability.icon.layers", icon::getLayerCount, icon::setLayerCount)
.tab("Effects").range(1, AbilityIconData.MAX_LAYERS).visibleWhen(isCustom));
addIconLayerFields(defs, icon, 0, isCustom);
addIconLayerFields(defs, icon, 1, () -> isCustom.getAsBoolean() && icon.getLayerCount() >= 2);
addIconLayerFields(defs, icon, 2, () -> isCustom.getAsBoolean() && icon.getLayerCount() >= 3);
// Animation
defs.add(FieldDef.section("Animation").tab("Effects").visibleWhen(isCustom));
defs.add(FieldDef.boolField("gui.animated", icon::isAnimated, icon::setAnimated)
.tab("Effects").visibleWhen(isCustom).hover("gui.animated.hover"));
defs.add(FieldDef.intField("gui.frameCount", icon::getFrameCount, icon::setFrameCount)
.tab("Effects").range(1, 256).visibleWhen(() -> isCustom.getAsBoolean() && icon.isAnimated()));
defs.add(FieldDef.intField("gui.frameTime", icon::getFrameTime, icon::setFrameTime)
.tab("Effects").range(1, 100).visibleWhen(() -> isCustom.getAsBoolean() && icon.isAnimated()));
}
// External field providers (e.g., DBC Addon injecting a "DBC" tab)
@@ -836,6 +845,28 @@ public abstract class Ability implements IAbility, IAbilityAction {
return defs;
}
private void addIconLayerFields(List<FieldDef> defs, AbilityIconData icon, int layerIndex,
java.util.function.BooleanSupplier visible) {
String sectionLabel = StatCollector.translateToLocal("ability.icon.layer") + " " + (layerIndex + 1);
defs.add(FieldDef.section(sectionLabel).tab("Effects").visibleWhen(visible));
defs.add(FieldDef.stringField("gui.texture",
() -> icon.getLayer(layerIndex).texture,
t -> icon.setLayerTexture(layerIndex, t))
.tab("Effects").visibleWhen(visible));
defs.add(FieldDef.row(
FieldDef.intField("ability.icon.x",
() -> icon.getLayer(layerIndex).iconX,
x -> icon.setLayerIconX(layerIndex, x)).range(0, 4096),
FieldDef.intField("ability.icon.y",
() -> icon.getLayer(layerIndex).iconY,
y -> icon.setLayerIconY(layerIndex, y)).range(0, 4096)
).tab("Effects").visibleWhen(visible));
defs.add(FieldDef.colorSubGui("ability.icon.tint",
() -> icon.getLayer(layerIndex).tintColor,
c -> icon.setLayerTintColor(layerIndex, c))
.tab("Effects").visibleWhen(visible));
}
/**
* Creates the GUI for configuring this ability.
* Override this method to provide a custom GUI subclass for type-specific settings.
@@ -1378,7 +1409,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
// NBT (config only, execution state is transient)
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT() {
public NBTTagCompound writeNBT(boolean saveScripts) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("id", id);
nbt.setString("name", name);
@@ -1405,9 +1436,10 @@ public abstract class Ability implements IAbility, IAbilityAction {
nbt.setInteger("windUpAnimationId", windUpAnimationId);
nbt.setInteger("activeAnimationId", activeAnimationId);
nbt.setInteger("dazedAnimationId", dazedAnimationId);
nbt.setString("windUpAnimationName", windUpAnimationName);
nbt.setString("activeAnimationName", activeAnimationName);
nbt.setString("dazedAnimationName", dazedAnimationName);
// Resolve current animation names from controller before writing
nbt.setString("windUpAnimationName", resolveAnimationName(windUpAnimationId, windUpAnimationName));
nbt.setString("activeAnimationName", resolveAnimationName(activeAnimationId, activeAnimationName));
nbt.setString("dazedAnimationName", resolveAnimationName(dazedAnimationId, dazedAnimationName));
nbt.setBoolean("showTelegraph", showTelegraph);
nbt.setString("telegraphType", telegraphType.name());
nbt.setFloat("telegraphHeightOffset", telegraphHeightOffset);
@@ -1452,6 +1484,16 @@ public abstract class Ability implements IAbility, IAbilityAction {
writeTypeNBT(typeNBT);
nbt.setTag("typeData", typeNBT);
// Script handler data (matching CustomEffect.writeToNBT pattern)
if (saveScripts) {
AbilityScript handler = getScriptHandler();
if (handler != null) {
NBTTagCompound scriptData = new NBTTagCompound();
handler.writeToNBT(scriptData);
nbt.setTag("ScriptData", scriptData);
}
}
return nbt;
}
@@ -1548,6 +1590,13 @@ public abstract class Ability implements IAbility, IAbilityAction {
if (nbt.hasKey("typeData")) {
readTypeNBT(nbt.getCompoundTag("typeData"));
}
// Script handler data (matching CustomEffect.readFromNBT pattern)
if (nbt.hasKey("ScriptData", 10)) {
AbilityScript handler = new AbilityScript(this.id);
handler.readFromNBT(nbt.getCompoundTag("ScriptData"));
setScriptHandler(handler);
}
}
// ═══════════════════════════════════════════════════════════════════
@@ -1627,8 +1676,29 @@ public abstract class Ability implements IAbility, IAbilityAction {
this.typeId = "ability." + registryKey.replace(':', '.');
}
// ═══════════════════════════════════════════════════════════════════
// DEFAULT ICON
// ═══════════════════════════════════════════════════════════════════
public DefaultIconLayer[] getDefaultIconLayers() {
return defaultIconLayers;
}
public int getDefaultIconWidth() {
return defaultIconWidth;
}
public int getDefaultIconHeight() {
return defaultIconHeight;
}
public boolean hasDefaultIcon() {
return defaultIconLayers != null && defaultIconLayers.length > 0
&& defaultIconLayers[0].texture != null && !defaultIconLayers[0].texture.isEmpty();
}
public Ability deepCopy() {
return AbilityController.Instance.fromNBT(this.writeNBT());
return AbilityController.Instance.fromNBT(this.writeNBT(true));
}
@Override
@@ -1964,17 +2034,32 @@ public abstract class Ability implements IAbility, IAbilityAction {
this.activeSound = activeSound;
}
/**
* Resolves the current animation name for a custom animation ID.
* If the ID refers to a custom animation, looks up the current name from the controller.
* For built-in animations (id == -1), returns the stored name as-is.
*/
protected String resolveAnimationName(int animId, String storedName) {
if (animId >= 0 && AnimationController.Instance != null) {
Animation anim = (Animation) AnimationController.Instance.get(animId);
if (anim != null && anim.name != null && !anim.name.isEmpty()) {
return anim.name;
}
}
return storedName;
}
public Animation getWindUpAnimation() {
if (AnimationController.Instance == null) return null;
// Built-in animation by name takes priority
if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(windUpAnimationName, true);
}
// Fall back to user animation by ID
// Custom animation by ID (most reliable, survives renames)
if (windUpAnimationId >= 0) {
return (Animation) AnimationController.Instance.get(windUpAnimationId);
}
// Built-in animation by name
if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(windUpAnimationName, true);
}
return null;
}
@@ -1997,14 +2082,14 @@ public abstract class Ability implements IAbility, IAbilityAction {
public Animation getActiveAnimation() {
if (AnimationController.Instance == null) return null;
// Built-in animation by name takes priority
if (activeAnimationName != null && !activeAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(activeAnimationName, true);
}
// Fall back to user animation by ID
// Custom animation by ID (most reliable, survives renames)
if (activeAnimationId >= 0) {
return (Animation) AnimationController.Instance.get(activeAnimationId);
}
// Built-in animation by name
if (activeAnimationName != null && !activeAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(activeAnimationName, true);
}
return null;
}
@@ -2027,14 +2112,14 @@ public abstract class Ability implements IAbility, IAbilityAction {
public Animation getDazedAnimation() {
if (AnimationController.Instance == null) return null;
// Built-in animation by name takes priority
if (dazedAnimationName != null && !dazedAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(dazedAnimationName, true);
}
// Fall back to user animation by ID
// Custom animation by ID (most reliable, survives renames)
if (dazedAnimationId >= 0) {
return (Animation) AnimationController.Instance.get(dazedAnimationId);
}
// Built-in animation by name
if (dazedAnimationName != null && !dazedAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(dazedAnimationName, true);
}
return null;
}
@@ -2284,14 +2369,14 @@ public abstract class Ability implements IAbility, IAbilityAction {
}
Animation animation = null;
// Check for built-in animation (by name) first
if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) {
animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true);
}
// Fall back to user animation (by ID)
else if (windUpAnimationId >= 0) {
// Custom animation by ID (most reliable, survives renames)
if (windUpAnimationId >= 0) {
animation = (Animation) AnimationController.Instance.get(windUpAnimationId);
}
// Built-in animation by name
else if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) {
animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true);
}
if (animation == null || animation.frames.isEmpty()) {
return this.windUpTicks;
@@ -2390,9 +2475,9 @@ public abstract class Ability implements IAbility, IAbilityAction {
double maxZ = Math.max(caster.posZ, target.posZ) + searchRange;
AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
List<EntityAbilityBarrier> barriers = world.getEntitiesWithinAABB(EntityAbilityBarrier.class, searchBox);
List<EntityEnergyBarrier> barriers = world.getEntitiesWithinAABB(EntityEnergyBarrier.class, searchBox);
for (EntityAbilityBarrier barrier : barriers) {
for (EntityEnergyBarrier barrier : barriers) {
if (barrier.isDead) continue;
if (barrier.isCharging()) continue;
@@ -2403,10 +2488,10 @@ public abstract class Ability implements IAbility, IAbilityAction {
if (AbilityTargetHelper.isAlly(caster, (EntityLivingBase) barrierOwner)) continue;
}
if (barrier instanceof EntityAbilityDome) {
if (isDomeBlocking((EntityAbilityDome) barrier, caster, target)) return true;
} else if (barrier instanceof EntityAbilityPanel) {
if (isPanelBlocking((EntityAbilityPanel) barrier, caster, target)) return true;
if (barrier instanceof EntityEnergyDome) {
if (isDomeBlocking((EntityEnergyDome) barrier, caster, target)) return true;
} else if (barrier instanceof EntityEnergyPanel) {
if (isPanelBlocking((EntityEnergyPanel) barrier, caster, target)) return true;
}
}
@@ -2417,7 +2502,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
* Check if a dome blocks an attack from caster to target.
* Blocks when caster is outside and target is inside the dome.
*/
private static boolean isDomeBlocking(EntityAbilityDome dome, EntityLivingBase caster, EntityLivingBase target) {
private static boolean isDomeBlocking(EntityEnergyDome dome, EntityLivingBase caster, EntityLivingBase target) {
float radius = dome.getDomeRadius();
double cdx = caster.posX - dome.posX;
@@ -2438,7 +2523,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
* Check if a panel blocks an attack from caster to target.
* Checks if the line from caster to target crosses through the panel bounds.
*/
private static boolean isPanelBlocking(EntityAbilityPanel panel, EntityLivingBase caster, EntityLivingBase target) {
private static boolean isPanelBlocking(EntityEnergyPanel panel, EntityLivingBase caster, EntityLivingBase target) {
float halfW = panel.getPanelData().panelWidth * 0.5f;
float halfH = panel.getPanelData().panelHeight * 0.5f;
@@ -2497,11 +2582,35 @@ public abstract class Ability implements IAbility, IAbilityAction {
@Override
public INbt getNbt() {
return NpcAPI.Instance().getINbt(writeNBT());
return NpcAPI.Instance().getINbt(writeNBT(false));
}
@Override
public void setNbt(INbt nbt) {
readNBT(nbt.getMCNBT());
}
// ═══════════════════════════════════════════════════════════════════
// SCRIPT HANDLER
// ═══════════════════════════════════════════════════════════════════
public AbilityScript getScriptHandler() {
if (this.id == null || this.id.isEmpty()) return null;
return AbilityController.Instance.abilityScriptHandlers.get(this.id);
}
public void setScriptHandler(AbilityScript handler) {
if (this.id == null || this.id.isEmpty()) return;
AbilityController.Instance.abilityScriptHandlers.put(this.id, handler);
}
public AbilityScript getOrCreateScriptHandler() {
if (this.id == null || this.id.isEmpty()) return null;
AbilityScript handler = getScriptHandler();
if (handler == null) {
handler = new AbilityScript(this.id);
AbilityController.Instance.abilityScriptHandlers.put(this.id, handler);
}
return handler;
}
}
@@ -218,7 +218,7 @@ public class AbilityAction {
Ability resolved = getAbility();
if (resolved == null) return false;
inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT());
inlineAbility = AbilityController.Instance.fromNBT(resolved.writeNBT(true));
slotType = SlotType.INLINE_ABILITY;
referenceId = null;
cachedAction = null;
@@ -245,12 +245,12 @@ public class AbilityAction {
// NBT
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT() {
public NBTTagCompound writeNBT(boolean saveScripts) {
switch (slotType) {
case INLINE_CHAIN: {
NBTTagCompound nbt = new NBTTagCompound();
if (inlineChain != null) {
nbt.setTag("InlineChain", inlineChain.writeNBT());
nbt.setTag("InlineChain", inlineChain.writeNBT(saveScripts));
}
return nbt;
}
@@ -275,7 +275,7 @@ public class AbilityAction {
case INLINE_ABILITY:
default:
return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound();
return inlineAbility != null ? inlineAbility.writeNBT(saveScripts) : new NBTTagCompound();
}
}
@@ -0,0 +1,165 @@
package kamkeel.npcs.controllers.data.ability;
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.ICustomAbility;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.List;
/**
* A blank-slate ability that does nothing by itself.
* All behavior is driven by script event hooks (abilityStart, abilityTick, abilityComplete,
* abilityToggle, abilityToggleTick).
* <p>
* Supports two modes based on toggle configuration:
* <ul>
* <li><b>Instant mode</b> (toggleStates = 0): Uses standard execution lifecycle with
* configurable duration. Script hooks: abilityStart, abilityTick, abilityComplete.</li>
* <li><b>Toggle mode</b> (toggleStates >= 1): Uses toggle lifecycle.
* Script hooks: abilityToggle, abilityToggleTick.</li>
* </ul>
*/
public class CustomAbility extends Ability implements ICustomAbility {
private int durationTicks = 20;
public CustomAbility() {
this.typeId = "ability.cnpc.custom";
this.name = "Custom";
this.targetingMode = TargetingMode.SELF;
this.lockMovement = LockMode.NO;
this.cooldownTicks = 0;
this.windUpTicks = 0;
this.telegraphType = TelegraphType.NONE;
this.showTelegraph = false;
}
// ==================== EXECUTION ====================
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target) {
if (durationTicks <= 0) {
signalCompletion();
}
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
if (durationTicks > 0 && tick >= durationTicks) {
signalCompletion();
}
}
// ==================== PROPERTIES ====================
@Override
public boolean hasDamage() {
return false;
}
@Override
public boolean isConcurrentCapable() {
return true;
}
@Override
public boolean isTargetingModeLocked() {
return false;
}
@Override
public boolean allowFreeOnCast() {
return true;
}
// ==================== FIELDS ====================
@Override
public int getDurationTicks() {
return durationTicks;
}
@Override
public void setDurationTicks(int ticks) {
this.durationTicks = Math.max(0, ticks);
}
// ==================== ICustomAbility ====================
@Override
public int getTelegraphShapeType() {
return getTelegraphType().ordinal();
}
@Override
public void setTelegraphShapeType(int type) {
TelegraphType[] values = TelegraphType.values();
if (type >= 0 && type < values.length) {
setTelegraphType(values[type]);
}
}
@Override
public int getTargetingModeType() {
return getTargetingMode().ordinal();
}
@Override
public void setTargetingModeType(int type) {
TargetingMode[] values = TargetingMode.values();
if (type >= 0 && type < values.length) {
setTargetingMode(values[type]);
}
}
// ==================== NBT ====================
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("durationTicks", durationTicks);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.durationTicks = nbt.getInteger("durationTicks");
}
// ==================== GUI ====================
@Override
public void getAbilityDefinitions(List<FieldDef> defs) {
// User Type (NPC / Player / Both)
defs.add(FieldDef.enumField("ability.allowedBy", UserType.class,
this::getAllowedBy, this::setAllowedBy));
// Targeting Mode
defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class,
this::getTargetingMode, this::setTargetingMode));
// Telegraph Shape
defs.add(FieldDef.enumField("ability.telegraphShape", TelegraphType.class,
this::getTelegraphType, this::setTelegraphType));
// Toggle section
defs.add(FieldDef.section("ability.section.toggle"));
defs.add(FieldDef.boolField("ability.toggleEnabled",
this::isToggleable, enabled -> setToggleStates(enabled ? Math.max(1, getToggleStates()) : 0)));
defs.add(FieldDef.intField("ability.toggleStates", this::getToggleStates, this::setToggleStates)
.range(1, 10)
.visibleWhen(this::isToggleable));
defs.add(FieldDef.boolField("ability.hasActiveToggle", this::hasActiveToggle, this::setHasActiveToggle)
.visibleWhen(this::isToggleable));
// Duration (instant mode only)
defs.add(FieldDef.section("ability.section.execution")
.visibleWhen(() -> !this.isToggleable()));
defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks)
.range(0, 6000)
.visibleWhen(() -> !this.isToggleable()));
}
}
@@ -137,21 +137,19 @@ public class ConditionItem extends AbilityCondition {
this::getUsageType, this::setUsageType));
defs.add(FieldDef.stringField("condition.item_name",
this::getItemName, this::setItemName));
// .hover("condition.hover.item_name"));
this::getItemName, this::setItemName)
.hover("condition.hover.item_name"));
defs.add(FieldDef.enumField("condition.armor_slot", ArmorSlot.class,
this::getArmorSlot, this::setArmorSlot)
.visibleWhen(() -> usageType == UsageType.ARMOR));
// .hover("condition.hover.armor_slots"));
.visibleWhen(() -> usageType == UsageType.ARMOR)
.hover("condition.hover.armor_slots"));
defs.add(FieldDef.intField("condition.item_count",
this::getRequiredCount, this::setRequiredCount)
.range(1, 64)
.visibleWhen(() -> usageType == UsageType.AMMO && userType.allowsPlayer()));
// .hover("condition.hover.required_count"));
.visibleWhen(() -> usageType == UsageType.AMMO && userType.allowsPlayer())
.hover("condition.hover.required_count"));
}
@SideOnly(Side.CLIENT)
@@ -6,24 +6,72 @@ import net.minecraft.nbt.NBTTagList;
/**
* Icon data for abilities, stored in the ability's customData NBT under "AbilityIcon".
* Used to render ability icons in the Ability Hotbar, Wheel, and Abilities Tab.
* Supports up to 3 layers, each with its own texture, UV coordinates, and tint color.
* Width, height, and scale are shared across all layers.
*/
public class AbilityIconData {
public static final String NBT_KEY = "AbilityIcon";
public static final int MAX_LAYERS = 3;
private final NBTTagCompound customData;
// Icon properties
public String texture = "";
public int iconX = 0;
public int iconY = 0;
// Shared across all layers
public int width = 32;
public int height = 32;
public float scale = 1.0f;
/** Per-state icon UV overrides (0-indexed, maps to toggle states 1, 2, ...). */
/** Whether a custom icon override is active. Default false = use type's default icon. */
private boolean enabled = false;
/** Number of active layers (1-3). */
private int layerCount = 1;
/** Layer data (always 3 slots allocated). */
private Layer[] layers = { new Layer(), new Layer(), new Layer() };
/** Per-state icon UV overrides for layer 0 (0-indexed, maps to toggle states 1, 2, ...). */
private int[][] stateIcons = null;
// Animation
private boolean animated = false;
private int frameCount = 1;
private int frametime = 2;
// ═══════════════════════════════════════════════════════════════════
// LAYER INNER CLASS
// ═══════════════════════════════════════════════════════════════════
public static class Layer {
public String texture = "";
public int iconX = 0;
public int iconY = 0;
public int tintColor = 0xFFFFFF;
public Layer() {}
public boolean hasTexture() {
return texture != null && !texture.isEmpty();
}
public void writeToNBT(NBTTagCompound nbt) {
nbt.setString("Texture", texture);
nbt.setInteger("IconX", iconX);
nbt.setInteger("IconY", iconY);
nbt.setInteger("TintColor", tintColor);
}
public void readFromNBT(NBTTagCompound nbt) {
texture = nbt.getString("Texture");
iconX = nbt.getInteger("IconX");
iconY = nbt.getInteger("IconY");
tintColor = nbt.hasKey("TintColor") ? nbt.getInteger("TintColor") : 0xFFFFFF;
}
}
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTION
// ═══════════════════════════════════════════════════════════════════
private AbilityIconData(NBTTagCompound customData) {
this.customData = customData;
}
@@ -54,6 +102,10 @@ public class AbilityIconData {
return fromCustomData(chain.getCustomData());
}
// ═══════════════════════════════════════════════════════════════════
// NBT SERIALIZATION
// ═══════════════════════════════════════════════════════════════════
/**
* Write current state back to the customData NBT.
*/
@@ -64,12 +116,24 @@ public class AbilityIconData {
}
public void writeToNBT(NBTTagCompound nbt) {
nbt.setString("Texture", texture);
nbt.setInteger("IconX", iconX);
nbt.setInteger("IconY", iconY);
nbt.setBoolean("Enabled", enabled);
nbt.setInteger("Width", width);
nbt.setInteger("Height", height);
nbt.setFloat("Scale", scale);
nbt.setInteger("LayerCount", layerCount);
NBTTagList layerList = new NBTTagList();
for (int i = 0; i < MAX_LAYERS; i++) {
NBTTagCompound layerNBT = new NBTTagCompound();
layers[i].writeToNBT(layerNBT);
layerList.appendTag(layerNBT);
}
nbt.setTag("Layers", layerList);
nbt.setBoolean("Animated", animated);
nbt.setInteger("FrameCount", frameCount);
nbt.setInteger("FrameTime", frametime);
if (stateIcons != null && stateIcons.length > 0) {
NBTTagList list = new NBTTagList();
for (int[] pair : stateIcons) {
@@ -83,15 +147,35 @@ public class AbilityIconData {
}
public void readFromNBT(NBTTagCompound nbt) {
texture = nbt.getString("Texture");
iconX = nbt.getInteger("IconX");
iconY = nbt.getInteger("IconY");
enabled = nbt.getBoolean("Enabled");
width = nbt.getInteger("Width");
if (width <= 0) width = 32;
height = nbt.getInteger("Height");
if (height <= 0) height = 32;
scale = nbt.getFloat("Scale");
if (scale <= 0) scale = 1.0f;
layerCount = nbt.getInteger("LayerCount");
if (layerCount < 1) layerCount = 1;
if (layerCount > MAX_LAYERS) layerCount = MAX_LAYERS;
if (nbt.hasKey("Animated"))
animated = nbt.getBoolean("Animated");
if (nbt.hasKey("FrameCount"))
frameCount = Math.max(1, nbt.getInteger("FrameCount"));
if (nbt.hasKey("FrameTime"))
frametime = Math.max(1, nbt.getInteger("FrameTime"));
if (nbt.hasKey("Layers")) {
NBTTagList layerList = nbt.getTagList("Layers", 10);
for (int i = 0; i < MAX_LAYERS; i++) {
layers[i] = new Layer();
if (i < layerList.tagCount()) {
layers[i].readFromNBT(layerList.getCompoundTagAt(i));
}
}
}
if (nbt.hasKey("StateIcons")) {
NBTTagList list = nbt.getTagList("StateIcons", 10);
stateIcons = new int[list.tagCount()][2];
@@ -103,41 +187,61 @@ public class AbilityIconData {
}
}
/**
* Check if this icon has a valid texture configured.
*/
public boolean hasTexture() {
return texture != null && !texture.isEmpty();
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS AND SETTERS (with auto-save)
// LAYER API
// ═══════════════════════════════════════════════════════════════════
public String getTexture() {
return texture;
public int getLayerCount() {
return layerCount;
}
public void setTexture(String texture) {
this.texture = texture != null ? texture : "";
public void setLayerCount(int count) {
this.layerCount = Math.max(1, Math.min(MAX_LAYERS, count));
save();
}
public int getIconX() {
return iconX;
public Layer getLayer(int index) {
return (index >= 0 && index < MAX_LAYERS) ? layers[index] : layers[0];
}
public void setIconX(int iconX) {
this.iconX = Math.max(0, iconX);
save();
public void setLayerTexture(int index, String tex) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].texture = tex != null ? tex : "";
save();
}
}
public int getIconY() {
return iconY;
public void setLayerIconX(int index, int x) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].iconX = Math.max(0, x);
save();
}
}
public void setIconY(int iconY) {
this.iconY = Math.max(0, iconY);
public void setLayerIconY(int index, int y) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].iconY = Math.max(0, y);
save();
}
}
public void setLayerTintColor(int index, int color) {
if (index >= 0 && index < MAX_LAYERS) {
layers[index].tintColor = color & 0xFFFFFF;
save();
}
}
// ═══════════════════════════════════════════════════════════════════
// SHARED PROPERTY GETTERS/SETTERS (with auto-save)
// ═══════════════════════════════════════════════════════════════════
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
save();
}
@@ -169,7 +273,38 @@ public class AbilityIconData {
}
// ═══════════════════════════════════════════════════════════════════
// PER-STATE ICON OVERRIDES
// ANIMATION
// ═══════════════════════════════════════════════════════════════════
public boolean isAnimated() {
return animated;
}
public void setAnimated(boolean animated) {
this.animated = animated;
save();
}
public int getFrameCount() {
return frameCount;
}
public void setFrameCount(int frameCount) {
this.frameCount = Math.max(1, frameCount);
save();
}
public int getFrameTime() {
return frametime;
}
public void setFrameTime(int frametime) {
this.frametime = Math.max(1, frametime);
save();
}
// ═══════════════════════════════════════════════════════════════════
// PER-STATE ICON OVERRIDES (applies to layer 0)
// ═══════════════════════════════════════════════════════════════════
public void setStateIcons(int[][] stateIcons) {
@@ -178,26 +313,26 @@ public class AbilityIconData {
}
/**
* Get iconX for a specific toggle state.
* Falls back to default iconX if no state override exists.
* Get iconX for a specific toggle state (layer 0).
* Falls back to layer 0 iconX if no state override exists.
* @param state 1-indexed toggle state (0 = off/default)
*/
public int getIconXForState(int state) {
if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) {
return stateIcons[state - 1][0];
}
return iconX;
return layers[0].iconX;
}
/**
* Get iconY for a specific toggle state.
* Falls back to default iconY if no state override exists.
* Get iconY for a specific toggle state (layer 0).
* Falls back to layer 0 iconY if no state override exists.
* @param state 1-indexed toggle state (0 = off/default)
*/
public int getIconYForState(int state) {
if (state > 0 && stateIcons != null && state - 1 < stateIcons.length) {
return stateIcons[state - 1][1];
}
return iconY;
return layers[0].iconY;
}
}
@@ -2,6 +2,7 @@ package kamkeel.npcs.controllers.data.ability.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
@@ -358,7 +359,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
*/
public ChainedAbility deepCopy() {
ChainedAbility copy = new ChainedAbility();
copy.readNBT(this.writeNBT());
copy.readNBT(this.writeNBT(true));
return copy;
}
@@ -376,7 +377,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
// NBT SERIALIZATION
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT() {
public NBTTagCompound writeNBT(boolean saveScripts) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("Id", id);
nbt.setString("Name", name);
@@ -398,13 +399,23 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
// Entries
NBTTagList entryList = new NBTTagList();
for (ChainedAbilityEntry entry : entries) {
entryList.appendTag(entry.writeNBT());
entryList.appendTag(entry.writeNBT(saveScripts));
}
nbt.setTag("Entries", entryList);
// Custom data (for external mods)
nbt.setTag("customData", (NBTTagCompound) customData.copy());
// Script handler data (matching CustomEffect.writeToNBT pattern)
if (saveScripts) {
ChainedAbilityScript handler = getScriptHandler();
if (handler != null) {
NBTTagCompound scriptData = new NBTTagCompound();
handler.writeToNBT(scriptData);
nbt.setTag("ScriptData", scriptData);
}
}
return nbt;
}
@@ -418,7 +429,7 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
cooldownTicks = nbt.hasKey("CooldownTicks") ? nbt.getInteger("CooldownTicks") : 100;
minRange = nbt.getFloat("MinRange");
maxRange = nbt.hasKey("MaxRange") ? nbt.getFloat("MaxRange") : 20;
// AllowedBy is computed from child abilities — old NBT data silently ignored
// AllowedBy is computed from child abilities
// Conditions
conditions.clear();
@@ -442,5 +453,33 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
// Custom data (for external mods)
customData = (NBTTagCompound) nbt.getCompoundTag("customData").copy();
// Script handler data (matching CustomEffect.readFromNBT pattern)
if (nbt.hasKey("ScriptData", 10)) {
ChainedAbilityScript handler = new ChainedAbilityScript(this.id);
handler.readFromNBT(nbt.getCompoundTag("ScriptData"));
setScriptHandler(handler);
}
}
// ═══════════════════════════════════════════════════════════════════
// SCRIPT HANDLER
// ═══════════════════════════════════════════════════════════════════
public ChainedAbilityScript getScriptHandler() {
return AbilityController.Instance.chainedAbilityScriptHandlers.get(this.id);
}
public void setScriptHandler(ChainedAbilityScript handler) {
AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler);
}
public ChainedAbilityScript getOrCreateScriptHandler() {
ChainedAbilityScript handler = getScriptHandler();
if (handler == null) {
handler = new ChainedAbilityScript(this.id);
AbilityController.Instance.chainedAbilityScriptHandlers.put(this.id, handler);
}
return handler;
}
}
@@ -50,5 +50,5 @@ public interface IAbilityAction {
*/
IAbilityAction deepCopyAction();
NBTTagCompound writeNBT();
NBTTagCompound writeNBT(boolean saveScripts);
}
@@ -40,6 +40,7 @@ public class EnergyBarrierData {
// Reflection: rebound projectiles that fail to break the barrier
public boolean reflect = false;
public float reflectStrengthPct = 25.0f;
public boolean targetOwner = false;
/**
* Per-projectile-type damage multipliers.
@@ -139,6 +140,14 @@ public class EnergyBarrierData {
this.reflectStrengthPct = Math.max(0.0f, Math.min(100.0f, reflectStrengthPct));
}
public boolean isTargetOwner() {
return targetOwner;
}
public void setTargetOwner(boolean targetOwner) {
this.targetOwner = targetOwner;
}
// ==================== NBT ====================
public void writeNBT(NBTTagCompound nbt) {
@@ -155,6 +164,7 @@ public class EnergyBarrierData {
nbt.setFloat("barrierMeleeMult", meleeDamageMultiplier);
nbt.setBoolean("barrierReflect", reflect);
nbt.setFloat("barrierReflectStrPct", reflectStrengthPct);
nbt.setBoolean("barrierTargetOwner", targetOwner);
NBTTagCompound multNbt = new NBTTagCompound();
for (Map.Entry<String, Float> entry : damageMultipliers.entrySet()) {
@@ -177,6 +187,7 @@ public class EnergyBarrierData {
meleeDamageMultiplier = nbt.hasKey("barrierMeleeMult") ? nbt.getFloat("barrierMeleeMult") : 1.0f;
reflect = nbt.hasKey("barrierReflect") && nbt.getBoolean("barrierReflect");
setReflectStrengthPct(nbt.hasKey("barrierReflectStrPct") ? nbt.getFloat("barrierReflectStrPct") : 25.0f);
targetOwner = nbt.hasKey("barrierTargetOwner") && nbt.getBoolean("barrierTargetOwner");
damageMultipliers.clear();
if (nbt.hasKey("barrierMultipliers")) {
@@ -200,6 +211,7 @@ public class EnergyBarrierData {
copy.meleeDamageMultiplier = meleeDamageMultiplier;
copy.reflect = reflect;
copy.reflectStrengthPct = reflectStrengthPct;
copy.targetOwner = targetOwner;
copy.damageMultipliers = new HashMap<>(damageMultipliers);
return copy;
}
@@ -16,10 +16,6 @@ public class EnergyDisplayData implements IEnergyDisplayData {
public float innerAlpha = 1.0f;
public float rotationSpeed = 4.0f;
// TODO: Skybox Feature
// public boolean skyboxEnabled = false;
// public String skyboxTexture = "";
public EnergyDisplayData() {
}
@@ -122,9 +118,6 @@ public class EnergyDisplayData implements IEnergyDisplayData {
nbt.setFloat("outerColorAlpha", outerColorAlpha);
nbt.setFloat("innerAlpha", innerAlpha);
nbt.setFloat("rotationSpeed", rotationSpeed);
// TODO: Skybox Feature
// nbt.setBoolean("skyboxEnabled", skyboxEnabled);
// nbt.setString("skyboxTexture", skyboxTexture);
}
public void readNBT(NBTTagCompound nbt) {
@@ -135,16 +128,10 @@ public class EnergyDisplayData implements IEnergyDisplayData {
outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f;
innerAlpha = nbt.hasKey("innerAlpha") ? nbt.getFloat("innerAlpha") : 1.0f;
rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f;
// TODO: Skybox Feature
// skyboxEnabled = nbt.hasKey("skyboxEnabled") && nbt.getBoolean("skyboxEnabled");
// skyboxTexture = nbt.hasKey("skyboxTexture") ? nbt.getString("skyboxTexture") : "";
}
public EnergyDisplayData copy() {
EnergyDisplayData copy = new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, innerAlpha, rotationSpeed);
// TODO: Skybox Feature
// copy.skyboxEnabled = skyboxEnabled;
// copy.skyboxTexture = skyboxTexture;
return copy;
}
}
@@ -10,6 +10,8 @@ public class EnergyPanelData {
public float panelWidth = 3.0f;
public float panelHeight = 3.0f;
public float heightOffset = 0.0f;
public float offsetX = 0.0f;
public float offsetZ = 0.0f;
// Launch properties (Wall only)
public boolean launching = false;
@@ -90,6 +92,8 @@ public class EnergyPanelData {
nbt.setFloat("panelWidth", panelWidth);
nbt.setFloat("panelHeight", panelHeight);
nbt.setFloat("panelHeightOffset", heightOffset);
nbt.setFloat("panelOffsetX", offsetX);
nbt.setFloat("panelOffsetZ", offsetZ);
nbt.setBoolean("panelLaunching", launching);
nbt.setFloat("panelLaunchSpeed", launchSpeed);
nbt.setFloat("panelLaunchDamage", launchDamage);
@@ -100,6 +104,8 @@ public class EnergyPanelData {
panelWidth = nbt.hasKey("panelWidth") ? nbt.getFloat("panelWidth") : 3.0f;
panelHeight = nbt.hasKey("panelHeight") ? nbt.getFloat("panelHeight") : 3.0f;
heightOffset = nbt.hasKey("panelHeightOffset") ? nbt.getFloat("panelHeightOffset") : 0.0f;
offsetX = nbt.hasKey("panelOffsetX") ? nbt.getFloat("panelOffsetX") : 0.0f;
offsetZ = nbt.hasKey("panelOffsetZ") ? nbt.getFloat("panelOffsetZ") : 0.0f;
launching = nbt.hasKey("panelLaunching") && nbt.getBoolean("panelLaunching");
launchSpeed = nbt.hasKey("panelLaunchSpeed") ? nbt.getFloat("panelLaunchSpeed") : 0.5f;
launchDamage = nbt.hasKey("panelLaunchDamage") ? nbt.getFloat("panelLaunchDamage") : 8.0f;
@@ -108,6 +114,8 @@ public class EnergyPanelData {
public EnergyPanelData copy() {
EnergyPanelData copy = new EnergyPanelData(panelWidth, panelHeight, heightOffset);
copy.offsetX = offsetX;
copy.offsetZ = offsetZ;
copy.launching = launching;
copy.launchSpeed = launchSpeed;
copy.launchDamage = launchDamage;
@@ -155,7 +155,7 @@ public class ChainedAbilityEntry {
Ability resolved = ctrl.resolveAbility(abilityReference);
if (resolved == null) return false;
inlineAbility = ctrl.fromNBT(resolved.writeNBT());
inlineAbility = ctrl.fromNBT(resolved.writeNBT(true));
entryType = EntryType.INLINE;
abilityReference = "";
return true;
@@ -175,22 +175,22 @@ public class ChainedAbilityEntry {
copy.delayTicks = this.delayTicks;
copy.concurrentEnabled = this.concurrentEnabled;
if (this.inlineAbility != null) {
copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT());
copy.inlineAbility = AbilityController.Instance.fromNBT(this.inlineAbility.writeNBT(true));
}
return copy;
}
// ═══════════════════════════════════════════════════════════════════
// NBT (backwards compatible)
// NBT
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeNBT() {
public NBTTagCompound writeNBT(boolean saveScripts) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("Delay", delayTicks);
nbt.setBoolean("Concurrent", concurrentEnabled);
if (entryType == EntryType.INLINE && inlineAbility != null) {
nbt.setTag("InlineAbility", inlineAbility.writeNBT());
nbt.setTag("InlineAbility", inlineAbility.writeNBT(saveScripts));
} else {
nbt.setString("Reference", abilityReference);
}
@@ -204,14 +204,12 @@ public class ChainedAbilityEntry {
entry.delayTicks = Math.max(0, nbt.getInteger("Delay"));
entry.concurrentEnabled = nbt.hasKey("Concurrent") ? nbt.getBoolean("Concurrent") : true;
// Inline entry (new format)
if (nbt.hasKey("InlineAbility")) {
NBTTagCompound abilityNBT = nbt.getCompoundTag("InlineAbility");
entry.entryType = EntryType.INLINE;
entry.inlineAbility = AbilityController.Instance != null
? AbilityController.Instance.fromNBT(abilityNBT) : null;
} else {
// Reference entry (old + new format)
entry.entryType = EntryType.REFERENCE;
entry.abilityReference = nbt.getString("Reference");
}
@@ -137,7 +137,7 @@ public class AbilityPreviewExecutor implements PreviewEntityHandler {
for (ChainedAbilityEntry entry : chain.getEntries()) {
Ability resolved = entry.resolve();
if (resolved != null && AbilityController.Instance != null) {
Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT());
Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT(true));
if (copy != null) {
chainAbilities.add(copy);
chainDelays.add(entry.getDelayTicks());
@@ -53,6 +53,9 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
this.activeSound = "mob.zombie.attack";
this.windUpAnimationName = "Ability_Charge_Windup";
this.activeAnimationName = "Ability_Charge_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/charge.png")
};
}
@Override
@@ -0,0 +1,215 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.addon.DBCAddon;
import noppes.npcs.controllers.AnimationController;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import noppes.npcs.NpcDamageSource;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.api.ability.type.IAbilityCounter;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.Arrays;
import java.util.List;
/**
* Counter ability: Absorbs incoming damage and counter-attacks the attacker.
*/
public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
private CounterType counterType = CounterType.FLAT;
private float counterValue = 6.0f;
private int counterAnimationId = -1;
private String counterAnimationName = "Ability_Guard_Counter";
public AbilityCounter() {
this.typeId = "ability.cnpc.counter";
this.name = "Counter";
this.cooldownTicks = 0;
this.windUpTicks = 20;
this.allowedBy = UserType.BOTH;
this.activeSound = "random.anvil_land";
this.activeAnimationName = "Ability_Guard_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png")
};
}
public enum CounterType {
FLAT,
PERCENT;
@Override
public String toString() {
switch (this) {
case FLAT:
return "ability.counter.flat";
case PERCENT:
return "ability.counter.percent";
default:
return name();
}
}
}
// ═══════════════════════════════════════════════════════════════════
// DEFEND HOOKS
// ═══════════════════════════════════════════════════════════════════
@Override
protected float performDefend(EntityLivingBase attacker, float amount) {
// Calculate counter damage
float damage;
if (counterType == CounterType.FLAT) {
damage = counterValue;
} else {
damage = amount * (counterValue / 100.0f);
}
// Hit back
if (caster != null && attacker.isEntityAlive()) {
if (caster instanceof EntityNPCInterface && DBCAddon.instance.canDBCAttack((EntityNPCInterface) caster, damage, attacker)) {
// NPC with DBC: dummy hit for events/knockback, then apply DBC damage with NPC's stats
attacker.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), 0.001f);
DBCAddon.instance.doDBCDamage((EntityNPCInterface) caster, damage, attacker);
} else {
// Player or non-DBC NPC: normal damage
DamageSource counterSource = caster instanceof EntityPlayer
? DamageSource.causePlayerDamage((EntityPlayer) caster)
: DamageSource.causeMobDamage(caster);
attacker.attackEntityFrom(counterSource, damage);
}
}
return 0;
}
// ═══════════════════════════════════════════════════════════════════
// OVERRIDES
// ═══════════════════════════════════════════════════════════════════
@Override
public boolean hasDamage() {
return true;
}
@Override
protected Animation getDefendAnimation() {
return getCounterAnimation();
}
public Animation getCounterAnimation() {
if (AnimationController.Instance == null) return null;
if (counterAnimationId >= 0) {
return (Animation) AnimationController.Instance.get(counterAnimationId);
}
if (counterAnimationName != null && !counterAnimationName.isEmpty()) {
return (Animation) AnimationController.Instance.get(counterAnimationName, true);
}
return null;
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
@Override
protected void writeSubTypeNBT(NBTTagCompound nbt) {
nbt.setString("counterType", counterType.name());
nbt.setFloat("counterValue", counterValue);
nbt.setInteger("counterAnimationId", counterAnimationId);
nbt.setString("counterAnimationName", resolveAnimationName(counterAnimationId, counterAnimationName));
}
@Override
protected void readSubTypeNBT(NBTTagCompound nbt) {
try {
this.counterType = CounterType.valueOf(nbt.getString("counterType"));
} catch (Exception e) {
this.counterType = CounterType.FLAT;
}
this.counterValue = nbt.getFloat("counterValue");
this.counterAnimationId = nbt.getInteger("counterAnimationId");
this.counterAnimationName = nbt.getString("counterAnimationName");
}
// ═══════════════════════════════════════════════════════════════════
// GUI
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
protected void getTypeDefinitions(List<FieldDef> defs) {
defs.addAll(Arrays.asList(
FieldDef.enumField("gui.type", CounterType.class, this::getCounterTypeEnum, this::setCounterTypeEnum)
.hover("ability.hover.counterType"),
FieldDef.floatField("gui.value", this::getCounterValue, this::setCounterValue),
AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)
));
FieldDef.insertAfter(defs, "ability.dazedAnimation",
FieldDef.animSubGui("ability.counterAnimation",
this::getCounterAnimationId, this::setCounterAnimationId,
this::getCounterAnimationName, this::setCounterAnimationName)
.tab("Effects"));
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
public CounterType getCounterTypeEnum() {
return counterType;
}
public void setCounterTypeEnum(CounterType counterType) {
this.counterType = counterType;
}
@Override
public int getCounterType() {
return counterType.ordinal();
}
@Override
public void setCounterType(int type) {
CounterType[] values = CounterType.values();
this.counterType = type >= 0 && type < values.length ? values[type] : CounterType.FLAT;
}
@Override
public float getCounterValue() {
return counterValue;
}
@Override
public void setCounterValue(float counterValue) {
this.counterValue = counterValue;
}
@Override
public int getCounterAnimationId() {
return counterAnimationId;
}
@Override
public void setCounterAnimationId(int counterAnimationId) {
this.counterAnimationId = counterAnimationId;
}
public String getCounterAnimationName() {
return counterAnimationName;
}
public void setCounterAnimationName(String name) {
this.counterAnimationName = name != null ? name : "";
}
}
@@ -79,6 +79,10 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
this.activeSound = "random.break";
this.windUpAnimationName = "Ability_Cutter_Windup";
this.activeAnimationName = "Ability_Cutter_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/cutter.png",
this::getActiveColor)
};
}
@Override
@@ -294,12 +298,6 @@ public class AbilityCutter extends Ability implements IAbilityCutter {
return entityRelative >= minAngle && entityRelative <= maxAngle;
}
private boolean isInArc(double dx, double dz, float casterYaw, float arcWidth) {
double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz));
double angleDiff = normalizeAngle(angleToEntity - casterYaw);
return Math.abs(angleDiff) <= arcWidth / 2.0;
}
private double normalizeAngle(double angle) {
while (angle > 180) angle -= 360;
while (angle < -180) angle += 360;
@@ -144,6 +144,9 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash {
this.telegraphType = TelegraphType.NONE;
this.showTelegraph = false;
this.windUpSound = "mob.bat.takeoff";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/dash.png")
};
}
@Override
@@ -302,7 +305,7 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash {
this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f;
this.dashSpeed = nbt.hasKey("dashSpeed") ? Math.max(0.01f, nbt.getFloat("dashSpeed")) : 0.5f;
this.dashAngle = nbt.hasKey("dashAngle") ? Math.max(0.01f, nbt.getFloat("dashAngle")) : 0.0f;
this.dashAngle = nbt.hasKey("dashAngle") ? nbt.getFloat("dashAngle") : 0.0f;
}
// Getters & Setters
@@ -394,7 +397,7 @@ public class AbilityDash extends AbilityMovement implements IAbilityDash {
FieldDef.row(
FieldDef.enumField("ability.dashDirection", DashDirection.class, this::getDashDirectionEnum, this::setDashDirectionEnum),
FieldDef.floatField("ability.dashAngle", this::getDashAngle, this::setDashAngle)
.visibleWhen(() -> getDashDirectionEnum() == DashDirection.CUSTOM)
.min(Float.NEGATIVE_INFINITY).visibleWhen(() -> getDashDirectionEnum() == DashDirection.CUSTOM)
).visibleWhen(() -> this.getDashModeEnum() == DashMode.DIRECTIONAL)
));
}
@@ -0,0 +1,299 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import noppes.npcs.api.ability.type.IAbilityDefend;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.controllers.data.Animation;
import java.util.List;
/**
* Abstract base class for defensive abilities (Guard, Counter, Dodge).
* <p>
* {@link #onDefend} handles shared checks (physical melee only) then delegates
* to {@link #performDefend(EntityLivingBase, float)} which subclasses override for their specific behavior.
*/
public abstract class AbilityDefend extends Ability implements IAbilityDefend {
// ═══════════════════════════════════════════════════════════════════
// SHARED PERSIST STATE
// ═══════════════════════════════════════════════════════════════════
protected int durationTicks = 60;
protected int maxHitAmount = 3;
// ═══════════════════════════════════════════════════════════════════
// TRANSIENT RUNTIME STATE
// ═══════════════════════════════════════════════════════════════════
protected transient EntityLivingBase caster;
protected transient int hitCount;
protected transient EntityLivingBase lastAttacker;
protected transient float lastDamageTaken;
protected transient Animation pendingDefendAnimation;
protected transient int defendAnimEndTick = -1;
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR DEFAULTS
// ═══════════════════════════════════════════════════════════════════
protected AbilityDefend() {
this.targetingMode = TargetingMode.SELF;
this.lockMovement = LockMode.ACTIVE;
this.interruptible = false;
this.telegraphType = TelegraphType.NONE;
this.showTelegraph = false;
this.windUpTicks = 0;
}
// ═══════════════════════════════════════════════════════════════════
// LIFECYCLE
// ═══════════════════════════════════════════════════════════════════
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target) {
this.caster = caster;
hitCount = 0;
lastAttacker = null;
lastDamageTaken = 0.0f;
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
if (tick >= durationTicks) {
signalCompletion();
}
}
@Override
public void reset() {
super.reset();
caster = null;
hitCount = 0;
lastAttacker = null;
lastDamageTaken = 0.0f;
pendingDefendAnimation = null;
defendAnimEndTick = -1;
}
// ═══════════════════════════════════════════════════════════════════
// DEFEND HOOK
// ═══════════════════════════════════════════════════════════════════
/**
* Called when the caster is hit while defending.
* Checks for physical melee damage only, then delegates to {@link #performDefend(float)}.
*
* @param attacker The entity that hit the caster
* @param source The damage source
* @param amount The original incoming damage
* @return The modified damage to apply (unchanged if not physical melee)
*/
public final float onDefend(EntityLivingBase attacker, DamageSource source, float amount) {
if (!isDefending())
return amount;
if (attacker == null || source == null)
return amount;
// Only react to physical melee damage
if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion() || source.isProjectile())
return amount;
lastAttacker = attacker;
lastDamageTaken = amount;
hitCount++;
float result = performDefend(attacker, amount);
// Queue defend reaction animation (played on next tick by AbstractDataAbilities)
pendingDefendAnimation = getDefendAnimation();
// Auto-complete after max hits
if (maxHitAmount > 0 && hitCount >= maxHitAmount) {
signalCompletion();
}
return result;
}
/**
* Subclass-specific defend behavior. Called only for physical melee hits while defending.
*
* @param attacker The entity that hit the caster
* @param amount The incoming damage
* @return The modified damage the caster should take
*/
protected abstract float performDefend(EntityLivingBase attacker, float amount);
// ═══════════════════════════════════════════════════════════════════
// SUBCLASS HOOKS
// ═══════════════════════════════════════════════════════════════════
/**
* Subclass-specific NBT persistence.
*/
protected abstract void writeSubTypeNBT(NBTTagCompound nbt);
protected abstract void readSubTypeNBT(NBTTagCompound nbt);
@SideOnly(Side.CLIENT)
protected abstract void getTypeDefinitions(List<FieldDef> defs);
// ═══════════════════════════════════════════════════════════════════
// DEFEND ANIMATION
// ═══════════════════════════════════════════════════════════════════
/**
* Returns the animation to play when this defend ability reacts to a hit.
* Subclasses override to provide their specific animation (counter strike, dodge roll, etc).
* Guard returns null (no reaction animation).
*/
protected Animation getDefendAnimation() {
return null;
}
/**
* Consume and return the pending defend animation (set during onDefend).
* Called by AbstractDataAbilities to play the animation on the next tick.
*/
public Animation consumeDefendAnimation() {
Animation anim = pendingDefendAnimation;
pendingDefendAnimation = null;
return anim;
}
/**
* Schedule return to active animation after the defend animation finishes.
*/
public void scheduleReturnToActive(int currentTick, Animation defendAnim) {
if (defendAnim != null) {
defendAnimEndTick = currentTick + (int) defendAnim.getTotalTime();
}
}
/**
* Check if the defend animation has finished and we should return to the active animation.
*/
public boolean shouldReturnToActiveAnimation(int currentTick) {
if (defendAnimEndTick >= 0 && currentTick >= defendAnimEndTick) {
defendAnimEndTick = -1;
return true;
}
return false;
}
// ═══════════════════════════════════════════════════════════════════
// STATE QUERIES
// ═══════════════════════════════════════════════════════════════════
@Override
public boolean isDefending() {
return isExecuting() && getPhase() == AbilityPhase.ACTIVE;
}
// ═══════════════════════════════════════════════════════════════════
// OVERRIDES
// ═══════════════════════════════════════════════════════════════════
@Override
public boolean hasDamage() {
return false;
}
@Override
public boolean allowBurst() {
return false;
}
@Override
public boolean isTargetingModeLocked() {
return true;
}
@Override
public TargetingMode[] getAllowedTargetingModes() {
return new TargetingMode[]{TargetingMode.SELF};
}
@Override
public float getTelegraphRadius() {
return 0;
}
/**
* Suppresses the auto-play of activeSound on ACTIVE phase entry.
* Defend abilities play their sound on hit reaction, not on phase start.
*/
@Override
public boolean keepTelegraphDuringActive() {
return true;
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
@Override
public final void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("durationTicks", durationTicks);
nbt.setInteger("maxHitAmount", maxHitAmount);
writeSubTypeNBT(nbt);
}
@Override
public final void readTypeNBT(NBTTagCompound nbt) {
this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60;
this.maxHitAmount = nbt.hasKey("maxHitAmount") ? nbt.getInteger("maxHitAmount") : 3;
readSubTypeNBT(nbt);
}
// ═══════════════════════════════════════════════════════════════════
// GUI
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
public final void getAbilityDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 6000));
defs.add(FieldDef.intField("ability.maxHitAmount", this::getMaxHitAmount, this::setMaxHitAmount).range(0, 100)
.hover("ability.hover.maxHitAmount"));
getTypeDefinitions(defs);
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
@Override
public int getDurationTicks() {
return durationTicks;
}
@Override
public void setDurationTicks(int ticks) {
this.durationTicks = Math.max(1, ticks);
}
@Override
public int getMaxHitAmount() {
return maxHitAmount;
}
@Override
public void setMaxHitAmount(int amount) {
this.maxHitAmount = Math.max(0, amount);
}
public int getHitCount() {
return hitCount;
}
}
@@ -0,0 +1,195 @@
package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import noppes.npcs.controllers.AnimationController;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.api.ability.type.IAbilityDodge;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.ArrayList;
import java.util.List;
/**
* Dodge ability: Completely cancels incoming attacks and plays a random dodge animation.
*/
public class AbilityDodge extends AbilityDefend implements IAbilityDodge {
private int dodgeAnimation1Id = -1;
private String dodgeAnimation1Name = "";
private int dodgeAnimation2Id = -1;
private String dodgeAnimation2Name = "";
private int dodgeAnimation3Id = -1;
private String dodgeAnimation3Name = "";
public AbilityDodge() {
this.typeId = "ability.cnpc.dodge";
this.name = "Dodge";
this.cooldownTicks = 0;
this.windUpTicks = 10;
this.allowedBy = UserType.BOTH;
this.activeAnimationName = "";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png")
};
}
// ═══════════════════════════════════════════════════════════════════
// DEFEND HOOKS
// ═══════════════════════════════════════════════════════════════════
@Override
protected float performDefend(EntityLivingBase attacker, float amount) {
return 0;
}
@Override
protected Animation getDefendAnimation() {
return getRandomDodgeAnimation();
}
/**
* Returns a random dodge animation from the configured slots (non-empty only).
*/
public Animation getRandomDodgeAnimation() {
if (AnimationController.Instance == null) return null;
List<Animation> available = new ArrayList<>();
Animation a1 = getDodgeAnimation(dodgeAnimation1Id, dodgeAnimation1Name);
Animation a2 = getDodgeAnimation(dodgeAnimation2Id, dodgeAnimation2Name);
Animation a3 = getDodgeAnimation(dodgeAnimation3Id, dodgeAnimation3Name);
if (a1 != null) available.add(a1);
if (a2 != null) available.add(a2);
if (a3 != null) available.add(a3);
if (available.isEmpty()) return null;
return available.get((int) (Math.random() * available.size()));
}
private Animation getDodgeAnimation(int id, String name) {
if (id >= 0) {
return (Animation) AnimationController.Instance.get(id);
}
if (name != null && !name.isEmpty()) {
return (Animation) AnimationController.Instance.get(name, true);
}
return null;
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
@Override
protected void writeSubTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("dodgeAnimation1Id", dodgeAnimation1Id);
nbt.setString("dodgeAnimation1Name", resolveAnimationName(dodgeAnimation1Id, dodgeAnimation1Name));
nbt.setInteger("dodgeAnimation2Id", dodgeAnimation2Id);
nbt.setString("dodgeAnimation2Name", resolveAnimationName(dodgeAnimation2Id, dodgeAnimation2Name));
nbt.setInteger("dodgeAnimation3Id", dodgeAnimation3Id);
nbt.setString("dodgeAnimation3Name", resolveAnimationName(dodgeAnimation3Id, dodgeAnimation3Name));
}
@Override
protected void readSubTypeNBT(NBTTagCompound nbt) {
this.dodgeAnimation1Id = nbt.getInteger("dodgeAnimation1Id");
this.dodgeAnimation1Name = nbt.getString("dodgeAnimation1Name");
this.dodgeAnimation2Id = nbt.getInteger("dodgeAnimation2Id");
this.dodgeAnimation2Name = nbt.getString("dodgeAnimation2Name");
this.dodgeAnimation3Id = nbt.getInteger("dodgeAnimation3Id");
this.dodgeAnimation3Name = nbt.getString("dodgeAnimation3Name");
}
// ═══════════════════════════════════════════════════════════════════
// GUI
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
protected void getTypeDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.section("ability.section.dodgeAnimations"));
FieldDef.insertAfter(defs, "ability.dazedAnimation",
FieldDef.animSubGui("ability.dodgeAnimation1",
this::getDodgeAnimation1Id, this::setDodgeAnimation1Id,
this::getDodgeAnimation1Name, this::setDodgeAnimation1Name)
.tab("Effects"));
FieldDef.insertAfter(defs, "ability.dodgeAnimation1",
FieldDef.animSubGui("ability.dodgeAnimation2",
this::getDodgeAnimation2Id, this::setDodgeAnimation2Id,
this::getDodgeAnimation2Name, this::setDodgeAnimation2Name)
.tab("Effects"));
FieldDef.insertAfter(defs, "ability.dodgeAnimation2",
FieldDef.animSubGui("ability.dodgeAnimation3",
this::getDodgeAnimation3Id, this::setDodgeAnimation3Id,
this::getDodgeAnimation3Name, this::setDodgeAnimation3Name)
.tab("Effects"));
FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false);
FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false);
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
@Override
public int getDodgeAnimation1Id() {
return dodgeAnimation1Id;
}
@Override
public void setDodgeAnimation1Id(int animationId) {
this.dodgeAnimation1Id = animationId;
}
public String getDodgeAnimation1Name() {
return dodgeAnimation1Name;
}
public void setDodgeAnimation1Name(String name) {
this.dodgeAnimation1Name = name != null ? name : "";
}
@Override
public int getDodgeAnimation2Id() {
return dodgeAnimation2Id;
}
@Override
public void setDodgeAnimation2Id(int animationId) {
this.dodgeAnimation2Id = animationId;
}
public String getDodgeAnimation2Name() {
return dodgeAnimation2Name;
}
public void setDodgeAnimation2Name(String name) {
this.dodgeAnimation2Name = name != null ? name : "";
}
@Override
public int getDodgeAnimation3Id() {
return dodgeAnimation3Id;
}
@Override
public void setDodgeAnimation3Id(int animationId) {
this.dodgeAnimation3Id = animationId;
}
public String getDodgeAnimation3Name() {
return dodgeAnimation3Name;
}
public void setDodgeAnimation3Name(String name) {
this.dodgeAnimation3Name = name != null ? name : "";
}
}
@@ -78,6 +78,11 @@ public class AbilityEffect extends Ability implements IAbilityEffect {
this.windUpTicks = 30;
this.telegraphType = TelegraphType.NONE;
this.showTelegraph = false;
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/effect.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/effect_overlay.png",
this::getActiveColor)
};
}
// ==================== ABILITY TYPE OVERRIDES ====================
@@ -2,285 +2,72 @@ package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.api.ability.type.IAbilityGuard;
import noppes.npcs.api.handler.data.IAnimation;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.util.ValueUtil;
import java.util.Arrays;
import java.util.List;
/**
* Guard ability: Defensive stance that reduces incoming damage.
* Can optionally counter-attack when hit.
*/
public class AbilityGuard extends Ability implements IAbilityGuard {
public class AbilityGuard extends AbilityDefend implements IAbilityGuard {
private int durationTicks = 60;
private float damageReduction = 0.5f;
private AbilityGuard.CounterType counterType = AbilityGuard.CounterType.FLAT;
private float counterValue = 6.0f;
private String counterSound = "random.anvil_land";
private boolean canCounter = false;
private int counterWindow = 10;
private int counterAnimationId = -1;
private String counterAnimationName;
// Runtime state
private transient EntityLivingBase lastAttacker;
private transient boolean counterTriggered;
private transient boolean counterEligible;
private transient float lastDamageTaken;
public AbilityGuard() {
this.typeId = "ability.cnpc.guard";
this.name = "Guard";
this.targetingMode = TargetingMode.SELF;
this.lockMovement = LockMode.ACTIVE;
this.cooldownTicks = 0;
this.windUpTicks = 0;
this.interruptible = false; // Hard to interrupt while guarding
// No telegraph for guard - it's a defensive stance
this.telegraphType = TelegraphType.NONE;
this.showTelegraph = false;
this.activeSound = "random.anvil_use";
this.allowedBy = UserType.BOTH;
this.activeAnimationName = "Ability_Guard_Active";
this.counterAnimationName = "Ability_Guard_Counter";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/guard.png")
};
}
// ═══════════════════════════════════════════════════════════════════
// DEFEND HOOKS
// ═══════════════════════════════════════════════════════════════════
@Override
public boolean hasDamage() {
return canCounter;
protected float performDefend(EntityLivingBase attacker, float amount) {
return Math.max(0, amount * (1.0f - damageReduction));
}
// ═══════════════════════════════════════════════════════════════════
// NBT
// ═══════════════════════════════════════════════════════════════════
@Override
public boolean allowBurst() {
return false;
}
public enum CounterType {
FLAT,
PERCENT;
@Override
public String toString() {
switch (this) {
case FLAT:
return "ability.counter.flat";
case PERCENT:
return "ability.counter.percent";
default:
return name();
}
}
}
@Override
public boolean isTargetingModeLocked() {
return true;
}
@Override
public TargetingMode[] getAllowedTargetingModes() {
return new TargetingMode[]{TargetingMode.SELF};
}
@Override
public void onExecute(EntityLivingBase caster, EntityLivingBase target) {
lastAttacker = null;
counterTriggered = false;
lastDamageTaken = 0.0f;
counterEligible = true;
}
@Override
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !caster.worldObj.isRemote) {
performCounter(caster, caster.worldObj);
}
if (tick > counterWindow && counterEligible) {
counterEligible = false;
}
if (tick >= durationTicks) {
signalCompletion();
return;
}
// Just enough to see the counter animation
if (counterTriggered && tick >= counterWindow + 10) {
signalCompletion();
}
}
public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) {
if (!isGuarding() || attacker == null) return;
lastAttacker = attacker;
lastDamageTaken = damage;
// Players: damage reduction handled via LivingHurtEvent (event.ammount modification)
// NPCs: called AFTER damageEntity() so health was already reduced — heal back here
if (caster instanceof EntityPlayer) {
if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) {
counterTriggered = true;
}
} else {
float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage);
float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth());
if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) {
caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth()));
counterTriggered = true;
} else {
caster.setHealth(newHealth);
}
}
}
private boolean isDirectHit(DamageSource source) {
if (source == null) return false;
if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) return false;
return source.getEntity() instanceof EntityLivingBase;
}
private void performCounter(EntityLivingBase caster, World world) {
float counterDamage = counterType == AbilityGuard.CounterType.PERCENT
? lastDamageTaken * (counterValue / 100.0f)
: counterValue;
boolean wasHit = applyAbilityDamage(caster, lastAttacker, counterDamage, 0.5f);
if (wasHit && counterSound != null && !counterSound.isEmpty()) {
world.playSoundAtEntity(caster, counterSound, 1.0f, 1.2f);
}
// Use shared animation utility - only available for NPCs
if (caster instanceof EntityNPCInterface) {
if (getCounterAnimation() instanceof IAnimation) {
((EntityNPCInterface) caster).abilities.playAbilityAnimation((Animation) getCounterAnimation());
}
} else if (caster instanceof EntityPlayer) {
if (getCounterAnimation() instanceof IAnimation) {
PlayerData.get((EntityPlayer) caster).abilityData.playAbilityAnimation((Animation) getCounterAnimation());
}
}
counterEligible = false;
lastAttacker = null;
lastDamageTaken = 0.0f;
}
private IAnimation getCounterAnimation() {
if (AnimationController.Instance == null) return null;
if (counterAnimationId > 0) {
return AnimationController.Instance.get(counterAnimationId);
}
if (counterAnimationName != null && !counterAnimationName.isEmpty()) {
return AnimationController.Instance.get(counterAnimationName, true);
}
return null;
}
/**
* Get the damage reduction factor while guarding.
* Returns 0.5 for 50% reduction.
*/
public float getDamageReductionFactor() {
if (isExecuting() && getPhase() == AbilityPhase.ACTIVE) {
return damageReduction;
}
return 0.0f;
}
/**
* Check if the caster is currently in guard stance.
*/
public boolean isGuarding() {
return isExecuting() && getPhase() == AbilityPhase.ACTIVE;
}
@Override
public void reset() {
super.reset();
lastAttacker = null;
counterTriggered = false;
lastDamageTaken = 0.0f;
}
@Override
public float getTelegraphRadius() {
return 0; // No telegraph for guard
}
@Override
public void writeTypeNBT(NBTTagCompound nbt) {
nbt.setInteger("durationTicks", durationTicks);
protected void writeSubTypeNBT(NBTTagCompound nbt) {
nbt.setFloat("damageReduction", damageReduction);
nbt.setBoolean("canCounter", canCounter);
nbt.setInteger("counterWindow", counterWindow);
nbt.setString("counterType", counterType.name());
nbt.setFloat("counterValue", counterValue);
nbt.setString("counterSound", counterSound);
nbt.setInteger("counterAnimationId", counterAnimationId);
nbt.setString("counterAnimationName", counterAnimationName);
}
@Override
public void readTypeNBT(NBTTagCompound nbt) {
this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60;
protected void readSubTypeNBT(NBTTagCompound nbt) {
this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f;
this.canCounter = nbt.getBoolean("canCounter");
this.counterWindow = nbt.getInteger("counterWindow");
try {
this.counterType = CounterType.valueOf(nbt.getString("counterType"));
} catch (Exception e) {
this.counterType = CounterType.FLAT;
}
this.counterValue = nbt.getFloat("counterValue");
this.counterSound = nbt.getString("counterSound");
this.counterAnimationId = nbt.getInteger("counterAnimationId");
this.counterAnimationName = nbt.getString("counterAnimationName");
}
// Getters & Setters
public int getDurationTicks() {
return durationTicks;
}
public void setDurationTicks(int durationTicks) {
this.durationTicks = Math.max(1, durationTicks);
}
// ═══════════════════════════════════════════════════════════════════
// GUI
// ═══════════════════════════════════════════════════════════════════
@SideOnly(Side.CLIENT)
@Override
public int getCounterWindow() {
return this.counterWindow;
protected void getTypeDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.floatField("ability.damageReduction", this::getDamageReduction, this::setDamageReduction));
FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false);
FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false);
}
@Override
public void setCounterWindow(int ticks) {
this.counterWindow = Math.min(durationTicks, ticks);
}
// ═══════════════════════════════════════════════════════════════════
// GETTERS / SETTERS
// ═══════════════════════════════════════════════════════════════════
@Override
public float getDamageReduction() {
@@ -291,105 +78,4 @@ public class AbilityGuard extends Ability implements IAbilityGuard {
public void setDamageReduction(float damageReduction) {
this.damageReduction = damageReduction;
}
@Override
public boolean canCounter() {
return canCounter;
}
public void setCanCounter(boolean canCounter) {
this.canCounter = canCounter;
}
public CounterType getCounterTypeEnum() {
return counterType;
}
public void setCounterTypeEnum(CounterType counterType) {
this.counterType = counterType;
}
@Override
public int getCounterType() {
return counterType.ordinal();
}
@Override
public void setCounterType(int type) {
CounterType[] values = CounterType.values();
this.counterType = type >= 0 && type < values.length ? values[type] : CounterType.FLAT;
}
public float getCounterValue() {
return counterValue;
}
public void setCounterValue(float counterValue) {
this.counterValue = counterValue;
}
public String getCounterSound() {
return counterSound;
}
public void setCounterSound(String counterSound) {
this.counterSound = counterSound;
}
public int getCounterAnimationId() {
return counterAnimationId;
}
public void setCounterAnimationId(int counterAnimationId) {
this.counterAnimationId = counterAnimationId;
}
public boolean isCounterTriggered() {
return counterTriggered;
}
public String getCounterAnimationName() {
return counterAnimationName;
}
public void setCounterAnimationName(String name) {
this.counterAnimationName = name != null ? name : "";
}
@SideOnly(Side.CLIENT)
@Override
public void getAbilityDefinitions(List<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.dazedAnimation",
FieldDef.animSubGui("ability.counterAnimation",
this::getCounterAnimationId, this::setCounterAnimationId,
this::getCounterAnimationName, this::setCounterAnimationName)
.tab("Effects").visibleWhen(this::canCounter));
FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false);
FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false);
}
}
@@ -30,6 +30,12 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
this.windUpTicks = 30;
this.windUpAnimationName = "Ability_Zone_Windup";
this.activeAnimationName = "Ability_Zone_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/hazard.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/hazard_overlay.png",
this::getActiveColor)
};
}
@Override
@@ -47,6 +47,11 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit {
this.activeSound = "random.anvil_land";
this.windUpAnimationName = "Ability_HeavyHit_Windup";
this.activeAnimationName = "Ability_HeavyHit_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/heavy_hit.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/heavy_hit_overlay.png",
this::getActiveColor)
};
}
@Override
@@ -43,6 +43,11 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave {
this.activeSound = "random.explode";
this.windUpAnimationName = "Ability_Shockwave_Windup";
this.activeAnimationName = "Ability_Shockwave_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/shockwave.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/shockwave_overlay.png",
this::getActiveColor)
};
}
@Override
@@ -83,6 +83,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam {
// Default built-in animations
this.windUpAnimationName = "Ability_Slam_Windup";
this.activeAnimationName = "Ability_Slam_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/slam.png")
};
}
/**
@@ -86,6 +86,9 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport {
this.showTelegraph = false;
this.windUpSound = "mob.endermen.portal";
this.activeSound = "mob.endermen.portal";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/teleport.png")
};
}
@Override
@@ -36,6 +36,11 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap {
this.windUpTicks = 30;
this.windUpAnimationName = "Ability_Zone_Windup";
this.activeAnimationName = "Ability_Zone_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/trap.png",
this::getActiveColor)
};
}
@Override
@@ -16,10 +16,11 @@ import net.minecraft.world.World;
import noppes.npcs.api.ability.type.IAbilityVortex;
import noppes.npcs.client.gui.builder.FieldDef;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.UUID;
/**
@@ -37,13 +38,25 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
private float pullDamage = 0.0f;
// Runtime state
private transient Set<UUID> pulledEntities;
private transient Map<UUID, PullState> pulledEntities;
private transient boolean pullComplete = false;
private transient int ticksSincePullDamage = 0;
private Set<UUID> getPulledEntities() {
private static class PullState {
double lastX, lastY, lastZ;
int stuckTicks;
PullState(EntityLivingBase entity) {
this.lastX = entity.posX;
this.lastY = entity.posY;
this.lastZ = entity.posZ;
this.stuckTicks = 0;
}
}
private Map<UUID, PullState> getPulledEntities() {
if (pulledEntities == null) {
pulledEntities = new HashSet<>();
pulledEntities = new HashMap<>();
}
return pulledEntities;
}
@@ -59,6 +72,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
this.telegraphType = TelegraphType.CIRCLE;
this.windUpSound = "mob.ghast.charge";
this.activeSound = "mob.ghast.fireball";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/vortex.png",
this::getActiveColor)
};
}
@Override
@@ -96,37 +113,36 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
double dist = caster.getDistanceToEntity(entity);
if (dist <= pullRadius) {
getPulledEntities().add(entity.getUniqueID());
getPulledEntities().put(entity.getUniqueID(), new PullState(entity));
}
}
} else {
// SINGULAR: pull one target
// NPC: pull aggro target if valid, otherwise nearest enemy
// Player: pull nearest enemy in range
// SINGULAR: pull one random target within range
// NPC: pull aggro target if valid, otherwise random enemy
// Player: pull random enemy in range
if (!isPlayerCaster(caster) && target != null && !target.isDead) {
double dist = caster.getDistanceToEntity(target);
if (dist <= pullRadius) {
getPulledEntities().add(target.getUniqueID());
getPulledEntities().put(target.getUniqueID(), new PullState(target));
return;
}
}
// Find nearest valid enemy
EntityLivingBase nearest = null;
double nearestDist = Double.MAX_VALUE;
// Collect all valid enemies, then pick one at random
List<EntityLivingBase> validTargets = new ArrayList<>();
for (EntityLivingBase entity : entities) {
if (entity == caster) continue;
if (entity.isDead) continue;
if (!AbilityTargetHelper.shouldAffect(caster, entity, TargetFilter.ENEMIES, false)) continue;
double dist = caster.getDistanceToEntity(entity);
if (dist <= pullRadius && dist < nearestDist) {
nearest = entity;
nearestDist = dist;
if (dist <= pullRadius) {
validTargets.add(entity);
}
}
if (nearest != null) {
getPulledEntities().add(nearest.getUniqueID());
if (!validTargets.isEmpty()) {
EntityLivingBase chosen = validTargets.get(caster.worldObj.rand.nextInt(validTargets.size()));
getPulledEntities().put(chosen.getUniqueID(), new PullState(chosen));
}
}
}
@@ -147,6 +163,21 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
if (caster.worldObj.isRemote) return;
// Safety cap: force-complete if active too long
int maxActiveTicks = Math.max(40, (int)(pullRadius / pullStrength * 3));
if (tick >= maxActiveTicks) {
for (Map.Entry<UUID, PullState> entry : new HashMap<>(getPulledEntities()).entrySet()) {
EntityLivingBase entity = findEntity(caster, caster.worldObj, entry.getKey());
if (entity != null && !entity.isDead) {
onTargetArrived(caster, entity, caster.worldObj);
}
}
getPulledEntities().clear();
pullComplete = true;
signalCompletion();
return;
}
double destX = caster.posX;
double destY = caster.posY;
double destZ = caster.posZ;
@@ -158,7 +189,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
ticksSincePullDamage = 0;
}
for (UUID uuid : new HashSet<>(getPulledEntities())) {
for (Map.Entry<UUID, PullState> entry : new HashMap<>(getPulledEntities()).entrySet()) {
UUID uuid = entry.getKey();
PullState state = entry.getValue();
EntityLivingBase entity = findEntity(caster, caster.worldObj, uuid);
if (entity == null || entity.isDead) {
getPulledEntities().remove(uuid);
@@ -170,7 +204,28 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
double dz = destZ - entity.posZ;
double dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist <= 1.5f) {
if (dist <= 1.5) {
getPulledEntities().remove(uuid);
onTargetArrived(caster, entity, caster.worldObj);
continue;
}
// Stuck detection: check if entity made progress since last tick
double lastDx = destX - state.lastX;
double lastDy = destY - state.lastY;
double lastDz = destZ - state.lastZ;
double lastDist = Math.sqrt(lastDx * lastDx + lastDy * lastDy + lastDz * lastDz);
double progress = lastDist - dist; // positive = entity moved closer
double expectedProgress = Math.min(pullStrength, dist * 0.5);
if (progress < expectedProgress * 0.3) {
state.stuckTicks++;
} else {
state.stuckTicks = 0;
}
if (state.stuckTicks >= 5) {
// Entity is stuck (wall, block, partial obstruction) - treat as arrived
getPulledEntities().remove(uuid);
onTargetArrived(caster, entity, caster.worldObj);
continue;
@@ -182,21 +237,20 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
double maxSpeed = dist * 0.5;
double effectiveSpeed = Math.min(pullStrength, maxSpeed);
double factor = effectiveSpeed / dist;
double nextX = dx * factor;
double nextY = dy * factor * 0.5;
double nextZ = dz * factor;
double motionX = dx * factor;
double motionY = dy * factor * 0.5;
double motionZ = dz * factor;
AxisAlignedBB nextBox = entity.boundingBox.copy().offset(nextX, nextY, nextZ);
if (!caster.worldObj.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) {
getPulledEntities().remove(uuid);
continue;
}
entity.motionX = nextX;
entity.motionY = nextY;
entity.motionZ = nextZ;
entity.motionX = motionX;
entity.motionY = motionY;
entity.motionZ = motionZ;
entity.velocityChanged = true;
// Update tracked position for next tick's stuck detection
state.lastX = entity.posX;
state.lastY = entity.posY;
state.lastZ = entity.posZ;
if (shouldDealPullDamage) {
entity.hurtResistantTime = 0;
applyAbilityDamage(caster, entity, pullDamage * 0.5f, 0);
@@ -222,11 +276,12 @@ public class AbilityVortex extends Ability implements IAbilityVortex {
/**
* Find an entity by UUID within the vortex pull area.
* Uses AABB search instead of iterating all loaded entities.
* Search area is expanded beyond pullRadius to account for entity drift.
*/
@SuppressWarnings("unchecked")
private EntityLivingBase findEntity(EntityLivingBase caster, World world, UUID uuid) {
// Search within pull radius (entities being pulled should be within this area)
AxisAlignedBB searchBox = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius);
double searchRadius = pullRadius + 5;
AxisAlignedBB searchBox = caster.boundingBox.expand(searchRadius, searchRadius / 2, searchRadius);
List<EntityLivingBase> nearbyEntities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox);
for (EntityLivingBase entity : nearbyEntities) {
@@ -5,7 +5,7 @@ import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
@@ -21,8 +21,13 @@ public abstract class AbilityBarrier extends AbilityEnergy {
protected final EnergyBarrierData barrierData;
// Spawn position offsets (relative to caster)
protected float offsetX = 0.0f;
protected float offsetY = 0.0f;
protected float offsetZ = 0.0f;
// Runtime entity tracking
protected transient EntityAbilityBarrier barrierEntity;
protected transient EntityEnergyBarrier barrierEntity;
protected AbilityBarrier(EnergyDisplayData displayData, EnergyBarrierData barrierData) {
super(displayData);
@@ -34,7 +39,7 @@ public abstract class AbilityBarrier extends AbilityEnergy {
/**
* Create and spawn the barrier entity during execution.
*/
protected abstract EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target);
protected abstract EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target);
/**
* Add type-specific GUI field definitions.
@@ -157,10 +162,16 @@ public abstract class AbilityBarrier extends AbilityEnergy {
writeBarrierTypeNBT(nbt);
writeEnergyNBT(nbt);
barrierData.writeNBT(nbt);
nbt.setFloat("barrierOffsetX", offsetX);
nbt.setFloat("barrierOffsetY", offsetY);
nbt.setFloat("barrierOffsetZ", offsetZ);
}
@Override
public final void readTypeNBT(NBTTagCompound nbt) {
offsetX = nbt.hasKey("barrierOffsetX") ? nbt.getFloat("barrierOffsetX") : 0.0f;
offsetY = nbt.hasKey("barrierOffsetY") ? nbt.getFloat("barrierOffsetY") : 0.0f;
offsetZ = nbt.hasKey("barrierOffsetZ") ? nbt.getFloat("barrierOffsetZ") : 0.0f;
readBarrierTypeNBT(nbt);
readEnergyNBT(nbt);
barrierData.readNBT(nbt);
@@ -271,6 +282,14 @@ public abstract class AbilityBarrier extends AbilityEnergy {
barrierData.setReflectStrengthPct(strengthPct);
}
public boolean isTargetOwner() {
return barrierData.targetOwner;
}
public void setTargetOwner(boolean targetOwner) {
barrierData.targetOwner = targetOwner;
}
// Melee data
public boolean isMeleeEnabled() {
return barrierData.meleeEnabled;
@@ -288,6 +307,31 @@ public abstract class AbilityBarrier extends AbilityEnergy {
barrierData.meleeDamageMultiplier = mult;
}
// Offset data
public float getOffsetX() {
return offsetX;
}
public void setOffsetX(float offsetX) {
this.offsetX = offsetX;
}
public float getOffsetY() {
return offsetY;
}
public void setOffsetY(float offsetY) {
this.offsetY = offsetY;
}
public float getOffsetZ() {
return offsetZ;
}
public void setOffsetZ(float offsetZ) {
this.offsetZ = offsetZ;
}
// ==================== GUI ====================
@SideOnly(Side.CLIENT)
@@ -296,6 +340,14 @@ public abstract class AbilityBarrier extends AbilityEnergy {
// Type-specific fields first
addBarrierTypeDefinitions(defs);
// Offset section
defs.add(FieldDef.section("ability.section.offset"));
defs.add(FieldDef.row(
FieldDef.floatField("ability.offsetX", this::getOffsetX, this::setOffsetX).min(Float.NEGATIVE_INFINITY),
FieldDef.floatField("ability.offsetY", this::getOffsetY, this::setOffsetY).min(Float.NEGATIVE_INFINITY)
));
defs.add(FieldDef.floatField("ability.offsetZ", this::getOffsetZ, this::setOffsetZ).min(Float.NEGATIVE_INFINITY));
// Barrier section
defs.add(FieldDef.section("ability.section.barrier"));
defs.add(FieldDef.boolField("ability.useHealth", this::isUseHealth, this::setUseHealth));
@@ -320,6 +372,9 @@ public abstract class AbilityBarrier extends AbilityEnergy {
.hover("ability.hover.reflect"));
defs.add(FieldDef.floatField("ability.reflectStrength", this::getReflectStrengthPct, this::setReflectStrengthPct)
.range(0, 100).visibleWhen(this::isReflect));
defs.add(FieldDef.boolField("ability.targetOwner", this::isTargetOwner, this::setTargetOwner)
.hover("ability.hover.targetOwner")
.visibleWhen(this::isReflect));
defs.add(FieldDef.boolField("ability.meleeEnabled", this::isMeleeEnabled, this::setMeleeEnabled)
.hover("ability.hover.meleeEnabled"));
defs.add(FieldDef.floatField("ability.meleeDamageMultiplier", this::getMeleeDamageMultiplier, this::setMeleeDamageMultiplier)
@@ -33,6 +33,7 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
private float beamWidth = 0.4f;
private float headSize = 0.6f;
private boolean freeAim = false;
public AbilityBeam() {
super(
@@ -55,6 +56,11 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
this.showTelegraph = true;
this.windUpAnimationName = "Ability_Beam_Windup";
this.activeAnimationName = "Ability_Beam_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/beam.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
// ==================== ABSTRACT IMPLEMENTATIONS ====================
@@ -62,12 +68,14 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
@Override
protected EntityAbilityBeam createEntity(EntityLivingBase caster, EntityLivingBase target,
Vec3 spawnPos, EnergyDisplayData resolved, int index) {
return new EntityAbilityBeam(
EntityAbilityBeam beam = new EntityAbilityBeam(
caster.worldObj, caster, target,
spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord,
beamWidth, headSize,
resolved, combatData, homingData, lightningData, lifespanData,
lockMovement.locksActive());
beam.setFreeAim(freeAim);
return beam;
}
@Override
@@ -95,6 +103,18 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
return new EntityAbilityBeam[size];
}
@Override
public void detach() {
if (entities != null) {
for (EntityAbilityBeam beam : entities) {
if (beam != null && !beam.isDead) {
beam.setAttachedToOwner(false);
}
}
}
super.detach();
}
@Override
protected float getProjectileTelegraphRadius() {
return headSize * 2.0f;
@@ -134,12 +154,14 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
protected void writeTypeSpecificNBT(NBTTagCompound nbt) {
nbt.setFloat("beamWidth", beamWidth);
nbt.setFloat("headSize", headSize);
nbt.setBoolean("freeAim", freeAim);
}
@Override
protected void readTypeSpecificNBT(NBTTagCompound nbt) {
this.beamWidth = nbt.getFloat("beamWidth");
this.headSize = nbt.getFloat("headSize");
this.freeAim = nbt.getBoolean("freeAim");
}
// ==================== TYPE-SPECIFIC GETTERS ====================
@@ -168,6 +190,14 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
this.headSize = headSize;
}
public boolean isFreeAim() {
return freeAim;
}
public void setFreeAim(boolean freeAim) {
this.freeAim = freeAim;
}
// ==================== TYPE-SPECIFIC GUI ====================
@SideOnly(Side.CLIENT)
@@ -184,6 +214,9 @@ public class AbilityBeam extends AbilityEnergyProjectile<EntityAbilityBeam> impl
));
defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback));
defs.add(FieldDef.section("ability.section.beam"));
defs.add(FieldDef.boolField("ability.freeAim", this::isFreeAim, this::setFreeAim)
.hover("ability.hover.freeAim")
.enabledWhen(() -> lockMovement.locksActive() && rotationMode == RotationMode.FREE && !freeOnCast));
defs.add(FieldDef.row(
FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth).range(0.1f, 100.0f),
FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize).range(0.1f, 100.0f)
@@ -55,6 +55,12 @@ public class AbilityDisc extends AbilityEnergyProjectile<EntityAbilityDisc> impl
this.showTelegraph = true;
this.windUpAnimationName = "Ability_Disc_Windup";
this.activeAnimationName = "Ability_Disc_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/disc.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/disc_overlay.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
// ==================== ABSTRACT IMPLEMENTATIONS ====================
@@ -8,8 +8,8 @@ import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyDome;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.builder.FieldDef;
@@ -42,18 +42,24 @@ public class AbilityDome extends AbilityBarrier {
this.showTelegraph = true;
this.windUpAnimationName = "";
this.activeAnimationName = "";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/dome.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
// ==================== ABSTRACT IMPLEMENTATIONS ====================
@Override
protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) {
EntityAbilityDome dome = new EntityAbilityDome(
protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) {
EntityEnergyDome dome = new EntityEnergyDome(
caster.worldObj, caster,
caster.posX, caster.posY, caster.posZ,
caster.posX + offsetX, caster.posY + offsetY, caster.posZ + offsetZ,
domeRadius, displayData.copy(), lightningData.copy(), barrierData.copy()
);
dome.setFollowCaster(followCaster);
dome.setOffsets(offsetX, offsetY, offsetZ);
dome.setSourceAbility(this);
return dome;
}
@@ -192,20 +192,6 @@ public abstract class AbilityEnergyProjectile<E extends EntityEnergyProjectile>
this.fireDelay = Math.max(0, delay);
}
/**
* @deprecated Use {@link #getFireDelay()}
*/
public int getDualFireDelay() {
return fireDelay;
}
/**
* @deprecated Use {@link #setFireDelay(int)}
*/
public void setDualFireDelay(int delay) {
setFireDelay(delay);
}
protected int clampIndex(int index) {
return Math.max(0, Math.min(index, projectileCount - 1));
}
@@ -53,6 +53,12 @@ public class AbilityLaser extends AbilityEnergyProjectile<EntityAbilityLaser> im
this.showTelegraph = true;
this.windUpAnimationName = "Ability_Laser_Windup";
this.activeAnimationName = "Ability_Laser_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/laser_shot.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/laser_shot_overlay.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
// ==================== OVERRIDES ====================
@@ -207,7 +213,10 @@ public class AbilityLaser extends AbilityEnergyProjectile<EntityAbilityLaser> im
FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth).range(0.1f, 100.0f),
FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed).range(0.1f, 50.0f)
));
defs.add(FieldDef.floatField("ability.maxLength", this::getMaxLength, this::setMaxLength).range(1.0f, 500.0f));
defs.add(FieldDef.row(
FieldDef.floatField("ability.maxLength", this::getMaxLength, this::setMaxLength).range(1.0f, 500.0f),
FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime).range(1, 1200)
));
defs.add(FieldDef.section("ability.section.explosive"));
defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"));
defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius)
@@ -49,6 +49,12 @@ public class AbilityOrb extends AbilityEnergyProjectile<EntityAbilityOrb> implem
this.showTelegraph = true;
this.windUpAnimationName = "Ability_Orb_Windup";
this.activeAnimationName = "Ability_Orb_Active";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/orb.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/orb_overlay.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
// ==================== ABSTRACT IMPLEMENTATIONS ====================
@@ -10,8 +10,8 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyPanel;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.builder.FieldDef;
@@ -45,24 +45,31 @@ public class AbilityShield extends AbilityBarrier {
this.windUpAnimationName = "";
this.activeAnimationName = "";
this.allowedBy = UserType.BOTH;
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/shield.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
// ==================== ABSTRACT IMPLEMENTATIONS ====================
@Override
protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) {
EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, 0.0f);
protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) {
EnergyPanelData panelData = new EnergyPanelData(shieldWidth, shieldHeight, offsetY);
panelData.offsetX = offsetX;
panelData.offsetZ = offsetZ;
float frontDist = 1.5f;
float yawRad = (float) Math.toRadians(caster.rotationYaw);
double spawnX = caster.posX + (-Math.sin(yawRad) * frontDist);
double spawnX = caster.posX + (-Math.sin(yawRad) * frontDist) + offsetX;
double spawnY = caster.posY + (caster.height * 0.5f);
double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist);
double spawnZ = caster.posZ + (Math.cos(yawRad) * frontDist) + offsetZ;
EntityAbilityPanel panel = new EntityAbilityPanel(
EntityEnergyPanel panel = new EntityEnergyPanel(
caster.worldObj, caster,
spawnX, spawnY, spawnZ, caster.rotationYaw,
EntityAbilityPanel.PanelMode.HELD,
EntityEnergyPanel.PanelMode.HELD,
displayData.copy(), lightningData.copy(), barrierData.copy(), panelData
);
panel.setSourceAbility(this);
@@ -9,7 +9,7 @@ import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergySweeper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.ability.type.IAbilitySweeper;
@@ -23,7 +23,7 @@ import java.util.List;
* Players can jump over it. The beam completes a set number of rotations before ending.
* Telegraph shows a large circle on the ground indicating range.
* <p>
* All damage logic is handled by the EntityAbilitySweeper entity to ensure
* All damage logic is handled by the EntityEnergySweeper entity to ensure
* visual and damage hitbox alignment.
*/
public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper {
@@ -40,7 +40,7 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper {
private boolean lockOnTarget = false;
// Runtime state (transient)
private transient EntityAbilitySweeper activeEntity = null;
private transient EntityEnergySweeper activeEntity = null;
public AbilitySweeper() {
super(new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f));
@@ -55,6 +55,12 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper {
// Circle telegraph to show range
this.telegraphType = TelegraphType.CIRCLE;
this.showTelegraph = true;
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/sweeper.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/sweeper_overlay.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
@Override
@@ -92,7 +98,7 @@ public class AbilitySweeper extends AbilityEnergy implements IAbilitySweeper {
// Spawn the sweeper entity that handles BOTH visuals AND damage.
// NPC: target is the aggro target — lockOnTarget tracks it during sweep.
// Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect.
activeEntity = new EntityAbilitySweeper(caster.worldObj, caster, target,
activeEntity = new EntityEnergySweeper(caster.worldObj, caster, target,
beamLength, beamWidth, beamHeight,
displayData,
sweepSpeed, numberOfRotations,
@@ -9,8 +9,8 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyPanelData;
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyPanel;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.builder.FieldDef;
@@ -45,6 +45,12 @@ public class AbilityWall extends AbilityBarrier {
this.showTelegraph = true;
this.windUpAnimationName = "";
this.activeAnimationName = "";
this.defaultIconLayers = new DefaultIconLayer[]{
new DefaultIconLayer("customnpcs:textures/gui/ability/wall.png"),
new DefaultIconLayer("customnpcs:textures/gui/ability/wall_overlay.png",
() -> isOuterColorEnabled() ? getOuterColor() : getInnerColor())
};
}
@Override
@@ -55,7 +61,7 @@ public class AbilityWall extends AbilityBarrier {
// ==================== ABSTRACT IMPLEMENTATIONS ====================
@Override
protected EntityAbilityBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) {
protected EntityEnergyBarrier createBarrierEntity(EntityLivingBase caster, EntityLivingBase target) {
// Place wall between caster and target
double placeX, placeY, placeZ;
float yaw;
@@ -87,14 +93,21 @@ public class AbilityWall extends AbilityBarrier {
yaw = caster.rotationYaw;
}
EntityAbilityPanel.PanelMode mode = panelData.launching
? EntityAbilityPanel.PanelMode.LAUNCHED
: EntityAbilityPanel.PanelMode.PLACED;
placeX += offsetX;
placeY += offsetY;
placeZ += offsetZ;
EntityAbilityPanel panel = new EntityAbilityPanel(
EntityEnergyPanel.PanelMode mode = panelData.launching
? EntityEnergyPanel.PanelMode.LAUNCHED
: EntityEnergyPanel.PanelMode.PLACED;
EnergyPanelData data = panelData.copy();
data.heightOffset = 0.0f; // Y offset now handled by base class via placeY
EntityEnergyPanel panel = new EntityEnergyPanel(
caster.worldObj, caster,
placeX, placeY, placeZ, yaw, mode,
displayData.copy(), lightningData.copy(), barrierData.copy(), panelData.copy()
displayData.copy(), lightningData.copy(), barrierData.copy(), data
);
panel.setSourceAbility(this);
return panel;
@@ -134,6 +147,11 @@ public class AbilityWall extends AbilityBarrier {
@Override
protected void readBarrierTypeNBT(NBTTagCompound nbt) {
panelData.readNBT(nbt);
// Migrate legacy heightOffset → base class offsetY
if (!nbt.hasKey("barrierOffsetY") && panelData.heightOffset != 0.0f) {
offsetY = panelData.heightOffset;
panelData.heightOffset = 0.0f;
}
}
// ==================== GETTERS & SETTERS ====================
@@ -158,14 +176,6 @@ public class AbilityWall extends AbilityBarrier {
panelData.setPanelHeight(height);
}
public float getHeightOffset() {
return panelData.heightOffset;
}
public void setHeightOffset(float offset) {
panelData.heightOffset = offset;
}
public boolean isLaunching() {
return panelData.launching;
}
@@ -208,8 +218,6 @@ public class AbilityWall extends AbilityBarrier {
FieldDef.floatField("gui.width", this::getPanelWidth, this::setPanelWidth).range(0.5f, 100.0f),
FieldDef.floatField("gui.height", this::getPanelHeight, this::setPanelHeight).range(0.5f, 100.0f)
));
defs.add(FieldDef.floatField("ability.heightOffset", this::getHeightOffset, this::setHeightOffset)
.min(Float.NEGATIVE_INFINITY));
defs.add(FieldDef.section("ability.section.launch"));
defs.add(FieldDef.boolField("gui.enabled", this::isLaunching, this::setLaunching)
.hover("ability.hover.launching"));
@@ -2,6 +2,7 @@ package kamkeel.npcs.controllers.data.profile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.api.handler.data.IProfile;
@@ -15,6 +16,7 @@ public class Profile implements IProfile {
public EntityPlayer player;
public int currentSlotId;
private final Map<Integer, ISlot> slots = new HashMap<>();
public Map<Integer, Long> sharedQuestTimestamps = new HashMap<>();
private boolean locked = false;
public Profile(EntityPlayer player, NBTTagCompound compound) {
@@ -39,6 +41,14 @@ public class Profile implements IProfile {
}
}
}
if (compound.hasKey("SharedQuestTimestamps")) {
NBTTagList list = compound.getTagList("SharedQuestTimestamps", 10);
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound entry = list.getCompoundTagAt(i);
sharedQuestTimestamps.put(entry.getInteger("Quest"), entry.getLong("Date"));
}
}
}
public Profile(EntityPlayer player) {
@@ -88,6 +98,16 @@ public class Profile implements IProfile {
slotsCompound.setTag(String.valueOf(entry.getKey()), entry.getValue().toNBT());
}
compound.setTag("Slots", slotsCompound);
NBTTagList questList = new NBTTagList();
for (Map.Entry<Integer, Long> entry : sharedQuestTimestamps.entrySet()) {
NBTTagCompound questEntry = new NBTTagCompound();
questEntry.setInteger("Quest", entry.getKey());
questEntry.setLong("Date", entry.getValue());
questList.appendTag(questEntry);
}
compound.setTag("SharedQuestTimestamps", questList);
return compound;
}
}
@@ -11,6 +11,7 @@ import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.util.AnchorPointHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.AxisAlignedBB;
@@ -55,6 +56,10 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
// Beam behavior mode (single source of truth).
private BeamMode beamMode = BeamMode.ANCHORED;
// Free Aim (players only) - steers beam toward player's look direction
private boolean freeAim = false;
private static final float FREE_AIM_STRENGTH = 0.15f;
// Charging state (beam-specific)
private float chargeOffsetDistance = 1.0f;
private int trailFadeTime = 20; // Ticks for trail to fully fade
@@ -433,8 +438,64 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
addTrailPoint();
}
/**
* Steer beam toward player's look direction (Free Aim mode).
* Target point is projected along look vector at the current head distance from origin.
*/
private void updateFreeAim() {
Entity owner = getOwnerEntity();
if (!(owner instanceof EntityPlayer)) return;
Vec3 look = getOwnerLookVector();
if (look == null) return;
double headDist = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ);
if (headDist < 0.1) return;
// Target point along look vector at current head distance
double targetX = startX + look.xCoord * headDist;
double targetY = startY + look.yCoord * headDist;
double targetZ = startZ + look.zCoord * headDist;
// Current head world position
double headWorldX = startX + headOffsetX;
double headWorldY = startY + headOffsetY;
double headWorldZ = startZ + headOffsetZ;
double dx = targetX - headWorldX;
double dy = targetY - headWorldY;
double dz = targetZ - headWorldZ;
double dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist < 0.01) return;
double desiredVX = (dx / dist) * getSpeed();
double desiredVY = (dy / dist) * getSpeed();
double desiredVZ = (dz / dist) * getSpeed();
motionX += (desiredVX - motionX) * FREE_AIM_STRENGTH;
motionY += (desiredVY - motionY) * FREE_AIM_STRENGTH;
motionZ += (desiredVZ - motionZ) * FREE_AIM_STRENGTH;
double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ);
if (vLen > 0) {
motionX = (motionX / vLen) * getSpeed();
motionY = (motionY / vLen) * getSpeed();
motionZ = (motionZ / vLen) * getSpeed();
}
}
@Override
protected void updateHoming() {
if (freeAim) {
Entity owner = getOwnerEntity();
if (owner instanceof EntityPlayer) {
updateFreeAim();
return;
}
// NPCs fall through to normal homing
}
if (!isHoming()) return;
Entity target = getTargetEntity();
@@ -545,6 +606,14 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
setBeamMode(modeFromAnchored(attached));
}
public boolean isFreeAim() {
return freeAim;
}
public void setFreeAim(boolean freeAim) {
this.freeAim = freeAim;
}
/**
* Get interpolated head offset for smooth rendering.
* Returns offset RELATIVE to origin.
@@ -630,7 +699,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
// ==================== REFLECTION ====================
@Override
protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) {
protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) {
boolean reflected = super.reflectFromBarrier(barrier, reflectStrengthPct);
if (reflected) {
// Switch to FREE_TRAIL: detach from caster (tail-less), trail fades out.
@@ -643,9 +712,14 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
resetHeadOffsets();
resetTrailStorage();
// Disable homing — reflected beams fly straight.
homingData.setHoming(false);
setTargetEntityId(-1);
// Free aim only works for the original caster
freeAim = false;
// If targeting owner, keep homing so beam tracks back to caster
if (!barrier.getBarrierData().isTargetOwner()) {
homingData.setHoming(false);
setTargetEntityId(-1);
}
}
return reflected;
}
@@ -668,6 +742,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
resetHeadOffsets();
resetTrailStorage();
homingData.setHoming(false);
freeAim = false;
setTargetEntityId(-1);
}
@@ -686,6 +761,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
readChargingNBT(nbt);
this.chargeOffsetDistance = nbt.hasKey("ChargeOffsetDistance") ? nbt.getFloat("ChargeOffsetDistance") : 1.0f;
this.trailFadeTime = nbt.hasKey("TrailFadeTime") ? nbt.getInteger("TrailFadeTime") : 20;
this.freeAim = nbt.getBoolean("FreeAim");
boolean attachedLegacy = !nbt.hasKey("AttachedToOwner") || nbt.getBoolean("AttachedToOwner");
BeamMode loadedMode = modeFromAnchored(attachedLegacy);
@@ -737,6 +813,7 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
nbt.setString("BeamMode", beamMode.name());
writeChargingNBT(nbt);
nbt.setFloat("ChargeOffsetDistance", chargeOffsetDistance);
nbt.setBoolean("FreeAim", freeAim);
nbt.setBoolean("FadeTrail", isFadingMode());
nbt.setInteger("TrailFadeTime", trailFadeTime);
@@ -409,7 +409,7 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
// ==================== REFLECTION ====================
@Override
protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) {
protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) {
boolean reflected = super.reflectFromBarrier(barrier, reflectStrengthPct);
if (reflected) {
// Disable boomerang on reflected discs — the original owner is no longer
@@ -419,8 +419,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
private boolean checkLaserBarrierCollision() {
if (currentLength <= 0) return false;
List<EntityAbilityBarrier> barriers = EntityAbilityBarrier.getActiveBarriers(worldObj);
for (EntityAbilityBarrier barrier : barriers) {
List<EntityEnergyBarrier> barriers = EntityEnergyBarrier.getActiveBarriers(worldObj);
for (EntityEnergyBarrier barrier : barriers) {
if (barrier.isDead || barrier.isCharging()) continue;
if (barrier.getOwnerEntityId() == this.ownerEntityId) continue;
@@ -433,17 +433,17 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
}
}
if (barrier instanceof EntityAbilityDome) {
EntityAbilityDome dome = (EntityAbilityDome) barrier;
if (barrier instanceof EntityEnergyDome) {
EntityEnergyDome dome = (EntityEnergyDome) barrier;
float intersectDist = getLineSphereIntersection(dome);
if (intersectDist >= 0) {
float damage = getModifiedDamage();
EntityAbilityBarrier.ProjectileHitOutcome hitOutcome = dome.onProjectileHitResolved(this, damage);
if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) {
EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = dome.onProjectileHitResolved(this, damage);
if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) {
continue;
}
if (hitOutcome.result != EntityAbilityBarrier.ProjectileHitResult.BROKEN) {
if (hitOutcome.result != EntityEnergyBarrier.ProjectileHitResult.BROKEN) {
currentLength = Math.max(0.0f, intersectDist);
endX = startX + dirX * currentLength;
endY = startY + dirY * currentLength;
@@ -469,12 +469,12 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
if (incoming) {
float damage = getModifiedDamage();
EntityAbilityBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage);
if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) {
EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage);
if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) {
continue;
}
if (hitOutcome.result != EntityAbilityBarrier.ProjectileHitResult.BROKEN) {
if (hitOutcome.result != EntityEnergyBarrier.ProjectileHitResult.BROKEN) {
endX = startX + dirX * currentLength;
endY = startY + dirY * currentLength;
endZ = startZ + dirZ * currentLength;
@@ -491,7 +491,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
}
@Override
protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) {
protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) {
if (barrier == null) {
return false;
}
@@ -568,12 +568,21 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
}
sourceAbility = null;
// Save original owner before transfer for potential target retargeting
int originalOwnerId = ownerEntityId;
Entity barrierOwner = barrier.getOwnerEntity();
if (barrierOwner != null) {
setOwnerEntityId(barrierOwner.getEntityId());
trackProjectile(this);
}
setTargetEntityId(-1);
// Target Owner: set the reflected projectile's target to the original caster
if (barrier.getBarrierData().isTargetOwner() && originalOwnerId != -1) {
setTargetEntityId(originalOwnerId);
} else {
setTargetEntityId(-1);
}
setInnerColor(barrier.getInnerColor());
setOuterColor(barrier.getOuterColor());
@@ -593,7 +602,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
* Returns the distance along the laser direction to the first entry point,
* or -1 if no intersection from outside.
*/
private float getLineSphereIntersection(EntityAbilityDome dome) {
private float getLineSphereIntersection(EntityEnergyDome dome) {
double cx = dome.posX;
double cy = dome.posY;
double cz = dome.posZ;
@@ -88,6 +88,15 @@ public abstract class EntityEnergyAbility extends Entity implements IEntityAddit
this.chargeDuration = duration;
}
/**
* Reset chargeTick back to chargeDuration so the charging timeout
* grace period restarts. Used by items that let the player hold
* a fully-charged orb indefinitely.
*/
public void resetChargeTick() {
this.chargeTick = this.chargeDuration;
}
public float getChargeProgress() {
if (chargeDuration <= 0) return 1.0f;
return Math.min(1.0f, (float) chargeTick / chargeDuration);
@@ -25,7 +25,7 @@ import java.util.List;
* and barrier lifecycle management.
* Extends EntityEnergyAbility for shared visual/owner/charging state.
*/
public abstract class EntityAbilityBarrier extends EntityEnergyAbility {
public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
/**
* Outcome of a projectile vs barrier interaction.
@@ -72,26 +72,26 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility {
}
public boolean shouldReflect() {
return reflectEnabled && useHealth && result == ProjectileHitResult.BLOCKED;
return reflectEnabled && result == ProjectileHitResult.BLOCKED;
}
}
// ==================== ACTIVE BARRIER REGISTRY ====================
private static final List<WeakReference<EntityAbilityBarrier>> activeBarriers = new ArrayList<>();
private static final List<WeakReference<EntityEnergyBarrier>> activeBarriers = new ArrayList<>();
private boolean tracked = false;
public static void trackBarrier(EntityAbilityBarrier barrier) {
public static void trackBarrier(EntityEnergyBarrier barrier) {
activeBarriers.add(new WeakReference<>(barrier));
}
/**
* Get all living barriers in the given world. Auto-cleans dead refs.
*/
public static List<EntityAbilityBarrier> getActiveBarriers(World world) {
List<EntityAbilityBarrier> result = new ArrayList<>();
Iterator<WeakReference<EntityAbilityBarrier>> it = activeBarriers.iterator();
public static List<EntityEnergyBarrier> getActiveBarriers(World world) {
List<EntityEnergyBarrier> result = new ArrayList<>();
Iterator<WeakReference<EntityEnergyBarrier>> it = activeBarriers.iterator();
while (it.hasNext()) {
EntityAbilityBarrier b = it.next().get();
EntityEnergyBarrier b = it.next().get();
if (b == null || b.isDead) {
it.remove();
} else if (b.worldObj == world) {
@@ -114,7 +114,7 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility {
protected static final int DW_HEALTH_PERCENT = 21;
protected static final int DW_HIT_FLASH = 22;
public EntityAbilityBarrier(World world) {
public EntityEnergyBarrier(World world) {
super(world);
this.noClip = true;
}
@@ -267,7 +267,7 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility {
healthBefore,
0.0f,
0.0f,
false,
barrierData.reflect,
barrierData.reflectStrengthPct,
false
);
@@ -506,10 +506,10 @@ public abstract class EntityAbilityBarrier extends EntityEnergyAbility {
* Find a barrier that would absorb damage for the given entity (its caster).
* Returns the barrier if: absorbing is enabled AND entity is the barrier's owner.
*/
public static EntityAbilityBarrier getAbsorbingBarrier(Entity entity) {
public static EntityEnergyBarrier getAbsorbingBarrier(Entity entity) {
if (entity == null || entity.worldObj == null) return null;
List<EntityAbilityBarrier> barriers = getActiveBarriers(entity.worldObj);
for (EntityAbilityBarrier barrier : barriers) {
List<EntityEnergyBarrier> barriers = getActiveBarriers(entity.worldObj);
for (EntityEnergyBarrier barrier : barriers) {
if (barrier.isDead) continue;
if (!barrier.barrierData.absorbing) continue;
if (barrier.ownerEntityId == entity.getEntityId()) {
@@ -22,29 +22,32 @@ import java.util.List;
* Energy Dome entity - a spherical barrier that blocks incoming energy projectiles.
* Centered on the caster's position at time of casting.
* Only blocks incoming attacks (not outgoing from allies inside).
* Extends EntityAbilityBarrier for shared barrier logic.
* Extends EntityEnergyBarrier for shared barrier logic.
*/
public class EntityAbilityDome extends EntityAbilityBarrier {
public class EntityEnergyDome extends EntityEnergyBarrier {
// ==================== DOME-SPECIFIC PROPERTIES ====================
protected float domeRadius = 5.0f;
protected float targetDomeRadius = 5.0f;
protected boolean followCaster = false;
protected float offsetX = 0.0f;
protected float offsetY = 0.0f;
protected float offsetZ = 0.0f;
// Server-side melee detection state
private boolean inTickMelee = false;
private final HashSet<Integer> processedMeleeSwings = new HashSet<>();
public EntityAbilityDome(World world) {
public EntityEnergyDome(World world) {
super(world);
this.noClip = true;
this.stepHeight = 0.0F;
this.setSize(1.0f, 1.0f);
}
public EntityAbilityDome(World world, EntityLivingBase owner, double x, double y, double z,
float domeRadius, EnergyDisplayData display, EnergyLightningData lightning,
EnergyBarrierData barrier) {
public EntityEnergyDome(World world, EntityLivingBase owner, double x, double y, double z,
float domeRadius, EnergyDisplayData display, EnergyLightningData lightning,
EnergyBarrierData barrier) {
this(world);
this.noClip = true;
this.stepHeight = 0.0F;
@@ -81,11 +84,11 @@ public class EntityAbilityDome extends EntityAbilityBarrier {
if (followCaster) {
Entity owner = ownerEntityId >= 0 ? worldObj.getEntityByID(ownerEntityId) : null;
if (owner != null) {
this.setPosition(owner.posX, owner.posY, owner.posZ);
this.setPosition(owner.posX + offsetX, owner.posY + offsetY, owner.posZ + offsetZ);
// Sync prevPos with owner's prevPos for smooth interpolation
this.prevPosX = owner.prevPosX;
this.prevPosY = owner.prevPosY;
this.prevPosZ = owner.prevPosZ;
this.prevPosX = owner.prevPosX + offsetX;
this.prevPosY = owner.prevPosY + offsetY;
this.prevPosZ = owner.prevPosZ + offsetZ;
}
}
@@ -186,13 +189,17 @@ public class EntityAbilityDome extends EntityAbilityBarrier {
}
}
double prevX = projectile.posX - projectile.motionX;
double prevY = projectile.posY - projectile.motionY;
double prevZ = projectile.posZ - projectile.motionZ;
// Test the UPCOMING movement (this tick) so the barrier intercepts before
// entity collision runs in updateProjectile(). Using the previous tick's
// segment caused small domes to miss fast projectiles that could cross the
// dome and hit the player in a single tick.
double nextX = projectile.posX + projectile.motionX;
double nextY = projectile.posY + projectile.motionY;
double nextZ = projectile.posZ + projectile.motionZ;
return isIncomingRay(
nextX, nextY, nextZ,
projectile.posX, projectile.posY, projectile.posZ,
prevX, prevY, prevZ,
projectile.getOwnerEntityId());
}
@@ -585,6 +592,12 @@ public class EntityAbilityDome extends EntityAbilityBarrier {
this.followCaster = follow;
}
public void setOffsets(float x, float y, float z) {
this.offsetX = x;
this.offsetY = y;
this.offsetZ = z;
}
@Override
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int increments) {
@@ -627,6 +640,9 @@ public class EntityAbilityDome extends EntityAbilityBarrier {
nbt.setFloat("DomeRadius", domeRadius);
nbt.setFloat("TargetDomeRadius", targetDomeRadius);
nbt.setBoolean("FollowCaster", followCaster);
nbt.setFloat("OffsetX", offsetX);
nbt.setFloat("OffsetY", offsetY);
nbt.setFloat("OffsetZ", offsetZ);
}
@Override
@@ -635,5 +651,8 @@ public class EntityAbilityDome extends EntityAbilityBarrier {
this.setDomeRadius(sanitize(nbt.getFloat("DomeRadius"), 5.0f, MAX_ENTITY_RADIUS));
this.targetDomeRadius = sanitize(nbt.hasKey("TargetDomeRadius") ? nbt.getFloat("TargetDomeRadius") : domeRadius, 5.0f, MAX_ENTITY_RADIUS);
this.followCaster = nbt.hasKey("FollowCaster") && nbt.getBoolean("FollowCaster");
this.offsetX = nbt.hasKey("OffsetX") ? nbt.getFloat("OffsetX") : 0.0f;
this.offsetY = nbt.hasKey("OffsetY") ? nbt.getFloat("OffsetY") : 0.0f;
this.offsetZ = nbt.hasKey("OffsetZ") ? nbt.getFloat("OffsetZ") : 0.0f;
}
}
@@ -21,9 +21,9 @@ import java.util.List;
/**
* Energy Panel entity - a flat rectangular barrier used by Wall and Shield abilities.
* Supports three modes: PLACED (stationary), HELD (tracks caster), LAUNCHED (moves forward).
* Extends EntityAbilityBarrier for shared barrier logic.
* Extends EntityEnergyBarrier for shared barrier logic.
*/
public class EntityAbilityPanel extends EntityAbilityBarrier {
public class EntityEnergyPanel extends EntityEnergyBarrier {
public enum PanelMode {
PLACED, // Stationary wall
@@ -41,15 +41,15 @@ public class EntityAbilityPanel extends EntityAbilityBarrier {
protected float targetPanelWidth;
protected float targetPanelHeight;
public EntityAbilityPanel(World world) {
public EntityEnergyPanel(World world) {
super(world);
this.setSize(0.5f, 0.5f);
}
public EntityAbilityPanel(World world, EntityLivingBase owner, double x, double y, double z,
float yaw, PanelMode mode,
EnergyDisplayData display, EnergyLightningData lightning,
EnergyBarrierData barrier, EnergyPanelData panel) {
public EntityEnergyPanel(World world, EntityLivingBase owner, double x, double y, double z,
float yaw, PanelMode mode,
EnergyDisplayData display, EnergyLightningData lightning,
EnergyBarrierData barrier, EnergyPanelData panel) {
this(world);
this.setPosition(x, y + panel.heightOffset, z);
this.ownerEntityId = owner.getEntityId();
@@ -157,17 +157,17 @@ public class EntityAbilityPanel extends EntityAbilityBarrier {
// Follow owner position
float frontDist = 1.5f;
float yawRad = (float) Math.toRadians(panelYaw);
double newX = owner.posX + (-Math.sin(yawRad) * frontDist);
double newX = owner.posX + (-Math.sin(yawRad) * frontDist) + panelData.offsetX;
double newY = owner.posY + panelData.heightOffset + (owner.height * 0.5f);
double newZ = owner.posZ + (Math.cos(yawRad) * frontDist);
double newZ = owner.posZ + (Math.cos(yawRad) * frontDist) + panelData.offsetZ;
this.setPosition(newX, newY, newZ);
// Sync prevPos with owner's prevPos for smooth interpolation
float prevYawRad = (float) Math.toRadians(owner.prevRotationYaw);
this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist);
this.prevPosX = owner.prevPosX + (-Math.sin(prevYawRad) * frontDist) + panelData.offsetX;
this.prevPosY = owner.prevPosY + panelData.heightOffset + (owner.height * 0.5f);
this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist);
this.prevPosZ = owner.prevPosZ + (Math.cos(prevYawRad) * frontDist) + panelData.offsetZ;
}
@Override
@@ -340,13 +340,15 @@ public class EntityAbilityPanel extends EntityAbilityBarrier {
}
}
double prevX = projectile.posX - projectile.motionX;
double prevY = projectile.posY - projectile.motionY;
double prevZ = projectile.posZ - projectile.motionZ;
// Test the UPCOMING movement so the barrier intercepts before entity
// collision runs in updateProjectile().
double nextX = projectile.posX + projectile.motionX;
double nextY = projectile.posY + projectile.motionY;
double nextZ = projectile.posZ + projectile.motionZ;
return isIncomingRay(
nextX, nextY, nextZ,
projectile.posX, projectile.posY, projectile.posZ,
prevX, prevY, prevZ,
projectile.getOwnerEntityId());
}
@@ -439,8 +439,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
* @return true if barrier interaction was handled (caller should stop processing this tick)
*/
protected boolean checkBarrierCollision() {
List<EntityAbilityBarrier> barriers = EntityAbilityBarrier.getActiveBarriers(worldObj);
for (EntityAbilityBarrier barrier : barriers) {
List<EntityEnergyBarrier> barriers = EntityEnergyBarrier.getActiveBarriers(worldObj);
for (EntityEnergyBarrier barrier : barriers) {
if (barrier.isDead) continue;
// Quick distance pre-filter
@@ -453,8 +453,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
if (barrier.isIncomingProjectile(this)) {
float damage = getModifiedDamage();
EntityAbilityBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage);
if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) {
EntityEnergyBarrier.ProjectileHitOutcome hitOutcome = barrier.onProjectileHitResolved(this, damage);
if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) {
continue;
}
if (handleBarrierHitOutcome(barrier, hitOutcome, damage)) {
@@ -473,12 +473,12 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
* @param fullDamage The DBC-scaled damage that was passed to the barrier (from getModifiedDamage).
* @return true if caller should stop processing this tick.
*/
protected boolean handleBarrierHitOutcome(EntityAbilityBarrier barrier, EntityAbilityBarrier.ProjectileHitOutcome hitOutcome, float fullDamage) {
if (hitOutcome == null || hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.PASS) {
protected boolean handleBarrierHitOutcome(EntityEnergyBarrier barrier, EntityEnergyBarrier.ProjectileHitOutcome hitOutcome, float fullDamage) {
if (hitOutcome == null || hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.PASS) {
return false;
}
if (hitOutcome.result == EntityAbilityBarrier.ProjectileHitResult.BROKEN) {
if (hitOutcome.result == EntityEnergyBarrier.ProjectileHitResult.BROKEN) {
if (hitOutcome.remainingProjectileDamage <= 0.0f) {
damageMultiplier = 0.0f;
setBarrierSparkTicks(Math.max(getBarrierSparkTicks(), BARRIER_BREAK_SPARK_TICKS));
@@ -511,7 +511,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
return true;
}
protected boolean reflectFromBarrier(EntityAbilityBarrier barrier, float reflectStrengthPct) {
protected boolean reflectFromBarrier(EntityEnergyBarrier barrier, float reflectStrengthPct) {
if (barrier == null) {
return false;
}
@@ -582,14 +582,22 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
}
sourceAbility = null;
// Save original owner before transfer for potential target retargeting
int originalOwnerId = ownerEntityId;
Entity barrierOwner = barrier.getOwnerEntity();
if (barrierOwner != null) {
setOwnerEntityId(barrierOwner.getEntityId());
// Ensure ownership-sensitive systems can query this projectile under the new owner.
trackProjectile(this);
}
// Old homing target may now be the new owner or ally; clear it after reflection.
setTargetEntityId(-1);
// Target Owner: set the reflected projectile's target to the original caster
if (barrier.getBarrierData().isTargetOwner() && originalOwnerId != -1) {
setTargetEntityId(originalOwnerId);
} else {
setTargetEntityId(-1);
}
setInnerColor(barrier.getInnerColor());
setOuterColor(barrier.getOuterColor());
@@ -672,14 +680,14 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
ProjectileReflectPacket.sendToTracking(this, writeReflectionData());
}
protected double[] getBarrierImpactNormal(EntityAbilityBarrier barrier, double velocityX, double velocityY, double velocityZ) {
if (barrier instanceof EntityAbilityDome) {
EntityAbilityDome dome = (EntityAbilityDome) barrier;
protected double[] getBarrierImpactNormal(EntityEnergyBarrier barrier, double velocityX, double velocityY, double velocityZ) {
if (barrier instanceof EntityEnergyDome) {
EntityEnergyDome dome = (EntityEnergyDome) barrier;
return normalizeVector(posX - dome.posX, posY - dome.posY, posZ - dome.posZ, velocityX, velocityY, velocityZ);
}
if (barrier instanceof EntityAbilityPanel) {
EntityAbilityPanel panel = (EntityAbilityPanel) barrier;
if (barrier instanceof EntityEnergyPanel) {
EntityEnergyPanel panel = (EntityEnergyPanel) barrier;
float yawRad = (float) Math.toRadians(panel.getPanelYaw());
double nx = -Math.sin(yawRad);
double nz = Math.cos(yawRad);
@@ -716,7 +724,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
return new double[]{0.0, 1.0, 0.0};
}
protected void beginBarrierImpactPause(boolean destroyOnResume, EntityAbilityBarrier barrier) {
protected void beginBarrierImpactPause(boolean destroyOnResume, EntityEnergyBarrier barrier) {
if (barrierImpactPauseTicks <= 0) {
pausedMotionX = motionX;
pausedMotionY = motionY;
@@ -740,12 +748,12 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
return Math.max(0.06f, Math.min(0.22f, size * 0.18f + 0.03f));
}
protected void snapOutsideBarrierForPause(EntityAbilityBarrier barrier) {
protected void snapOutsideBarrierForPause(EntityEnergyBarrier barrier) {
if (barrier == null) return;
float bias = getBarrierPauseOutsideDistance();
if (barrier instanceof EntityAbilityDome) {
EntityAbilityDome dome = (EntityAbilityDome) barrier;
if (barrier instanceof EntityEnergyDome) {
EntityEnergyDome dome = (EntityEnergyDome) barrier;
double nx = posX - dome.posX;
double ny = posY - dome.posY;
double nz = posZ - dome.posZ;
@@ -776,8 +784,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
return;
}
if (barrier instanceof EntityAbilityPanel) {
EntityAbilityPanel panel = (EntityAbilityPanel) barrier;
if (barrier instanceof EntityEnergyPanel) {
EntityEnergyPanel panel = (EntityEnergyPanel) barrier;
float yawRad = (float) Math.toRadians(panel.getPanelYaw());
double normalX = -Math.sin(yawRad);
double normalZ = Math.cos(yawRad);
@@ -29,7 +29,7 @@ import java.util.Set;
* <p>
* Design: Similar to Beam trail visuals but rotating around origin.
*/
public class EntityAbilitySweeper extends EntityEnergyAbility {
public class EntityEnergySweeper extends EntityEnergyAbility {
// Beam properties
private float beamLength = 10.0f;
@@ -61,18 +61,18 @@ public class EntityAbilitySweeper extends EntityEnergyAbility {
private transient int ticksSinceDamage = 0;
private transient Set<Integer> hitThisTick = new HashSet<>();
public EntityAbilitySweeper(World world) {
public EntityEnergySweeper(World world) {
super(world);
this.setSize(0.1f, 0.1f);
this.noClip = true;
}
public EntityAbilitySweeper(World world, EntityLivingBase owner, EntityLivingBase target,
float beamLength, float beamWidth, float beamHeight,
EnergyDisplayData displayData,
float sweepSpeed, int numberOfRotations,
float damage, int damageInterval, boolean piercing,
boolean lockOnTarget) {
public EntityEnergySweeper(World world, EntityLivingBase owner, EntityLivingBase target,
float beamLength, float beamWidth, float beamHeight,
EnergyDisplayData displayData,
float sweepSpeed, int numberOfRotations,
float damage, int damageInterval, boolean piercing,
boolean lockOnTarget) {
this(world);
this.ownerEntityId = owner.getEntityId();
@@ -226,6 +226,8 @@ import kamkeel.npcs.network.packets.request.role.RoleCompanionUpdatePacket;
import kamkeel.npcs.network.packets.request.role.RoleGetPacket;
import kamkeel.npcs.network.packets.request.role.RoleSavePacket;
import kamkeel.npcs.network.packets.request.script.BlockScriptPacket;
import kamkeel.npcs.network.packets.request.script.AbilityScriptPacket;
import kamkeel.npcs.network.packets.request.script.ChainedAbilityScriptPacket;
import kamkeel.npcs.network.packets.request.script.EffectScriptPacket;
import kamkeel.npcs.network.packets.request.script.EventScriptPacket;
import kamkeel.npcs.network.packets.request.script.ForgeScriptPacket;
@@ -316,6 +318,8 @@ public class PacketHandler {
REQUEST_PACKET.registerPacket(new ScriptInfoPacket());
REQUEST_PACKET.registerPacket(new ScriptFilesPacket());
REQUEST_PACKET.registerPacket(new EffectScriptPacket());
REQUEST_PACKET.registerPacket(new AbilityScriptPacket());
REQUEST_PACKET.registerPacket(new ChainedAbilityScriptPacket());
// Cloner Packets
REQUEST_PACKET.registerPacket(new CloneListPacket());
@@ -214,4 +214,6 @@ public enum EnumRequestPacket {
RecipeScript,
ManageAuctionAction,
AbilityScript,
ChainedAbilityScript,
}
@@ -62,7 +62,7 @@ public final class BuiltInAbilityGetPacket extends AbstractPacket {
String name = ByteBufUtils.readString(in);
Ability ability = AbilityController.Instance.getAbilityByDisplayName(name);
if (ability != null) {
NBTTagCompound compound = ability.writeNBT();
NBTTagCompound compound = ability.writeNBT(false);
compound.setBoolean("BuiltIn", true);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
}
@@ -61,7 +61,7 @@ public final class ChainedAbilityGetPacket extends AbstractPacket {
String chainName = ByteBufUtils.readString(in);
ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName);
if (chain != null) {
NBTTagCompound compound = chain.writeNBT();
NBTTagCompound compound = chain.writeNBT(false);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
}
}
@@ -73,7 +73,7 @@ public final class ChainedAbilitySavePacket extends AbstractPacket {
if (chain.getName() != null && !chain.getName().isEmpty()) {
AbilityController.Instance.saveChainedAbility(chain);
NoppesUtilServer.sendChainedAbilitiesData((EntityPlayerMP) player);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, chain.writeNBT());
GuiDataPacket.sendGuiData((EntityPlayerMP) player, chain.writeNBT(false));
}
}
}
@@ -61,7 +61,7 @@ public final class CustomAbilityGetPacket extends AbstractPacket {
String abilityName = ByteBufUtils.readString(in);
Ability ability = AbilityController.Instance.getCustomAbility(abilityName);
if (ability != null) {
NBTTagCompound compound = ability.writeNBT();
NBTTagCompound compound = ability.writeNBT(false);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound);
}
}
@@ -70,7 +70,7 @@ public final class CustomAbilitySavePacket extends AbstractPacket {
if (ability != null) {
AbilityController.Instance.saveCustomAbility(ability);
NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player);
NBTTagCompound responseNbt = ability.writeNBT();
NBTTagCompound responseNbt = ability.writeNBT(false);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, responseNbt);
}
}
@@ -0,0 +1,117 @@
package kamkeel.npcs.network.packets.request.script;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.LogWriter;
import noppes.npcs.config.ConfigDebug;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.controllers.data.AbilityScript;
import noppes.npcs.controllers.data.IScriptHandler;
import java.io.IOException;
public final class AbilityScriptPacket extends AbstractPacket {
public static String packetName = "Request|AbilityScript";
private Action type;
private String abilityId;
private int page;
private int maxSize;
private NBTTagCompound compound;
public AbilityScriptPacket() {
}
public AbilityScriptPacket(Action type, String abilityId, int page, int maxSize, NBTTagCompound compound) {
this.type = type;
this.abilityId = abilityId;
this.page = page;
this.maxSize = maxSize;
this.compound = compound;
}
@Override
public Enum getType() {
return EnumRequestPacket.AbilityScript;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.REQUEST_PACKET;
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.SCRIPT_PLAYER;
}
@SideOnly(Side.CLIENT)
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeInt(type.ordinal());
ByteBufUtils.writeUTF8String(out, abilityId);
if (type == Action.SAVE) {
out.writeInt(this.page);
out.writeInt(this.maxSize);
ByteBufUtils.writeNBT(out, this.compound);
}
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP))
return;
if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT))
return;
Action requestedAction = Action.values()[in.readInt()];
String id = ByteBufUtils.readUTF8String(in);
Ability ability = AbilityController.Instance.resolveAbility(id);
if (ability == null)
return;
AbilityScript data = ability.getOrCreateScriptHandler();
if (requestedAction == Action.GET) {
PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player);
} else {
data.saveScript(in);
// Persist to disk
AbilityController.Instance.saveCustomAbility(ability);
if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
LogWriter.script(String.format("[%s] (Player) %s SAVED ABILITY SCRIPT %s [%s]",
"ABILITY SCRIPTS", player.getCommandSenderName(), ability.getName(), ability.getId()));
}
}
}
public static void Save(String abilityId, int id, int maxSize, NBTTagCompound compound) {
PacketClient.sendClient(new AbilityScriptPacket(Action.SAVE, abilityId, id, maxSize, compound));
}
public static void Get(String abilityId) {
PacketClient.sendClient(new AbilityScriptPacket(Action.GET, abilityId, -1, -1, new NBTTagCompound()));
}
private enum Action {
GET,
SAVE
}
}
@@ -0,0 +1,117 @@
package kamkeel.npcs.network.packets.request.script;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.LogWriter;
import noppes.npcs.config.ConfigDebug;
import noppes.npcs.config.ConfigScript;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import noppes.npcs.controllers.data.IScriptHandler;
import java.io.IOException;
public final class ChainedAbilityScriptPacket extends AbstractPacket {
public static String packetName = "Request|ChainedAbilityScript";
private Action type;
private String chainId;
private int page;
private int maxSize;
private NBTTagCompound compound;
public ChainedAbilityScriptPacket() {
}
public ChainedAbilityScriptPacket(Action type, String chainId, int page, int maxSize, NBTTagCompound compound) {
this.type = type;
this.chainId = chainId;
this.page = page;
this.maxSize = maxSize;
this.compound = compound;
}
@Override
public Enum getType() {
return EnumRequestPacket.ChainedAbilityScript;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.REQUEST_PACKET;
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.SCRIPT_PLAYER;
}
@SideOnly(Side.CLIENT)
@Override
public void sendData(ByteBuf out) throws IOException {
out.writeInt(type.ordinal());
ByteBufUtils.writeUTF8String(out, chainId);
if (type == Action.SAVE) {
out.writeInt(this.page);
out.writeInt(this.maxSize);
ByteBufUtils.writeNBT(out, this.compound);
}
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP))
return;
if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT))
return;
Action requestedAction = Action.values()[in.readInt()];
String id = ByteBufUtils.readUTF8String(in);
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(id);
if (chain == null)
return;
ChainedAbilityScript data = chain.getOrCreateScriptHandler();
if (requestedAction == Action.GET) {
PacketUtil.getScripts((IScriptHandler) data, (EntityPlayerMP) player);
} else {
data.saveScript(in);
// Persist to disk
AbilityController.Instance.saveChainedAbility(chain);
if (ConfigDebug.PlayerLogging && FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
LogWriter.script(String.format("[%s] (Player) %s SAVED CHAIN SCRIPT %s [%s]",
"CHAIN SCRIPTS", player.getCommandSenderName(), chain.getName(), chain.getId()));
}
}
}
public static void Save(String chainId, int id, int maxSize, NBTTagCompound compound) {
PacketClient.sendClient(new ChainedAbilityScriptPacket(Action.SAVE, chainId, id, maxSize, compound));
}
public static void Get(String chainId) {
PacketClient.sendClient(new ChainedAbilityScriptPacket(Action.GET, chainId, -1, -1, new NBTTagCompound()));
}
private enum Action {
GET,
SAVE
}
}
@@ -93,7 +93,7 @@ public class Register<T> {
public void register() {
for (Map.Entry<String, Supplier<Ability>> entry : entries.entrySet()) {
AbilityController.Instance.registerType(entry.getKey(), entry.getValue());
AbilityController.Instance.registerType(entry.getValue());
if (!typeOnly.contains(entry.getKey())) {
AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get());
}
@@ -2,6 +2,7 @@ package noppes.npcs;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityDefend;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
@@ -11,6 +12,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.DamageSource;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.scripted.event.AbilityEvent;
import noppes.npcs.controllers.data.Animation;
import java.util.ArrayList;
@@ -124,28 +126,53 @@ public abstract class AbstractDataAbilities {
*/
protected abstract long getWorldTime();
// -- Event Firing --
// -- Event Firing (unified via EventHooks) --
/**
* Fire tick event. Implementation differs between NPC (NpcAPI) and Player (ScriptController).
*/
protected abstract void fireTickEvent(Ability ability, EntityLivingBase target);
protected void fireTickEvent(Ability ability, EntityLivingBase target) {
EventHooks.onAbilityTick(ability, getEntity(), target, ability.getPhase().ordinal(), ability.getCurrentTick());
}
/**
* Fire execute event. Returns true if cancelled.
*/
protected abstract boolean fireExecuteEvent(Ability ability, EntityLivingBase target);
protected boolean fireExecuteEvent(Ability ability, EntityLivingBase target) {
return EventHooks.onAbilityExecute(ability, getEntity(), target);
}
/**
* Fire complete event.
*/
protected abstract void fireCompleteEvent(Ability ability, EntityLivingBase target);
protected void fireCompleteEvent(Ability ability, EntityLivingBase target) {
EventHooks.onAbilityComplete(ability, getEntity(), target);
}
/**
* Fire interrupt event.
*/
protected abstract void fireInterruptEvent(Ability ability, EntityLivingBase target,
DamageSource source, float damage);
protected void fireInterruptEvent(Ability ability, EntityLivingBase target,
DamageSource source, float damage) {
EventHooks.onAbilityInterrupt(ability, getEntity(), target, source, damage);
}
protected boolean fireToggleEvent(Ability ability, int oldState, int newState) {
return EventHooks.onAbilityToggle(ability, getEntity(), oldState, newState);
}
protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) {
AbilityEvent.ToggleUpdateEvent event = new AbilityEvent.ToggleUpdateEvent(getEntity(), ability, tick, state);
EventHooks.onAbilityToggleUpdate(ability, event);
return event.isEnabled();
}
// -- Chain Events (unified via EventHooks) --
protected void fireChainStartEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) {
EventHooks.onChainStart(chain, getEntity(), entryIndex, target);
}
protected void fireChainNextEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) {
EventHooks.onChainNext(chain, getEntity(), entryIndex, target);
}
protected void fireChainCompleteEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target) {
EventHooks.onChainComplete(chain, getEntity(), entryIndex, target);
}
protected void fireChainInterruptEvent(ChainedAbility chain, int entryIndex, EntityLivingBase target,
DamageSource source, float damage) {
EventHooks.onChainInterrupt(chain, getEntity(), entryIndex, target, source, damage);
}
// -- Telegraph --
@@ -291,6 +318,19 @@ public abstract class AbstractDataAbilities {
return currentAbility;
}
/**
* Get the active defend ability if one is currently defending.
*/
public AbilityDefend getActiveDefend() {
if (currentAbility instanceof AbilityDefend) {
AbilityDefend defend = (AbilityDefend) currentAbility;
if (defend.isDefending()) {
return defend;
}
}
return null;
}
/**
* Check if a chained ability is currently executing.
*/
@@ -391,8 +431,7 @@ public abstract class AbstractDataAbilities {
AbilityToggleEntry entry = new AbilityToggleEntry(ability, state);
activeToggles.put(key, entry);
ability.onToggleOn(getEntity());
ability.onToggleStateChanged(getEntity(), 0, state);
ability.onToggle(getEntity(), 0, state);
onToggleStateChanged(key, true, state);
return true;
}
@@ -404,7 +443,7 @@ public abstract class AbstractDataAbilities {
if (fireToggleEvent(ability, oldState, newState)) return oldState;
entry.setState(newState);
ability.onToggleStateChanged(getEntity(), oldState, newState);
ability.onToggle(getEntity(), oldState, newState);
onToggleStateChanged(key, true, newState);
return newState;
}
@@ -417,8 +456,7 @@ public abstract class AbstractDataAbilities {
if (fireToggleEvent(entry.getAbility(), oldState, 0)) return;
activeToggles.remove(key);
entry.getAbility().onToggleOff(getEntity());
entry.getAbility().onToggleStateChanged(getEntity(), oldState, 0);
entry.getAbility().onToggle(getEntity(), oldState, 0);
onToggleStateChanged(key, false, 0);
}
@@ -460,8 +498,7 @@ public abstract class AbstractDataAbilities {
AbilityToggleEntry entry = activeToggles.remove(key);
if (entry != null) {
int oldState = entry.getState();
entry.getAbility().onToggleOff(entity);
entry.getAbility().onToggleStateChanged(entity, oldState, 0);
entry.getAbility().onToggle(entity, oldState, 0);
onToggleStateChanged(key, false, 0);
}
}
@@ -474,41 +511,23 @@ public abstract class AbstractDataAbilities {
protected void onToggleStateChanged(String key, boolean active, int state) {
}
/**
* Fire a toggle event before state change.
* @param oldState Previous state (0 = off)
* @param newState Target state (0 = off)
* @return true if the event was canceled
*/
protected boolean fireToggleEvent(Ability ability, int oldState, int newState) {
return false;
}
/**
* Fire a toggle update event every 10 ticks.
* @return true if the toggle should remain active, false to force-deactivate
*/
protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) {
return true;
}
/**
* Clear all active toggles (e.g., on death/reset).
* Calls onToggleOff and onToggleStateChanged for each active toggle.
* Calls onToggle for each active toggle to signal deactivation.
*/
protected void clearActiveToggles() {
if (activeToggles.isEmpty()) return;
EntityLivingBase entity = getEntity();
for (Map.Entry<String, AbilityToggleEntry> mapEntry : activeToggles.entrySet()) {
AbilityToggleEntry entry = mapEntry.getValue();
entry.getAbility().onToggleOff(entity);
entry.getAbility().onToggleStateChanged(entity, entry.getState(), 0);
entry.getAbility().onToggle(entity, entry.getState(), 0);
}
activeToggles.clear();
}
/**
* Add a toggle entry directly without calling onToggleOn.
* Add a toggle entry directly without calling onToggle.
* Used for client-side sync and NBT restoration.
* @param key The ability key
* @param state The toggle state (0 = remove, 1+ = set at state)
@@ -747,6 +766,7 @@ public abstract class AbstractDataAbilities {
}
}
if (startChainEntry(chainTarget)) {
fireChainNextEvent(currentChain, chainEntryIndex, chainTarget);
launchConsecutiveConcurrentEntries(chainTarget);
}
}
@@ -849,6 +869,24 @@ public abstract class AbstractDataAbilities {
currentAbility.onActiveTick(entity, target, currentAbility.getCurrentTick());
// Play pending defend reaction animation + sound (counter strike, dodge roll, etc.)
if (currentAbility instanceof AbilityDefend) {
AbilityDefend defend = (AbilityDefend) currentAbility;
Animation defendAnim = defend.consumeDefendAnimation();
if (defendAnim != null) {
playAbilityAnimation(defendAnim);
playAbilitySound(currentAbility.getActiveSound());
defend.scheduleReturnToActive(currentAbility.getCurrentTick(), defendAnim);
}
// Return to active animation after defend animation finishes (Counter → guard stance)
if (defend.shouldReturnToActiveAnimation(currentAbility.getCurrentTick())) {
Animation activeAnim = currentAbility.getActiveAnimation();
if (activeAnim != null) {
playAbilityAnimation(activeAnim);
}
}
}
// Check if ability completed during onActiveTick
if (currentAbility.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(target);
@@ -1036,10 +1074,11 @@ public abstract class AbstractDataAbilities {
releaseRotationControl();
releaseLockedPosition();
// If chain was active, roll chain cooldown and clear chain state
// If chain was active, fire interrupt event, roll cooldown and clear chain state
if (currentChain != null) {
rollChainCooldown(currentChain);
interruptCooldownRolled = true;
fireChainInterruptEvent(currentChain, chainEntryIndex, getTarget(), source, damage);
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -1116,6 +1155,25 @@ public abstract class AbstractDataAbilities {
onAbilityComplete();
}
/**
* Cleanly complete the currently executing ability.
* Unlike cancel/interrupt, this triggers the normal completion path
* (fires abilityComplete event, rolls cooldown, advances chains).
* Only works during the ACTIVE phase.
*/
public void completeCurrentAbility() {
if (currentAbility == null || !currentAbility.isExecuting()) return;
if (currentAbility.getPhase() != AbilityPhase.ACTIVE) return;
// Signal completion on the ability (handles cleanup, detach/freeOnCast, burst logic)
if (!currentAbility.signalCompletion()) return;
// If signalCompletion moved to IDLE, handle the clean completion path
if (currentAbility.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(getTarget());
}
}
// ═══════════════════════════════════════════════════════════════════
// CHAINED ABILITY EXECUTION
// ═══════════════════════════════════════════════════════════════════
@@ -1137,6 +1195,7 @@ public abstract class AbstractDataAbilities {
// AFTER semantics: no delay before first entry (delay applies after each entry completes)
boolean started = startChainEntry(target);
if (started) {
fireChainStartEvent(currentChain, 0, target);
launchConsecutiveConcurrentEntries(target);
}
return started;
@@ -1253,7 +1312,7 @@ public abstract class AbstractDataAbilities {
chainEntryIndex++;
// Deep copy the ability so it has its own state
Ability concurrentCopy = AbilityController.Instance.fromNBT(resolved.writeNBT());
Ability concurrentCopy = AbilityController.Instance.fromNBT(resolved.writeNBT(true));
if (concurrentCopy == null) continue;
ConcurrentSlot slot = new ConcurrentSlot(concurrentCopy);
@@ -1279,6 +1338,7 @@ public abstract class AbstractDataAbilities {
protected void completeChain() {
if (currentChain != null) {
rollChainCooldown(currentChain);
fireChainCompleteEvent(currentChain, chainEntryIndex, getTarget());
}
currentChain = null;
chainEntryIndex = -1;
+8 -8
View File
@@ -29,15 +29,15 @@ import kamkeel.npcs.controllers.TelegraphController;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker;
import kamkeel.npcs.controllers.data.profile.CNPCData;
import kamkeel.npcs.developer.Developer;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityEnergySweeper;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import kamkeel.npcs.entity.EntityEnergySlicer;
import kamkeel.npcs.network.PacketHandler;
@@ -298,10 +298,10 @@ public class CustomNpcs {
registerNewEntity(EntityAbilityDisc.class, "abilitydisc", 64, 1, true);
registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 1, true);
registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 160, 1, true);
registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true);
registerNewEntity(EntityEnergySweeper.class, "abilitysweeper", 64, 3, true);
registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true);
registerNewEntity(EntityAbilityDome.class, "energydome", 64, 3, true);
registerNewEntity(EntityAbilityPanel.class, "energypanel", 64, 3, true);
registerNewEntity(EntityEnergyDome.class, "energydome", 64, 3, true);
registerNewEntity(EntityEnergyPanel.class, "energypanel", 64, 3, true);
registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 1, true);
new RecipeController();
@@ -433,7 +433,7 @@ public class CustomNpcs {
}
EntityEnergyProjectile.clearAllProjectiles();
EntityAbilityBarrier.clearAllBarriers();
EntityEnergyBarrier.clearAllBarriers();
EnergyChargeTracker.Instance.clear();
if (FMLCommonHandler.instance().getSide().isClient())
+6 -93
View File
@@ -7,18 +7,19 @@ import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.ability.type.AbilityDefend;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.DamageSource;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.AbilityEvent;
import noppes.npcs.EventHooks;
import java.util.ArrayList;
import java.util.List;
@@ -124,51 +125,6 @@ public class DataAbilities extends AbstractDataAbilities {
return npc.worldObj.getTotalWorldTime();
}
@Override
protected void fireTickEvent(Ability ability, EntityLivingBase target) {
AbilityEvent.TickEvent event = new AbilityEvent.TickEvent(
npc.wrappedNPC, ability, target,
ability.getPhase().ordinal(), ability.getCurrentTick());
NpcAPI.EVENT_BUS.post(event);
}
@Override
protected boolean fireExecuteEvent(Ability ability, EntityLivingBase target) {
AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent(
npc.wrappedNPC, ability, target);
return NpcAPI.EVENT_BUS.post(executeEvent);
}
@Override
protected void fireCompleteEvent(Ability ability, EntityLivingBase target) {
AbilityEvent.CompleteEvent completeEvent = new AbilityEvent.CompleteEvent(
npc.wrappedNPC, ability, target);
NpcAPI.EVENT_BUS.post(completeEvent);
}
@Override
protected void fireInterruptEvent(Ability ability, EntityLivingBase target,
DamageSource source, float damage) {
AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent(
npc.wrappedNPC, ability, target, source, damage);
NpcAPI.EVENT_BUS.post(interruptEvent);
}
@Override
protected boolean fireToggleEvent(Ability ability, int oldState, int newState) {
AbilityEvent.ToggleEvent event = new AbilityEvent.ToggleEvent(
npc.wrappedNPC, ability, oldState, newState);
return NpcAPI.EVENT_BUS.post(event);
}
@Override
protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) {
AbilityEvent.ToggleUpdateEvent event = new AbilityEvent.ToggleUpdateEvent(
npc.wrappedNPC, ability, tick, state);
NpcAPI.EVENT_BUS.post(event);
return event.isEnabled();
}
@Override
protected void spawnTelegraph(Ability ability, EntityLivingBase target) {
List<TelegraphInstance> telegraphs = ability.createTelegraphs(npc, target);
@@ -502,10 +458,7 @@ public class DataAbilities extends AbstractDataAbilities {
*/
private boolean startAbility(Ability ability, EntityLivingBase target) {
// Fire start event (cancelable)
AbilityEvent.StartEvent startEvent = new AbilityEvent.StartEvent(
npc.wrappedNPC, ability, target);
if (NpcAPI.EVENT_BUS.post(startEvent)) {
// Event was cancelled - don't start the ability
if (EventHooks.onAbilityStart(ability, npc, target)) {
return false;
}
@@ -564,11 +517,6 @@ public class DataAbilities extends AbstractDataAbilities {
// Track hit for hit count condition
recordHit();
net.minecraft.entity.Entity sourceEntity = source.getEntity();
EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null;
currentAbility.onDamageTaken(npc, attacker, source, amount);
if (currentAbility.canInterrupt(source)) {
interruptCurrentAbility(source, amount);
return true;
@@ -577,18 +525,6 @@ public class DataAbilities extends AbstractDataAbilities {
return false;
}
/**
* Get the damage reduction factor if a Guard ability is currently active.
*
* @return The damage reduction factor (0.0 = no reduction, 1.0 = full immunity), or 0 if not guarding
*/
public float getGuardDamageReduction() {
if (currentAbility instanceof AbilityGuard) {
return ((AbilityGuard) currentAbility).getDamageReductionFactor();
}
return 0.0f;
}
/**
* Record a hit for the hit count condition.
* Includes periodic cleanup to prevent memory leak.
@@ -698,29 +634,6 @@ public class DataAbilities extends AbstractDataAbilities {
// SCRIPT EVENTS
// ═══════════════════════════════════════════════════════════════════
/**
* Fire an ability hit event. Called by abilities when they hit an entity.
* Returns null if the event was cancelled, otherwise returns the (possibly modified) event.
*
* @param ability The ability doing the hit
* @param target The original target of the ability
* @param hitEntity The entity being hit
* @param damage The damage amount
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback
* @return The event (with possibly modified values), or null if cancelled
*/
public AbilityEvent.HitEvent fireHitEvent(Ability ability, EntityLivingBase target,
EntityLivingBase hitEntity, float damage,
float knockback, float knockbackUp) {
AbilityEvent.HitEvent event = new AbilityEvent.HitEvent(
npc.wrappedNPC, ability, target, hitEntity, damage, knockback, knockbackUp);
if (NpcAPI.EVENT_BUS.post(event)) {
return null; // Cancelled
}
return event;
}
/**
* Get the NPC this DataAbilities belongs to.
*/
@@ -1091,7 +1004,7 @@ public class DataAbilities extends AbstractDataAbilities {
NBTTagList actionList = new NBTTagList();
for (AbilityAction slot : actionSlots) {
actionList.appendTag(slot.writeNBT());
actionList.appendTag(slot.writeNBT(true));
}
compound.setTag("AbilityActions", actionList);
@@ -1146,7 +1059,7 @@ public class DataAbilities extends AbstractDataAbilities {
}
}
// Active toggles - restore state directly (no onToggleOn callback during load)
// Active toggles - restore state directly (no onToggle callback during load)
activeToggles.clear();
if (compound.hasKey("ActiveToggles")) {
NBTTagList toggleNbt = compound.getTagList("ActiveToggles", 10); // 10 = TAG_COMPOUND
+133 -23
View File
@@ -53,7 +53,16 @@ import noppes.npcs.controllers.data.RecipeScript;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.entity.EntityProjectile;
import noppes.npcs.scripted.NpcAPI;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import noppes.npcs.api.entity.IEntityLivingBase;
import noppes.npcs.api.event.IAbilityEvent;
import noppes.npcs.api.event.IChainEvent;
import noppes.npcs.controllers.data.AbilityScript;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import noppes.npcs.scripted.event.AbilityEvent;
import noppes.npcs.scripted.event.AnimationEvent;
import noppes.npcs.scripted.event.ChainEvent;
import noppes.npcs.scripted.event.BlockEvent;
import noppes.npcs.scripted.event.CustomNPCsEvent;
import noppes.npcs.scripted.event.EnergyProjectileEvent;
@@ -68,7 +77,6 @@ import noppes.npcs.scripted.event.player.AuctionEvent;
import noppes.npcs.scripted.event.player.CustomGuiEvent;
import noppes.npcs.scripted.event.player.DialogEvent;
import noppes.npcs.scripted.event.player.FactionEvent;
import noppes.npcs.scripted.event.player.PlayerAbilityEvent;
import noppes.npcs.scripted.event.player.PlayerEvent;
import noppes.npcs.scripted.event.player.PlayerEvent.ChatEvent;
import noppes.npcs.scripted.event.player.PlayerEvent.ContainerOpen;
@@ -851,44 +859,146 @@ public class EventHooks {
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onPlayerAbilityStart(PlayerDataScript handler, PlayerAbilityEvent.StartEvent event) {
handler.callScript(EnumScriptType.ABILITY_START, event);
// ==================== ABILITY EVENTS (Unified NPC/Player) ====================
private static IScriptHandler getEntityScriptHandler(IEntityLivingBase entity) {
if (entity instanceof ICustomNpc<?>) {
return ((EntityNPCInterface) ((ICustomNpc<?>) entity).getMCEntity()).script;
} else if (entity instanceof IPlayer && ScriptController.Instance != null) {
return ScriptController.Instance.getPlayerScripts(
(EntityPlayer) ((IPlayer) entity).getMCEntity());
}
return null;
}
/**
* Dispatches an ability event through the three-tier routing chain:
* <ol>
* <li><b>AbilityScript</b> — fires for BOTH NPC and Player casters</li>
* <li><b>Entity script handler</b> — routes to the caster's own handler:
* NPC casters fire on the NPC script handler only,
* Player casters fire on the Player script handler only</li>
* <li><b>EVENT_BUS</b> — global event bus, fires last</li>
* </ol>
*
* @return true if the event was cancelled (for @Cancelable events)
*/
private static boolean postAbilityEvent(Ability ability, Event event) {
IAbilityEvent abilityEvent = (IAbilityEvent) event;
// 1. Internal ability script (fires for ALL — both NPC and Player)
AbilityScript abScript = ability.getScriptHandler();
if (abScript != null) {
abScript.callScript(abilityEvent.getHookName(), event);
}
// Short-circuit if cancelled by ability script
if (event.isCancelable() && event.isCanceled()) {
return true;
}
// 2. Entity script handler (NPC → NPC handler, Player → Player handler, never cross-fires)
IScriptHandler handler = getEntityScriptHandler(abilityEvent.getEntity());
if (handler != null && !handler.isClient()) {
handler.callScript(abilityEvent.getHookName(), event);
}
// Short-circuit if cancelled by entity script
if (event.isCancelable() && event.isCanceled()) {
return true;
}
// 3. EVENT_BUS (global — fires last)
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onPlayerAbilityExecute(PlayerDataScript handler, PlayerAbilityEvent.ExecuteEvent event) {
handler.callScript(EnumScriptType.ABILITY_EXECUTE, event);
private static boolean postChainEvent(ChainedAbility chain, Event event) {
IChainEvent chainEvent = (IChainEvent) event;
// 1. Internal chain script (fires first)
ChainedAbilityScript chainScript = chain.getScriptHandler();
if (chainScript != null) {
chainScript.callScript(chainEvent.getHookName(), event);
}
// Short-circuit if cancelled by chain script
if (event.isCancelable() && event.isCanceled()) {
return true;
}
// 2. Entity script handler (NPC or Player)
IScriptHandler handler = getEntityScriptHandler(chainEvent.getEntity());
if (handler != null && !handler.isClient()) {
handler.callScript(chainEvent.getHookName(), event);
}
// Short-circuit if cancelled by entity script
if (event.isCancelable() && event.isCanceled()) {
return true;
}
// 3. EVENT_BUS (global — fires last)
return NpcAPI.EVENT_BUS.post(event);
}
public static void onPlayerAbilityTick(PlayerDataScript handler, PlayerAbilityEvent.TickEvent event) {
handler.callScript(EnumScriptType.ABILITY_TICK, event);
NpcAPI.EVENT_BUS.post(event);
public static boolean onAbilityStart(Ability ability, EntityLivingBase entity, EntityLivingBase target) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.StartEvent(entity, ability, target));
}
public static void onPlayerAbilityInterrupt(PlayerDataScript handler, PlayerAbilityEvent.InterruptEvent event) {
handler.callScript(EnumScriptType.ABILITY_INTERRUPT, event);
NpcAPI.EVENT_BUS.post(event);
public static boolean onAbilityExecute(Ability ability, EntityLivingBase entity, EntityLivingBase target) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.ExecuteEvent(entity, ability, target));
}
public static void onPlayerAbilityComplete(PlayerDataScript handler, PlayerAbilityEvent.CompleteEvent event) {
handler.callScript(EnumScriptType.ABILITY_COMPLETE, event);
NpcAPI.EVENT_BUS.post(event);
public static boolean onAbilityTick(Ability ability, EntityLivingBase entity, EntityLivingBase target, int phase, int tick) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.TickEvent(entity, ability, target, phase, tick));
}
public static boolean onPlayerAbilityHit(PlayerDataScript handler, PlayerAbilityEvent.HitEvent event) {
handler.callScript(EnumScriptType.ABILITY_HIT, event);
return NpcAPI.EVENT_BUS.post(event);
public static boolean onAbilityComplete(Ability ability, EntityLivingBase entity, EntityLivingBase target) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.CompleteEvent(entity, ability, target));
}
public static boolean onPlayerAbilityToggle(PlayerDataScript handler, PlayerAbilityEvent.ToggleEvent event) {
handler.callScript(EnumScriptType.ABILITY_TOGGLE, event);
return NpcAPI.EVENT_BUS.post(event);
public static boolean onAbilityInterrupt(Ability ability, EntityLivingBase entity, EntityLivingBase target,
DamageSource source, float damage) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.InterruptEvent(entity, ability, target, source, damage));
}
public static void onPlayerAbilityToggleUpdate(PlayerDataScript handler, PlayerAbilityEvent.ToggleUpdateEvent event) {
handler.callScript(EnumScriptType.ABILITY_TOGGLE_UPDATE, event);
NpcAPI.EVENT_BUS.post(event);
public static boolean onAbilityHit(Ability ability, AbilityEvent.HitEvent event) {
if (ability == null || event == null) return false;
return postAbilityEvent(ability, event);
}
public static boolean onAbilityToggle(Ability ability, EntityLivingBase entity, int oldState, int newState) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.ToggleEvent(entity, ability, oldState, newState));
}
public static boolean onAbilityToggleUpdate(Ability ability, AbilityEvent.ToggleUpdateEvent event) {
if (ability == null || event == null) return false;
return postAbilityEvent(ability, event);
}
// Chain events
public static void onChainStart(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) {
postChainEvent(chain, new ChainEvent.StartEvent(entity, chain, entryIndex, target));
}
public static void onChainNext(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) {
postChainEvent(chain, new ChainEvent.NextEvent(entity, chain, entryIndex, target));
}
public static void onChainComplete(ChainedAbility chain, EntityLivingBase entity, int entryIndex, EntityLivingBase target) {
postChainEvent(chain, new ChainEvent.CompleteEvent(entity, chain, entryIndex, target));
}
public static void onChainInterrupt(ChainedAbility chain, EntityLivingBase entity, int entryIndex,
EntityLivingBase target, DamageSource source, float damage) {
postChainEvent(chain, new ChainEvent.InterruptEvent(entity, chain, entryIndex, target, source, damage));
}
public static void onPlayerChangeDim(PlayerDataScript handler, IPlayer player, int fromDim, int toDim) {
@@ -10,10 +10,15 @@ import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCounter;
import kamkeel.npcs.controllers.data.ability.type.AbilityDefend;
import kamkeel.npcs.controllers.data.ability.type.AbilityDodge;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.util.AttributeAttackUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.ContainerPlayer;
@@ -596,6 +601,7 @@ public class ScriptPlayerEventHandler {
if (event.entityLiving.worldObj instanceof WorldServer) {
boolean cancel = event.isCanceled();
Entity source = NoppesUtilServer.GetDamageSource(event.source);
if (event.entityLiving instanceof EntityPlayerMP) {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving);
noppes.npcs.scripted.event.player.PlayerEvent.AttackedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.AttackedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source);
@@ -623,6 +629,22 @@ public class ScriptPlayerEventHandler {
noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent pevent1 = new noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.source.getEntity()), event.entityLiving, attackAmount, event.source);
cancel = cancel || EventHooks.onPlayerAttack(handler, pevent1);
}
// Dodge & Counter: cancel attack entirely
if (!cancel && event.entityLiving instanceof EntityPlayerMP) {
PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving);
if (pData != null && pData.abilityData != null) {
AbilityDefend defend = pData.abilityData.getActiveDefend();
if (defend instanceof AbilityDodge || defend instanceof AbilityCounter) {
EntityLivingBase attacker = source instanceof EntityLivingBase ? (EntityLivingBase) source : null;
float result = defend.onDefend(attacker, event.source, event.ammount);
if (result != event.ammount) {
cancel = true;
}
}
}
}
event.setCanceled(cancel);
}
}
@@ -645,20 +667,28 @@ public class ScriptPlayerEventHandler {
}
if (event.entityLiving instanceof EntityPlayerMP) {
// Handle ability damage interactions (Guard counter, damage reduction)
// Handle ability damage interactions
PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving);
if (pData != null && pData.abilityData != null && pData.abilityData.isExecutingAbility()) {
if (pData.abilityData.isCurrentAbilityInvulnerable()) {
event.ammount = 0;
cancel = true;
} else {
event.ammount = pData.abilityData.onDamage(event.source, event.ammount);
// Guard: reduce damage
AbilityDefend defend = pData.abilityData.getActiveDefend();
if (defend instanceof AbilityGuard) {
EntityLivingBase attacker = source instanceof EntityLivingBase ? (EntityLivingBase) source : null;
event.ammount = defend.onDefend(attacker, event.source, event.ammount);
}
float modified = pData.abilityData.onDamage(event.source, event.ammount);
event.ammount = modified;
}
}
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving);
noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source);
cancel = EventHooks.onPlayerDamaged(handler, pevent);
cancel = cancel || EventHooks.onPlayerDamaged(handler, pevent);
event.ammount = pevent.damage;
}
@@ -5,8 +5,8 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSoundOperation;
import kamkeel.npcs.network.enums.EnumSyncAction;
@@ -159,7 +159,7 @@ public class ServerEventsHandler {
if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote)
return;
EntityAbilityBarrier barrier = EntityAbilityBarrier.getAbsorbingBarrier(event.entityLiving);
EntityEnergyBarrier barrier = EntityEnergyBarrier.getAbsorbingBarrier(event.entityLiving);
if (barrier != null) {
// Redirect the caster's damage to their barrier
barrier.absorbDamage(event.ammount);
@@ -191,9 +191,9 @@ public class ServerEventsHandler {
}
if (!blacklisted) return;
List<EntityAbilityBarrier> barriers = EntityAbilityBarrier.getActiveBarriers(player.worldObj);
for (EntityAbilityBarrier barrier : barriers) {
if (barrier instanceof EntityAbilityDome && barrier.isEntityInside(player)) {
List<EntityEnergyBarrier> barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj);
for (EntityEnergyBarrier barrier : barriers) {
if (barrier instanceof EntityEnergyDome && barrier.isEntityInside(player)) {
event.setCanceled(true);
return;
}
@@ -79,16 +79,6 @@ public class CombatHandler {
aggressors.put(el, f + damageAmount);
}
// Handle guard counter before interruption
// if (npc.abilities.getCurrentAbility() instanceof AbilityGuard) {
// AbilityGuard guard =
// (AbilityGuard) npc.abilities.getCurrentAbility();
// if (guard.isGuarding() && e instanceof EntityLivingBase) {
// guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount);
// }
// }
// Check for ability interruption
npc.abilities.onDamage(source, damageAmount);
}
@@ -7,14 +7,14 @@ import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import kamkeel.npcs.addon.client.DBCClient;
import kamkeel.npcs.client.command.CommandCNPCDebugger;
import kamkeel.npcs.client.renderer.RenderAbilityBeam;
import kamkeel.npcs.client.renderer.RenderAbilityDisc;
import kamkeel.npcs.client.renderer.RenderAbilityLaser;
import kamkeel.npcs.client.renderer.RenderAbilityOrb;
import kamkeel.npcs.client.renderer.RenderAbilitySweeper;
import kamkeel.npcs.client.renderer.RenderAbilityZone;
import kamkeel.npcs.client.renderer.RenderAbilityDome;
import kamkeel.npcs.client.renderer.RenderAbilityPanel;
import kamkeel.npcs.client.renderer.RenderEnergyBeam;
import kamkeel.npcs.client.renderer.RenderEnergyDisc;
import kamkeel.npcs.client.renderer.RenderEnergyLaser;
import kamkeel.npcs.client.renderer.RenderEnergyOrb;
import kamkeel.npcs.client.renderer.RenderSweeper;
import kamkeel.npcs.client.renderer.RenderZone;
import kamkeel.npcs.client.renderer.RenderEnergyDome;
import kamkeel.npcs.client.renderer.RenderEnergyPanel;
import kamkeel.npcs.client.renderer.EnergyChargePreviewRenderer;
import kamkeel.npcs.client.renderer.RenderEnergyExplosion;
import kamkeel.npcs.client.renderer.RenderEnergySlicer;
@@ -26,10 +26,10 @@ import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergySweeper;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.client.Minecraft;
@@ -282,14 +282,14 @@ public class ClientProxy extends CommonProxy {
RenderingRegistry.registerEntityRenderingHandler(EntityNpcDragon.class, new RenderNpcDragon(new ModelNpcDragon(0.0F), 0.5F));
RenderingRegistry.registerEntityRenderingHandler(EntityNpcSlime.class, new RenderNpcSlime(new ModelNpcSlime(16), new ModelNpcSlime(0), 0.25F));
RenderingRegistry.registerEntityRenderingHandler(EntityProjectile.class, new RenderProjectile());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderAbilityOrb());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderAbilityDisc());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDome.class, new RenderAbilityDome());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityPanel.class, new RenderAbilityPanel());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderEnergyOrb());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderEnergyDisc());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderEnergyLaser());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderEnergyBeam());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergySweeper.class, new RenderSweeper());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderZone());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyExplosion.class, new RenderEnergyExplosion());
@@ -8,6 +8,7 @@ import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.config.ConfigClient;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -101,18 +102,10 @@ public class ImageDownloadAlt extends SimpleTexture {
HttpURLConnection connection = null;
try {
URL url = new URL(ImageDownloadAlt.this.imageUrl);
connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy());
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestProperty("Content-Type", "image/png");
connection.setRequestProperty("Expect", "100-continue");
//connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// Modify Accept Redirect
if (isImgurLink(url)) {
connection.setRequestProperty("Accept", "*/*");
}
// Adding a config so people can switch back if needed.
// TODO: Remove config option if improved works better
connection = ConfigClient.ImprovedImageDownloadConnection ? setupConnectionImproved(url) : setupConnectionOld(url);
connection.connect();
@@ -152,6 +145,44 @@ public class ImageDownloadAlt extends SimpleTexture {
this.imageThread.start();
}
private HttpURLConnection setupConnectionOld(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy());
// setups stuff which basically tells the browser if this a get or post request
connection.setDoInput(true);
connection.setDoOutput(false);
// ??? I believe these are used to tell the receiver what you are sending to them
// Not what you expect to receive from them.
connection.setRequestProperty("Content-Type", "image/png");
connection.setRequestProperty("Expect", "100-continue");
//connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// Modify Accept Redirect
if (isImgurLink(url)) {
connection.setRequestProperty("Accept", "*/*");
}
return connection;
}
private HttpURLConnection setupConnectionImproved(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) (url).openConnection(Minecraft.getMinecraft().getProxy());
connection.setRequestMethod("GET");
// Basically redundant because I set it as a GET request?
// Better safe than sorry ig.
connection.setDoInput(true);
connection.setDoOutput(false);
// Random ass user agent I grabbed from my snooping on imgur
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0");
// I tell the server what I want to receive.
// TODO: Should this just accept PNGs?
connection.setRequestProperty("Accept", "image/png,image/*");
return connection;
}
// Check if the URL is an Imgur link
private static boolean isImgurLink(URL url) {
@@ -8,6 +8,7 @@ import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -129,6 +130,12 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
int width = data.getTotalWidth();
int height = data.getTotalHeight();
// Animation V offset for preview
if (data.isAnimated()) {
iconY += (int) (data.getCurrentFrameVOffset() * height);
} else if (effect.animated && effect.frameCount > 1) {
iconY += (int) (AnimationHelper.getFrameVOffset(height, effect.frameCount, effect.frametime) * height);
}
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
@@ -183,6 +190,33 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
effect.height
));
scrollWindow.addLabel(new GuiNpcLabel(9, "effect.editor.height", scrollWindow.getTextField(9).xPosition - 43, y + 6, 0xFFFFFF));
y += 25;
// Animation controls
scrollWindow.addLabel(new GuiNpcLabel(11, "gui.animated", x, y + 5, 0xFFFFFF));
GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(11, x + 70, y, 50, 20, effect.animated);
animBtn.setHoverText("gui.animated.hover");
scrollWindow.addButton(animBtn);
if (effect.animated) {
y += 23;
scrollWindow.addLabel(new GuiNpcLabel(12, "gui.frameCount", x, y + 6, 0xFFFFFF));
scrollWindow.addTextField(setIntegerOnly(
new GuiNpcTextField(12, this, x + 80, y, 60, 20, "" + effect.frameCount),
1,
256,
effect.frameCount
));
y += 23;
scrollWindow.addLabel(new GuiNpcLabel(13, "gui.frameTime", x, y + 6, 0xFFFFFF));
scrollWindow.addTextField(setIntegerOnly(
new GuiNpcTextField(13, this, x + 80, y, 60, 20, "" + effect.frametime),
1,
100,
effect.frametime
));
}
}
@@ -209,6 +243,11 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton;
effect.lossOnDeath = button.getBoolean();
}
if (id == 11) {
GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton;
effect.animated = button.getBoolean();
initGui();
}
}
@Override
@@ -248,6 +287,12 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
case 9:
effect.height = guiNpcTextField.getInteger();
break;
case 12:
effect.frameCount = Math.max(1, guiNpcTextField.getInteger());
break;
case 13:
effect.frametime = Math.max(1, guiNpcTextField.getInteger());
break;
}
}
@@ -649,9 +649,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Search matches either the display name or the typeId (strip color codes for matching)
String stripped = displayName.replaceAll("\u00A7.", "");
if (search.isEmpty() || stripped.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) {
// Yellow for concurrent-capable types, gray for other built-in types
// Lime green for concurrent-capable types, gray for other built-in types
if (AbilityController.Instance.isConcurrentCapableType(typeId)) {
displayName = "\u00A7e" + displayName;
displayName = "\u00A7a" + displayName;
} else if (AbilityController.Instance.isBuiltInType(typeId)) {
displayName = "\u00A77" + displayName;
}
@@ -787,7 +787,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
NBTTagList actionList = new NBTTagList();
for (AbilityAction slot : npcSlots) {
actionList.appendTag(slot.writeNBT());
actionList.appendTag(slot.writeNBT(false));
}
compound.setTag("AbilityActions", actionList);
@@ -1105,7 +1105,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
public void onAbilitySaved(Ability ability) {
// Editing a global parent ability via "Modify Parent" on a chain entry
if (editingChainEntryParent) {
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false)));
return;
}
@@ -1119,7 +1119,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
AbilityAction slot = npcSlots.get(selectedAbilityIndex);
if (slot.isReference()) {
// Modify Parent on standalone reference — save to global preset
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false)));
} else {
// Inline ability — update slot data
npcSlots.set(selectedAbilityIndex, AbilityAction.inline(ability));
@@ -3,6 +3,8 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.AbilityScript;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
@@ -143,6 +145,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
GuiMenuTopButton closeBtn = new GuiMenuTopButton(-1000, guiLeft + xSize - 22, guiTop - 17, "X");
addTopButton(closeBtn);
GuiMenuTopButton scriptBtn = new GuiMenuTopButton(-999, "script.scripts", closeBtn);
addTopButton(scriptBtn);
// Build scroll window dimensions
int swX = guiLeft + 4;
int swY = guiTop + 5;
@@ -152,9 +157,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
int y = 5;
int labelCounter = LABEL_ID_START;
// General tab: type label + optional concurrent label at top — reserve space
// General tab: type label + optional info labels at top — reserve space
if (activeTab == TAB_GENERAL) {
y += ROW_H;
if ("ability.cnpc.custom".equals(ability.getTypeId())) {
y += 15;
}
if (ability.isConcurrentCapable()) {
y += 15;
}
@@ -168,14 +176,20 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH);
// General tab: add type label + optional concurrent label at top of scroll window
// General tab: add type label + optional info labels at top of scroll window
if (activeTab == TAB_GENERAL) {
int baseId = builder.getNextLabelId();
int infoY = 25;
sw.addLabel(new GuiNpcLabel(baseId, "gui.type", 5, 10, 0xFFFFFF));
sw.addLabel(new GuiNpcLabel(baseId + 1, ability.getTypeId(), 55, 10, 0xFFFFFF));
if (ability.isConcurrentCapable()) {
if ("ability.cnpc.custom".equals(ability.getTypeId())) {
sw.addLabel(new GuiNpcLabel(baseId + 2,
StatCollector.translateToLocal("ability.concurrentInfo"), 5, 25, 0x55FF55));
StatCollector.translateToLocal("ability.customScriptInfo"), 5, infoY, 0xFF55FF));
infoY += 15;
}
if (ability.isConcurrentCapable()) {
sw.addLabel(new GuiNpcLabel(baseId + 3,
StatCollector.translateToLocal("ability.concurrentInfo"), 5, infoY, 0x55FF55));
}
}
@@ -302,6 +316,13 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
initGui();
return;
}
if (id == -999) {
GuiNpcTextField.unfocus();
applyToAbility();
callback.onAbilitySaved(ability);
GuiScriptInterface.open(parent, new AbilityScript(ability.getId()));
return;
}
if (id == -1000) {
close();
return;
@@ -405,7 +426,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
public void loadAbility(Ability loadedAbility) {
if (loadedAbility == null) return;
NBTTagCompound nbt = loadedAbility.writeNBT();
NBTTagCompound nbt = loadedAbility.writeNBT(false);
nbt.setString("typeId", ability.getTypeId());
ability.readNBT(nbt);
@@ -70,7 +70,7 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui
private void doSave() {
saved = true;
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false)));
if (callback != null) {
callback.onAbilitySaved(ability);
}
@@ -83,8 +83,10 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS
continue;
String displayName = I18n.format(typeId);
if (AbilityController.Instance.isConcurrentCapableType(typeId)) {
displayName = "\u00A7e" + displayName;
if (typeId.equals("ability.cnpc.custom")) {
displayName = "\u00A7d" + displayName;
} else if (AbilityController.Instance.isConcurrentCapableType(typeId)) {
displayName = "\u00A7a" + displayName;
}
allDisplayNameToTypeId.put(displayName, typeId);
}
@@ -122,6 +124,21 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS
}
Collections.sort(list, (a, b) -> String.CASE_INSENSITIVE_ORDER.compare(
a.replaceAll("\u00A7.", ""), b.replaceAll("\u00A7.", "")));
// Pin Custom Ability to top of list
String customEntry = null;
for (String name : list) {
String tid = displayNameToTypeId.get(name);
if (tid != null && tid.equals("ability.cnpc.custom")) {
customEntry = name;
break;
}
}
if (customEntry != null) {
list.remove(customEntry);
list.add(0, customEntry);
}
return list;
}
@@ -5,6 +5,8 @@ import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityAction;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.data.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider;
@@ -57,6 +59,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
private static final int BTN_TAB_ENTRIES = 91;
private static final int BTN_TAB_TARGET = 92;
private static final int BTN_TAB_EXTRA_BASE = 93;
private static final int BTN_SCRIPT = -999;
private static final int BTN_CLOSE = -1000;
// ── Entries tab: per-entry ID encoding ─────────────────────────────────────
@@ -160,14 +163,43 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
// ── Icon tab ──────────────────────────────────────────────
AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain);
fieldDefs.add(FieldDef.stringField("gui.texture", chainIcon::getTexture, chainIcon::setTexture).tab("Icon"));
fieldDefs.add(FieldDef.section("ability.icon.section.uv").tab("Icon"));
fieldDefs.add(FieldDef.intField("ability.icon.x", chainIcon::getIconX, chainIcon::setIconX).tab("Icon").range(0, 4096));
fieldDefs.add(FieldDef.intField("ability.icon.y", chainIcon::getIconY, chainIcon::setIconY).tab("Icon").range(0, 4096));
fieldDefs.add(FieldDef.section("gui.size").tab("Icon"));
fieldDefs.add(FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).tab("Icon").range(1, 256));
fieldDefs.add(FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).tab("Icon").range(1, 256));
fieldDefs.add(FieldDef.row(
FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).range(1, 256),
FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).range(1, 256)
).tab("Icon"));
fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f));
fieldDefs.add(FieldDef.intField("ability.icon.layers", chainIcon::getLayerCount, chainIcon::setLayerCount)
.tab("Icon").range(1, AbilityIconData.MAX_LAYERS));
for (int i = 0; i < AbilityIconData.MAX_LAYERS; i++) {
final int idx = i;
java.util.function.BooleanSupplier layerVisible = () -> chainIcon.getLayerCount() > idx;
String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1);
fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.stringField("gui.texture",
() -> chainIcon.getLayer(idx).texture,
t -> chainIcon.setLayerTexture(idx, t))
.tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.row(
FieldDef.intField("ability.icon.x",
() -> chainIcon.getLayer(idx).iconX,
x -> chainIcon.setLayerIconX(idx, x)).range(0, 4096),
FieldDef.intField("ability.icon.y",
() -> chainIcon.getLayer(idx).iconY,
y -> chainIcon.setLayerIconY(idx, y)).range(0, 4096)
).tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.colorSubGui("ability.icon.tint",
() -> chainIcon.getLayer(idx).tintColor,
c -> chainIcon.setLayerTintColor(idx, c))
.tab("Icon").visibleWhen(layerVisible));
}
// Animation
fieldDefs.add(FieldDef.section("Animation").tab("Icon"));
fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover"));
fieldDefs.add(FieldDef.intField("gui.frameCount", chainIcon::getFrameCount, chainIcon::setFrameCount)
.tab("Icon").range(1, 256).visibleWhen(chainIcon::isAnimated));
fieldDefs.add(FieldDef.intField("gui.frameTime", chainIcon::getFrameTime, chainIcon::setFrameTime)
.tab("Icon").range(1, 100).visibleWhen(chainIcon::isAnimated));
// External field providers (e.g., DBC Addon injecting a "DBC" tab)
if (AbilityController.Instance != null) {
@@ -258,6 +290,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
GuiMenuTopButton closeBtn = new GuiMenuTopButton(BTN_CLOSE, guiLeft + xSize - 22, guiTop - 17, "X");
addTopButton(closeBtn);
GuiMenuTopButton scriptBtn = new GuiMenuTopButton(BTN_SCRIPT, "script.scripts", closeBtn);
addTopButton(scriptBtn);
// Scroll window dimensions
int swX = guiLeft + 4;
int swY = guiTop + 5;
@@ -487,6 +522,10 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
initGui();
return;
}
if (id == BTN_SCRIPT) {
GuiScriptInterface.open(parent, new ChainedAbilityScript(chain.getId()));
return;
}
if (id == BTN_CLOSE) {
saveOnClose = true;
close();
@@ -853,7 +892,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
public void onAbilitySaved(Ability ability) {
if (editingParentAbility) {
// Persist the global parent ability to the server
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT(false)));
editingParentAbility = false;
return;
}
@@ -187,19 +187,27 @@ public class FieldDef {
idSetter.accept(-1);
} else {
idSetter.accept(sel.selectedAnimationId);
nameSetter.accept("");
String customName = sel.getSelectedName();
nameSetter.accept(customName != null ? customName : "");
}
})
.buttonLabel(() -> {
String name = nameGetter.get();
if (name != null && !name.isEmpty()) return name;
int id = idGetter.get();
if (id < 0 && name != null && !name.isEmpty()) {
// Built-in animation: show just the name
return name;
}
if (id >= 0) {
// Custom animation: show (X) Name
if (name != null && !name.isEmpty()) {
return "(" + id + ") " + name;
}
Animation anim = AnimationController.Instance != null
? (Animation) AnimationController.Instance.get(id) : null;
String animName = anim != null ? anim.getName() : "";
return animName != null && !animName.isEmpty()
? "(ID: " + id + ") " + animName : "ID: " + id;
? "(" + id + ") " + animName : String.valueOf(id);
}
return "gui.none";
})
@@ -347,9 +347,14 @@ public class GuiFieldBuilder {
String translated = StatCollector.translateToLocal(def.getLabel());
int labelW = fontRenderer.getStringWidth(translated);
int fieldX = colLLabel + labelW + labelPadding;
// Clamp field width so it doesn't extend under the scrollbar
// Available width before the scrollbar
int maxW = contentRight - fieldX - 15;
if (maxW > 0 && fieldW > maxW) fieldW = maxW;
if (def.getType() == FieldType.SUB_GUI && maxW > 0) {
// SUB_GUI fields fill all available width up to the scrollbar
fieldW = maxW;
} else if (maxW > 0 && fieldW > maxW) {
fieldW = maxW;
}
renderFieldAt(def, colLLabel, fieldX, fieldW, y);
}
@@ -7,6 +7,7 @@ import noppes.npcs.api.gui.ICustomGuiComponent;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.custom.GuiCustom;
import noppes.npcs.client.gui.custom.interfaces.IGuiComponent;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.scripted.gui.ScriptGuiTexturedRect;
import org.lwjgl.opengl.GL11;
@@ -30,6 +31,11 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
float alpha;
float rotation;
// Animation
boolean animated;
int frameCount = 1;
int frametime = 2;
public CustomGuiTexturedRect(int id, String texture, int x, int y, int width, int height) {
this(id, texture, x, y, width, height, 0, 0);
}
@@ -64,10 +70,18 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
int totalWidth = this.imageData.getTotalWidth();
int totalHeight = this.imageData.getTotalHeight();
// Animation V offset
float vOff = 0f;
if (this.imageData.isAnimated()) {
vOff = this.imageData.getCurrentFrameVOffset();
} else if (this.animated && this.frameCount > 1) {
vOff = AnimationHelper.getFrameVOffset(totalHeight, this.frameCount, this.frametime);
}
float u1 = (float) textureX / (float) totalWidth;
float u2 = u1 + (float) width / (float) totalWidth;
float v1 = (float) textureY / (float) totalHeight;
float v2 = v1 + (float) height / (float) totalHeight;
float v1 = vOff + (float) textureY / (float) totalHeight;
float v2 = vOff + ((float) textureY + (float) height) / (float) totalHeight;
GL11.glPushMatrix();
float red = (color >> 16 & 255) / 255f;
@@ -104,6 +118,9 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
component.setColor(color);
component.setAlpha(alpha);
component.setRotation(rotation);
if (this.animated && this.frameCount > 1) {
component.setAnimation(this.frameCount, this.frametime);
}
return component;
}
@@ -124,6 +141,12 @@ public class CustomGuiTexturedRect extends Gui implements IGuiComponent {
rect.alpha = component.getAlpha();
rect.rotation = component.getRotation();
if (component.isAnimated()) {
rect.animated = true;
rect.frameCount = component.getFrameCount();
rect.frametime = component.getFrameTime();
}
return rect;
}
}
@@ -5,6 +5,8 @@ import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.network.PacketClient;
import java.util.UUID;
import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilityGetPacket;
@@ -495,7 +497,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
private void handleChainConfigClosed() {
if (pendingSaveChain != null) {
PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT()));
PacketClient.sendClient(new ChainedAbilitySavePacket(pendingSaveChain.writeNBT(false)));
selected = pendingSaveChain.getName();
pendingSaveChain = null;
}
@@ -510,6 +512,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
Ability newAbility = AbilityController.Instance.create(pendingTypeId);
if (newAbility != null) {
gui.getVariants().get(idx).apply(newAbility);
newAbility.setId(UUID.randomUUID().toString());
pendingTypeId = null;
openConfig(newAbility);
return true;
@@ -536,6 +539,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
if (variants.size() == 1) {
variants.get(0).apply(newAbility);
}
newAbility.setId(UUID.randomUUID().toString());
openConfig(newAbility);
return true;
}
@@ -550,7 +554,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
if (pendingSaveAbility == null) return false;
if (gui.isConfirmed()) {
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT()));
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false)));
pendingSaveAbility = null;
return false;
}
@@ -574,7 +578,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
setSubGui(new SubGuiDuplicateNameConfirm());
return true;
}
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT()));
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT(false)));
pendingSaveAbility = null;
return false;
}
@@ -13,6 +13,7 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.renderer.ImageData;
import org.lwjgl.opengl.GL11;
@@ -25,6 +26,11 @@ public class AbilityIcon extends Gui {
public int width;
public int height;
// Default icon layers (extracted from ability)
private Ability.DefaultIconLayer[] defaultLayers = null;
private int defaultIconWidth = 48;
private int defaultIconHeight = 48;
private AbilityIcon(AbilityIconData data) {
this.data = data;
this.width = data.width;
@@ -33,7 +39,11 @@ public class AbilityIcon extends Gui {
public static AbilityIcon fromAbility(Ability ability) {
if (ability != null) {
return new AbilityIcon(AbilityIconData.fromAbility(ability));
AbilityIcon icon = new AbilityIcon(AbilityIconData.fromAbility(ability));
icon.defaultLayers = ability.getDefaultIconLayers();
icon.defaultIconWidth = ability.getDefaultIconWidth();
icon.defaultIconHeight = ability.getDefaultIconHeight();
return icon;
}
return fromDefaults();
}
@@ -66,44 +76,88 @@ public class AbilityIcon extends Gui {
public void draw(int state, float alpha) {
TextureManager renderEngine = Minecraft.getMinecraft().renderEngine;
ImageData imageData = null;
if (data.hasTexture()) {
imageData = ClientCacheHandler.getImageData(data.texture);
}
GL11.glPushMatrix();
GL11.glColor4f(1, 1, 1, alpha);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
Tessellator t;
if (imageData == null || !imageData.imageLoaded()) {
GL11.glScalef(1.0f, 1.0f, 1);
renderEngine.bindTexture(FALLBACK_TEXTURE);
t = getFallbackTessellator();
} else {
if (data.isEnabled()) {
// Path 1: Custom icon — draw each active layer bottom-to-top
GL11.glScalef(data.scale, data.scale, 1);
renderEngine.bindTexture(imageData.getLocation());
t = getTessellator(imageData, state);
boolean drewAny = false;
for (int i = 0; i < data.getLayerCount(); i++) {
AbilityIconData.Layer layer = data.getLayer(i);
if (!layer.hasTexture()) continue;
ImageData imageData = ClientCacheHandler.getImageData(layer.texture);
if (imageData != null && imageData.imageLoaded()) {
int tint = layer.tintColor;
float r = ((tint >> 16) & 0xFF) / 255f;
float g = ((tint >> 8) & 0xFF) / 255f;
float b = (tint & 0xFF) / 255f;
GL11.glColor4f(r, g, b, alpha);
renderEngine.bindTexture(imageData.getLocation());
Tessellator t = getLayerTessellator(imageData, layer, i == 0 ? state : 0);
t.draw();
drewAny = true;
}
}
if (!drewAny) {
GL11.glColor4f(1, 1, 1, alpha);
renderEngine.bindTexture(FALLBACK_TEXTURE);
getFallbackTessellator().draw();
}
} else if (hasDefaultLayers()) {
// Path 2: Default layers — draw each layer with its dynamic color
for (Ability.DefaultIconLayer defLayer : defaultLayers) {
String texPath = defLayer.getTextureForState(state);
if (texPath == null || texPath.isEmpty()) continue;
ImageData imageData = ClientCacheHandler.getImageData(texPath);
if (imageData != null && imageData.imageLoaded()) {
int color = defLayer.getColor();
float r = ((color >> 16) & 0xFF) / 255f;
float g = ((color >> 8) & 0xFF) / 255f;
float b = (color & 0xFF) / 255f;
GL11.glColor4f(r, g, b, alpha);
renderEngine.bindTexture(imageData.getLocation());
getDefaultIconTessellator().draw();
}
}
} else {
// Path 3: No custom icon, no default layers — generic fallback
GL11.glColor4f(1, 1, 1, alpha);
renderEngine.bindTexture(FALLBACK_TEXTURE);
getFallbackTessellator().draw();
}
t.draw();
GL11.glPopMatrix();
}
private Tessellator getTessellator(ImageData imageData, int state) {
private boolean hasDefaultLayers() {
return defaultLayers != null && defaultLayers.length > 0;
}
private Tessellator getLayerTessellator(ImageData imageData, AbilityIconData.Layer layer, int state) {
float hw = data.width / 2f;
float hh = data.height / 2f;
float texW = imageData.getTotalWidth();
float texH = imageData.getTotalHeight();
int ix = data.getIconXForState(state);
int iy = data.getIconYForState(state);
// State UV overrides only apply to layer 0
int ix = (state > 0) ? data.getIconXForState(state) : layer.iconX;
int iy = (state > 0) ? data.getIconYForState(state) : layer.iconY;
// Animation V offset
float vOff = 0f;
if (imageData.isAnimated()) {
vOff = imageData.getCurrentFrameVOffset();
} else if (data.isAnimated()) {
vOff = AnimationHelper.getFrameVOffset((int) texH, data.getFrameCount(), data.getFrameTime());
}
float u1 = ix / texW;
float v1 = iy / texH;
float v1 = vOff + iy / texH;
float u2 = (ix + data.width) / texW;
float v2 = (iy + data.height) / texH;
float v2 = vOff + (iy + data.height) / texH;
Tessellator t = Tessellator.instance;
t.startDrawingQuads();
@@ -114,6 +168,19 @@ public class AbilityIcon extends Gui {
return t;
}
private Tessellator getDefaultIconTessellator() {
float hw = defaultIconWidth / 2f;
float hh = defaultIconHeight / 2f;
Tessellator t = Tessellator.instance;
t.startDrawingQuads();
t.addVertexWithUV(-hw, hh, zLevel, 0, 1);
t.addVertexWithUV(hw, hh, zLevel, 1, 1);
t.addVertexWithUV(hw, -hh, zLevel, 1, 0);
t.addVertexWithUV(-hw, -hh, zLevel, 0, 0);
return t;
}
private Tessellator getFallbackTessellator() {
float hw = 16f;
float hh = 16f;
@@ -128,17 +195,20 @@ public class AbilityIcon extends Gui {
}
public boolean hasTexture() {
return data.hasTexture();
return data.isEnabled() || hasDefaultLayers();
}
/**
* Returns the approximate visual size (max dimension) that draw() produces.
* Textured: max(width,height) * scale. Fallback: 32.
* Custom icon: max(width,height) * scale. Default icon: max(defaultW,defaultH). Fallback: 32.
*/
public float getDrawSize() {
if (data.hasTexture()) {
if (data.isEnabled()) {
return Math.max(width, height) * data.scale;
}
if (hasDefaultLayers()) {
return Math.max(defaultIconWidth, defaultIconHeight);
}
return 32f;
}
}
@@ -10,6 +10,7 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.CustomNpcResourceListener;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.script.GuiScriptInterface;
@@ -286,6 +287,31 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
scrollWindow.addLabel(new GuiNpcLabel(70, "display.durabilityShow", x, localY + 5, 0xFFFFFF));
GuiNpcButtonYesNo durabilityButton = new GuiNpcButtonYesNo(26, x + 120, localY, linkedItem.display.durabilityShow);
scrollWindow.addButton(durabilityButton);
localY += 30;
// Animation controls
scrollWindow.addLabel(new GuiNpcLabel(80, "gui.animated", x, localY + 5, 0xFFFFFF));
boolean isAnim = linkedItem.display.animated != null && linkedItem.display.animated;
GuiNpcButtonYesNo animBtn = new GuiNpcButtonYesNo(29, x + 120, localY, isAnim);
animBtn.setHoverText("gui.animated.hover");
scrollWindow.addButton(animBtn);
localY += 25;
if (isAnim) {
scrollWindow.addLabel(new GuiNpcLabel(81, "gui.frameCount", x, localY + 5, 0xFFFFFF));
GuiNpcTextField fcField = new GuiNpcTextField(71, this, x + 120, localY, 60, 20,
"" + (linkedItem.display.frameCount != null ? linkedItem.display.frameCount : 1));
fcField.setIntegersOnly().setMinMaxDefault(1, 256, 1);
scrollWindow.addTextField(fcField);
localY += 25;
scrollWindow.addLabel(new GuiNpcLabel(82, "gui.frameTime", x, localY + 5, 0xFFFFFF));
GuiNpcTextField ftField = new GuiNpcTextField(72, this, x + 120, localY, 60, 20,
"" + (linkedItem.display.frametime != null ? linkedItem.display.frametime : 2));
ftField.setIntegersOnly().setMinMaxDefault(1, 100, 2);
scrollWindow.addTextField(ftField);
localY += 25;
}
scrollWindow.scrollY = 0;
scrollWindow.maxScrollY = Math.max(localY - scrollWindow.clipHeight, 0);
@@ -381,6 +407,9 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
linkedItem.isNormalItem = ((GuiNpcButtonYesNo) guibutton).getBoolean();
} else if (id == 26 && guibutton instanceof GuiNpcButtonYesNo) {
linkedItem.display.durabilityShow = ((GuiNpcButtonYesNo) guibutton).getBoolean();
} else if (id == 29 && guibutton instanceof GuiNpcButtonYesNo) {
linkedItem.display.animated = ((GuiNpcButtonYesNo) guibutton).getBoolean();
initGui();
}
}
@@ -429,6 +458,10 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
linkedItem.display.translateY = textField.getFloat();
} else if (id == 63) {
linkedItem.display.translateZ = textField.getFloat();
} else if (id == 71) {
linkedItem.display.frameCount = Math.max(1, textField.getInteger());
} else if (id == 72) {
linkedItem.display.frametime = Math.max(1, textField.getInteger());
}
}
@@ -472,7 +505,20 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
int iconWidth = data.getTotalWidth();
int iconHeight = data.getTotalWidth();
int width = data.getTotalWidth();
int height = data.getTotalWidth();
int height = data.getTotalHeight();
// Animation V offset for preview
if (data.isAnimated()) {
iconY += (int) (data.getCurrentFrameVOffset() * height);
iconHeight = data.getFrameHeight();
} else if (linkedItem.display.animated != null && linkedItem.display.animated
&& linkedItem.display.frameCount != null && linkedItem.display.frameCount > 1) {
iconY += (int) (AnimationHelper.getFrameVOffset(height, linkedItem.display.frameCount, linkedItem.display.frametime) * height);
iconHeight = height / linkedItem.display.frameCount;
} else {
iconHeight = data.getTotalWidth();
height = data.getTotalWidth();
}
float[] colors = ColorUtil.hexToRGB(linkedItem.display.itemColor);
GL11.glColor3f(colors[0], colors[1], colors[2]);
@@ -145,11 +145,12 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL
scrollSounds.resetScroll();
getTextField(66).setText("");
soundSearch = "";
initGui();
}
if (guiCustomScroll.id == 1) {
selectedResource = new ResourceLocation(selectedDomain, guiCustomScroll.getSelected());
getButton(1).enabled = true;
}
initGui();
}
@Override
@@ -6,6 +6,7 @@ import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.texture.TextureManager;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.PlayerEffect;
@@ -82,6 +83,13 @@ public class GuiEffectBar extends GuiScreen {
int texWidth = imageData.getTotalWidth();
int texHeight = imageData.getTotalHeight();
// Animation V offset
if (imageData.isAnimated()) {
iconV += (int) (imageData.getCurrentFrameVOffset() * texHeight);
} else if (entry.effect.animated && entry.effect.frameCount > 1) {
iconV += (int) (AnimationHelper.getFrameVOffset(texHeight, entry.effect.frameCount, entry.effect.frametime) * texHeight);
}
// Use iconYOffset to vertically center the icon
func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight);
@@ -191,7 +199,14 @@ public class GuiEffectBar extends GuiScreen {
if (imageData != null && imageData.imageLoaded()) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
imageData.bindTexture();
func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalHeight());
int tooltipIconV = hoveredEffect.iconY;
int tooltipTexH = imageData.getTotalHeight();
if (imageData.isAnimated()) {
tooltipIconV += (int) (imageData.getCurrentFrameVOffset() * tooltipTexH);
} else if (hoveredEffect.animated && hoveredEffect.frameCount > 1) {
tooltipIconV += (int) (AnimationHelper.getFrameVOffset(tooltipTexH, hoveredEffect.frameCount, hoveredEffect.frametime) * tooltipTexH);
}
func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, tooltipIconV, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), tooltipTexH);
}
textureManager.bindTexture(specialIcons);
@@ -0,0 +1,49 @@
package noppes.npcs.client.renderer;
import net.minecraft.client.Minecraft;
/**
* Static utility for computing animated texture UV offsets.
* Used by renderers when animation parameters come from data class fields
* rather than .mcmeta auto-detection on ImageData.
*/
public class AnimationHelper {
/**
* Returns the V-coordinate offset (0.0-1.0) for the current animation frame.
* Based on system time for consistent sync across all animated textures.
*
* @param totalHeight Total pixel height of the sprite strip
* @param frameCount Number of frames in the strip
* @param frametime Ticks per frame (1 tick = 50ms)
* @return V offset in 0.0-1.0 range, or 0.0 if not animated
*/
public static float getFrameVOffset(int totalHeight, int frameCount, int frametime) {
if (frameCount <= 1 || totalHeight <= 0) {
return 0f;
}
frametime = Math.max(1, frametime);
long millis = Minecraft.getSystemTime();
int tick = (int) (millis / 50L);
int frameIdx = (tick / frametime) % frameCount;
int frameHeight = totalHeight / frameCount;
return (float) (frameIdx * frameHeight) / (float) totalHeight;
}
/**
* Returns the V-coordinate size of a single frame in 0.0-1.0 range.
*
* @param totalHeight Total pixel height of the sprite strip
* @param frameCount Number of frames in the strip
* @return V size of one frame, or 1.0 if not animated
*/
public static float getFrameVSize(int totalHeight, int frameCount) {
if (frameCount <= 1 || totalHeight <= 0) {
return 1f;
}
int frameHeight = totalHeight / frameCount;
return (float) frameHeight / (float) totalHeight;
}
}
@@ -1,5 +1,8 @@
package noppes.npcs.client.renderer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.IResource;
@@ -11,6 +14,7 @@ import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ImageData {
private final ResourceLocation location;
@@ -23,6 +27,14 @@ public class ImageData {
private boolean gotWidthHeight;
private boolean invalid;
// Animation fields
private boolean animated = false;
private int frameCount = 1;
private int frametime = 2;
private int[] frames = null;
private boolean interpolate = false;
private boolean mcmetaChecked = false;
public ImageData(String directory) {
this.location = new ResourceLocation(directory);
if (directory.startsWith("https://") || directory.startsWith("http://")) {
@@ -141,6 +153,11 @@ public class ImageData {
private void correctWidthHeight() {
this.totalWidth = Math.max(this.totalWidth, 1);
this.totalHeight = Math.max(this.totalHeight, 1);
if (!this.isUrl && !this.mcmetaChecked) {
this.mcmetaChecked = true;
tryLoadMcmeta();
}
}
public int getTotalWidth() {
@@ -150,4 +167,112 @@ public class ImageData {
public int getTotalHeight() {
return this.gotWidthHeight ? this.totalHeight : -1;
}
// ═══════════════════════════════════════════════════════════════════
// ANIMATION
// ═══════════════════════════════════════════════════════════════════
private void tryLoadMcmeta() {
try {
ResourceLocation mcmetaLoc = new ResourceLocation(
location.getResourceDomain(),
location.getResourcePath() + ".mcmeta"
);
IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(mcmetaLoc);
InputStream stream = resource.getInputStream();
try {
InputStreamReader reader = new InputStreamReader(stream);
JsonObject root = new JsonParser().parse(reader).getAsJsonObject();
if (root.has("animation")) {
JsonObject anim = root.getAsJsonObject("animation");
this.animated = true;
if (anim.has("frametime")) {
this.frametime = Math.max(1, anim.get("frametime").getAsInt());
}
if (anim.has("interpolate")) {
this.interpolate = anim.get("interpolate").getAsBoolean();
}
if (anim.has("frames")) {
JsonArray framesArray = anim.getAsJsonArray("frames");
this.frames = new int[framesArray.size()];
int maxFrame = 0;
for (int i = 0; i < framesArray.size(); i++) {
this.frames[i] = framesArray.get(i).getAsInt();
if (this.frames[i] > maxFrame) {
maxFrame = this.frames[i];
}
}
this.frameCount = maxFrame + 1;
} else if (this.totalWidth > 0) {
this.frameCount = Math.max(1, this.totalHeight / this.totalWidth);
}
}
} finally {
stream.close();
}
} catch (Exception ignored) {
// No .mcmeta found or parse error — not animated
}
}
/**
* Programmatically enable animation on this ImageData.
* Used when animation settings come from data class fields rather than .mcmeta files.
*/
public void setAnimation(int frameCount, int frametime) {
if (frameCount > 1) {
this.animated = true;
this.frameCount = Math.max(1, frameCount);
this.frametime = Math.max(1, frametime);
}
}
public boolean isAnimated() {
return this.animated && this.frameCount > 1;
}
public int getFrameCount() {
return this.frameCount;
}
public int getFrameTime() {
return this.frametime;
}
/**
* Returns the pixel height of a single animation frame.
* For non-animated textures, returns the total height.
*/
public int getFrameHeight() {
if (this.animated && this.frameCount > 1) {
return Math.max(1, this.totalHeight / this.frameCount);
}
return this.gotWidthHeight ? this.totalHeight : -1;
}
/**
* Returns the V-coordinate offset (0.0-1.0) for the current animation frame.
* Based on system time so all instances of the same texture animate in sync.
* Returns 0.0 for non-animated textures.
*/
public float getCurrentFrameVOffset() {
if (!this.animated || this.frameCount <= 1 || this.totalHeight <= 0) {
return 0f;
}
long millis = Minecraft.getSystemTime();
int tick = (int) (millis / 50L);
int frameIdx;
if (this.frames != null && this.frames.length > 0) {
frameIdx = (tick / this.frametime) % this.frames.length;
frameIdx = this.frames[frameIdx];
} else {
frameIdx = (tick / this.frametime) % this.frameCount;
}
int frameHeight = this.totalHeight / this.frameCount;
return (float) (frameIdx * frameHeight) / (float) this.totalHeight;
}
}
@@ -17,6 +17,7 @@ import net.minecraftforge.client.IItemRenderer;
import noppes.npcs.api.item.IItemCustomizable;
import noppes.npcs.api.item.IItemStack;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.renderer.AnimationHelper;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.items.ItemCustomizable;
import noppes.npcs.scripted.NpcAPI;
@@ -222,7 +223,8 @@ public class ItemCustomRenderer implements IItemRenderer {
int pass = 0;
GL11.glPushMatrix();
ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture();
ImageData entityImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture());
entityImageData.bindTexture();
if (renderInFrame) {
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
@@ -233,10 +235,22 @@ public class ItemCustomRenderer implements IItemRenderer {
Tessellator tessellator = Tessellator.instance;
// Animation V offset for entity rendering
float entityVOff = 0f;
float entityVEnd = 1f;
if (entityImageData.isAnimated()) {
entityVOff = entityImageData.getCurrentFrameVOffset();
entityVEnd = entityVOff + (float) entityImageData.getFrameHeight() / entityImageData.getTotalHeight();
} else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated()
&& scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) {
entityVOff = AnimationHelper.getFrameVOffset(entityImageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime());
entityVEnd = entityVOff + AnimationHelper.getFrameVSize(entityImageData.getTotalHeight(), scriptCustomItem.getFrameCount());
}
float f14 = 0.0F;
float f15 = 1.0F;
float f4 = 0.0F;
float f5 = 1.0F;
float f4 = entityVOff;
float f5 = entityVEnd;
float f6 = 1.0F;
float f7 = 0.5F;
float f8 = 0.25F;
@@ -272,8 +286,11 @@ public class ItemCustomRenderer implements IItemRenderer {
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
}*/
ImageData imageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture());
ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, imageData.getTotalWidth(), imageData.getTotalHeight(), f9);
ImageData loopImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture());
int entityFrameH = loopImageData.isAnimated() ? loopImageData.getFrameHeight()
: (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated() && scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1
? loopImageData.getTotalHeight() / scriptCustomItem.getFrameCount() : loopImageData.getTotalHeight());
ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, loopImageData.getTotalWidth(), entityFrameH, f9);
if (itemStack.hasEffect(pass)) {
GL11.glDepthFunc(GL11.GL_EQUAL);
@@ -359,8 +376,20 @@ public class ItemCustomRenderer implements IItemRenderer {
GL11.glDisable(GL11.GL_LIGHTING); //Forge: Make sure that render states are reset, a renderEffect can derp them up.
GL11.glEnable(GL11.GL_ALPHA_TEST);
ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture();
renderCustomItemSlot(0, 0, 16, 16, itemRed, itemGreen, itemBlue);
ImageData imageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture());
imageData.bindTexture();
float vOff = 0f;
float vEnd = 1f;
if (imageData.isAnimated()) {
vOff = imageData.getCurrentFrameVOffset();
vEnd = vOff + (float) imageData.getFrameHeight() / imageData.getTotalHeight();
} else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated()
&& scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) {
vOff = AnimationHelper.getFrameVOffset(imageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime());
vEnd = vOff + AnimationHelper.getFrameVSize(imageData.getTotalHeight(), scriptCustomItem.getFrameCount());
}
renderCustomItemSlot(0, 0, 16, 16, itemRed, itemGreen, itemBlue, vOff, vEnd);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_ALPHA_TEST);
@@ -412,13 +441,17 @@ public class ItemCustomRenderer implements IItemRenderer {
}
public void renderCustomItemSlot(int posX, int posY, int imageWidth, int imageHeight, float itemRed, float itemGreen, float itemBlue) {
renderCustomItemSlot(posX, posY, imageWidth, imageHeight, itemRed, itemGreen, itemBlue, 0f, 1f);
}
public void renderCustomItemSlot(int posX, int posY, int imageWidth, int imageHeight, float itemRed, float itemGreen, float itemBlue, float vOff, float vEnd) {
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA_F(itemRed, itemGreen, itemBlue, 1.0F);
tessellator.addVertexWithUV((double) (posX), (double) (posY + imageHeight), 0, 0, 1);
tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY + imageHeight), 0, 1, 1);
tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY), 0, 1, 0);
tessellator.addVertexWithUV((double) (posX), (double) (posY), 0, 0, 0);
tessellator.addVertexWithUV((double) (posX), (double) (posY + imageHeight), 0, 0, vEnd);
tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY + imageHeight), 0, 1, vEnd);
tessellator.addVertexWithUV((double) (posX + imageWidth), (double) (posY), 0, 1, vOff);
tessellator.addVertexWithUV((double) (posX), (double) (posY), 0, 0, vOff);
tessellator.draw();
}
@@ -429,7 +462,8 @@ public class ItemCustomRenderer implements IItemRenderer {
TextureManager texturemanager = mc.getTextureManager();
int par3 = 0;
ClientCacheHandler.getImageData(scriptCustomItem.getTexture()).bindTexture();
ImageData item3dImageData = ClientCacheHandler.getImageData(scriptCustomItem.getTexture());
item3dImageData.bindTexture();
Tessellator tessellator = Tessellator.instance;
IIcon icon = entityLivingBase.getItemIcon(itemStack, par3);
@@ -447,7 +481,19 @@ public class ItemCustomRenderer implements IItemRenderer {
GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F);
renderCustomItemIn2D(scriptCustomItem, tessellator, 1.0F, 0.0F, 0.0F, 1.0F, 0.0625F);
// Animation V offset for 3D handheld rendering
float item3dVOff = 0f;
float item3dVEnd = 1f;
if (item3dImageData.isAnimated()) {
item3dVOff = item3dImageData.getCurrentFrameVOffset();
item3dVEnd = item3dVOff + (float) item3dImageData.getFrameHeight() / item3dImageData.getTotalHeight();
} else if (scriptCustomItem.isTextureAnimated() != null && scriptCustomItem.isTextureAnimated()
&& scriptCustomItem.getFrameCount() != null && scriptCustomItem.getFrameCount() > 1) {
item3dVOff = AnimationHelper.getFrameVOffset(item3dImageData.getTotalHeight(), scriptCustomItem.getFrameCount(), scriptCustomItem.getFrameTime());
item3dVEnd = item3dVOff + AnimationHelper.getFrameVSize(item3dImageData.getTotalHeight(), scriptCustomItem.getFrameCount());
}
renderCustomItemIn2D(scriptCustomItem, tessellator, 1.0F, item3dVOff, 0.0F, item3dVEnd, 0.0625F);
if (itemStack.hasEffect(par3)) {
GL11.glDepthFunc(GL11.GL_EQUAL);
@@ -485,7 +531,10 @@ public class ItemCustomRenderer implements IItemRenderer {
public static void renderCustomItemIn2D(IItemCustomizable wrapper, Tessellator p_78439_0_, float p_78439_1_, float p_78439_2_, float p_78439_3_, float p_78439_4_, float p_78439_7_) {
ImageData imageData = ClientCacheHandler.getImageData(wrapper.getTexture());
int width = imageData.getTotalWidth();
int height = imageData.getTotalHeight();
// Use frame height for edge pixel calculations so animated strips render correctly
int height = imageData.isAnimated() ? imageData.getFrameHeight()
: (wrapper.isTextureAnimated() != null && wrapper.isTextureAnimated() && wrapper.getFrameCount() != null && wrapper.getFrameCount() > 1
? imageData.getTotalHeight() / wrapper.getFrameCount() : imageData.getTotalHeight());
p_78439_0_.startDrawingQuads();
p_78439_0_.setNormal(0.0F, 0.0F, 1.0F);
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more