Merge remote-tracking branch 'origin/dev' into dev

This commit is contained in:
luisc committed 2026-02-23 16:15:56 -06:00
commit 088b1c211e
195 files changed
+8227 -3310

No files matched your search

@@ -2,11 +2,11 @@ package noppes.npcs;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry;
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;
import kamkeel.npcs.controllers.data.ability.ConcurrentSlot;
import kamkeel.npcs.controllers.data.ability.ToggleEntry;
import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.DamageSource;
@@ -268,6 +268,15 @@ public abstract class AbstractDataAbilities {
return currentAbility != null && currentAbility.isExecuting();
}
/**
* True when an executing ability grants invulnerability for its current phase.
*/
public boolean isCurrentAbilityInvulnerable() {
return currentAbility != null
&& currentAbility.isExecuting()
&& currentAbility.isInvulnerableForCurrentPhase();
}
/**
* Get the currently executing ability.
*/
@@ -296,7 +305,7 @@ public abstract class AbstractDataAbilities {
/**
* Currently active toggles. Key = ability key, Value = toggle entry with state and tick counter.
*/
protected Map<String, ToggleEntry> activeToggles = new LinkedHashMap<>();
protected Map<String, AbilityToggleEntry> activeToggles = new LinkedHashMap<>();
/**
* Cycle a toggle ability to its next state.
@@ -306,7 +315,7 @@ public abstract class AbstractDataAbilities {
* @return The new state (0 = off, 1+ = active state number)
*/
public int toggleAbility(String key) {
ToggleEntry existing = activeToggles.get(key);
AbilityToggleEntry existing = activeToggles.get(key);
if (existing != null) {
int currentState = existing.getState();
int maxStates = existing.getAbility().getToggleStates();
@@ -326,7 +335,7 @@ public abstract class AbstractDataAbilities {
* @return 0 if not active, 1+ for active state
*/
public int getToggleState(String key) {
ToggleEntry entry = activeToggles.get(key);
AbilityToggleEntry entry = activeToggles.get(key);
return entry != null ? entry.getState() : 0;
}
@@ -340,7 +349,7 @@ public abstract class AbstractDataAbilities {
}
return;
}
ToggleEntry existing = activeToggles.get(key);
AbilityToggleEntry existing = activeToggles.get(key);
if (existing != null) {
int currentState = existing.getState();
if (currentState != state) {
@@ -373,7 +382,7 @@ public abstract class AbstractDataAbilities {
if (fireToggleEvent(ability, 0, state)) return false;
ToggleEntry entry = new ToggleEntry(ability, state);
AbilityToggleEntry entry = new AbilityToggleEntry(ability, state);
activeToggles.put(key, entry);
ability.onToggleOn(getEntity());
ability.onToggleStateChanged(getEntity(), 0, state);
@@ -381,7 +390,7 @@ public abstract class AbstractDataAbilities {
return true;
}
private int cycleToggleState(String key, ToggleEntry entry, int oldState, int newState) {
private int cycleToggleState(String key, AbilityToggleEntry entry, int oldState, int newState) {
Ability ability = entry.getAbility();
if (newState < 1 || newState > ability.getToggleStates()) return oldState;
@@ -394,7 +403,7 @@ public abstract class AbstractDataAbilities {
}
private void deactivateToggle(String key) {
ToggleEntry entry = activeToggles.get(key);
AbilityToggleEntry entry = activeToggles.get(key);
if (entry == null) return;
int oldState = entry.getState();
@@ -418,8 +427,8 @@ public abstract class AbstractDataAbilities {
EntityLivingBase entity = getEntity();
List<String> toRemove = null;
for (Map.Entry<String, ToggleEntry> mapEntry : activeToggles.entrySet()) {
ToggleEntry entry = mapEntry.getValue();
for (Map.Entry<String, AbilityToggleEntry> mapEntry : activeToggles.entrySet()) {
AbilityToggleEntry entry = mapEntry.getValue();
entry.incrementTick();
if (entry.getAbility().hasActiveToggle()) {
@@ -441,7 +450,7 @@ public abstract class AbstractDataAbilities {
if (toRemove != null) {
for (String key : toRemove) {
ToggleEntry entry = activeToggles.remove(key);
AbilityToggleEntry entry = activeToggles.remove(key);
if (entry != null) {
int oldState = entry.getState();
entry.getAbility().onToggleOff(entity);
@@ -483,8 +492,8 @@ public abstract class AbstractDataAbilities {
protected void clearActiveToggles() {
if (activeToggles.isEmpty()) return;
EntityLivingBase entity = getEntity();
for (Map.Entry<String, ToggleEntry> mapEntry : activeToggles.entrySet()) {
ToggleEntry entry = mapEntry.getValue();
for (Map.Entry<String, AbilityToggleEntry> mapEntry : activeToggles.entrySet()) {
AbilityToggleEntry entry = mapEntry.getValue();
entry.getAbility().onToggleOff(entity);
entry.getAbility().onToggleStateChanged(entity, entry.getState(), 0);
}
@@ -502,7 +511,7 @@ public abstract class AbstractDataAbilities {
Ability ability = AbilityController.Instance != null
? AbilityController.Instance.resolveAbility(key) : null;
if (ability != null && ability.isToggleable()) {
activeToggles.put(key, new ToggleEntry(ability, state));
activeToggles.put(key, new AbilityToggleEntry(ability, state));
}
} else {
activeToggles.remove(key);
@@ -1034,6 +1043,62 @@ public abstract class AbstractDataAbilities {
protected void onInterruptComplete() {
}
/**
* Cancel the currently executing ability (voluntary player action).
* Unlike interrupt, this always goes directly to IDLE (never DAZED),
* immediately rolls cooldown, and clears state.
* Also handles cancellation during chain delay (between chain entries).
*/
public void cancelCurrentAbility() {
boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting();
boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0;
if (!hasExecutingAbility && !isInChainDelay) return;
if (hasExecutingAbility) {
AbilityPhase phase = currentAbility.getPhase();
// Cannot cancel during DAZED (already interrupted)
if (phase == AbilityPhase.DAZED) return;
// Only allow cancel during active phases
if (phase != AbilityPhase.WINDUP && phase != AbilityPhase.ACTIVE
&& phase != AbilityPhase.BURST_DELAY) return;
// Remove telegraph
removeTelegraph(currentAbility);
// Fire extender complete hook (cancelled = interrupted)
AbilityController.Instance.fireOnAbilityComplete(currentAbility, getEntity(), getTarget(), true);
// Fire interrupt event (source=null, damage=0 for voluntary cancel)
fireInterruptEvent(currentAbility, getTarget(), null, 0);
// Cancel the ability (cleanup + go directly to IDLE, no DAZED)
currentAbility.onInterrupt(getEntity(), null, 0);
currentAbility.cancel();
// Release locks and stop animation
stopAbilityAnimation();
releaseRotationControl();
releaseLockedPosition();
}
// Roll cooldown
if (currentChain != null) {
rollChainCooldown(currentChain);
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
} else if (currentAbility != null) {
rollCooldown(currentAbility);
}
// Interrupt all concurrent slots
interruptConcurrentSlots();
// Clear state via the normal completion path
onAbilityComplete();
}
// ═══════════════════════════════════════════════════════════════════
// CHAINED ABILITY EXECUTION
// ═══════════════════════════════════════════════════════════════════
@@ -209,21 +209,31 @@ public class AnimationMixinFunctions {
return null;
}
public static void playerFullModel_head(Entity p_78088_1_, CallbackInfo callbackInfo) {
if (!DBCAddon.IsAvailable() && ClientCacheHandler.playerAnimations.containsKey(p_78088_1_.getUniqueID())) {
AnimationData animData = ClientCacheHandler.playerAnimations.get(p_78088_1_.getUniqueID());
if (animData != null && animData.isActive()) {
Frame frame = (Frame) animData.animation.currentFrame();
if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) {
FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL);
part.interpolateOffset();
part.interpolateAngles();
float pi = 180 / (float) Math.PI;
GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]);
GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0);
GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0);
GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1);
}
public static void playerFullModel_head(Entity entity, CallbackInfo callbackInfo) {
if (!ClientCacheHandler.playerAnimations.containsKey(entity.getUniqueID())) return;
AnimationData animData = ClientCacheHandler.playerAnimations.get(entity.getUniqueID());
if (animData == null || !animData.isActive()) return;
// Snap body rotation to head so animations face the look direction
if (entity instanceof EntityLivingBase) {
EntityLivingBase living = (EntityLivingBase) entity;
living.renderYawOffset = living.rotationYaw;
living.prevRenderYawOffset = living.prevRotationYaw;
}
// FULL_MODEL GL transforms (non-DBC only)
if (!DBCAddon.IsAvailable()) {
Frame frame = (Frame) animData.animation.currentFrame();
if (frame.frameParts.containsKey(EnumAnimationPart.FULL_MODEL)) {
FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL);
part.interpolateOffset();
part.interpolateAngles();
float pi = 180 / (float) Math.PI;
GL11.glTranslatef(part.prevPivots[0], -part.prevPivots[1], part.prevPivots[2]);
GL11.glRotatef(part.prevRotations[0] * pi, 1, 0, 0);
GL11.glRotatef(part.prevRotations[1] * pi, 0, 1, 0);
GL11.glRotatef(part.prevRotations[2] * pi, 0, 0, 1);
}
}
}
+12 -11
View File
@@ -28,14 +28,15 @@ import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.TelegraphController;
import kamkeel.npcs.controllers.data.profile.CNPCData;
import kamkeel.npcs.developer.Developer;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityEnergySlicer;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.util.BukkitUtil;
@@ -121,7 +122,7 @@ import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta5")
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta7")
public class CustomNpcs {
@SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")
@@ -291,15 +292,15 @@ public class CustomNpcs {
registerNewEntity(EntityChairMount.class, "CustomNpcChairMount", 64, 10, false);
registerNewEntity(EntityProjectile.class, "throwableitem", 64, 3, true);
registerNewEntity(EntityMagicProjectile.class, "magicprojectile", 64, 3, true);
registerNewEntity(EntityAbilityOrb.class, "abilityorb", 64, 3, true);
registerNewEntity(EntityAbilityDisc.class, "abilitydisc", 64, 3, true);
registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 3, true);
registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 3, true);
registerNewEntity(EntityAbilityOrb.class, "abilityorb", 64, 1, true);
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(EntityAbilityZone.class, "abilityzone", 64, 3, true);
registerNewEntity(EntityEnergyDome.class, "energydome", 64, 3, true);
registerNewEntity(EntityEnergyPanel.class, "energypanel", 64, 3, true);
registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 3, true);
registerNewEntity(EntityAbilityDome.class, "energydome", 64, 3, true);
registerNewEntity(EntityAbilityPanel.class, "energypanel", 64, 3, true);
registerNewEntity(EntityEnergySlicer.class, "energyslicer", 64, 1, true);
new RecipeController();
@@ -430,7 +431,7 @@ public class CustomNpcs {
}
kamkeel.npcs.entity.EntityEnergyProjectile.clearAllProjectiles();
kamkeel.npcs.entity.EntityEnergyBarrier.clearAllBarriers();
EntityAbilityBarrier.clearAllBarriers();
if (FMLCommonHandler.instance().getSide().isClient())
clientJaninoCompiler = null;
+11 -9
View File
@@ -3,10 +3,10 @@ package noppes.npcs;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityAction;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.ToggleEntry;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket;
@@ -14,7 +14,6 @@ import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.util.DamageSource;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.entity.EntityNPCInterface;
@@ -556,12 +555,15 @@ public class DataAbilities extends AbstractDataAbilities {
* @return true if ability was interrupted
*/
public boolean onDamage(DamageSource source, float amount) {
// Track hit for hit count condition
recordHit();
if (currentAbility == null || !currentAbility.isExecuting()) {
return false;
}
if (currentAbility.isInvulnerableForCurrentPhase()) {
return false;
}
// Track hit for hit count condition
recordHit();
net.minecraft.entity.Entity sourceEntity = source.getEntity();
EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null;
@@ -1095,7 +1097,7 @@ public class DataAbilities extends AbstractDataAbilities {
// Active toggles (compound format with state)
NBTTagList toggleList = new NBTTagList();
for (Map.Entry<String, ToggleEntry> entry : activeToggles.entrySet()) {
for (Map.Entry<String, AbilityToggleEntry> entry : activeToggles.entrySet()) {
NBTTagCompound toggleNbt = new NBTTagCompound();
toggleNbt.setString("Key", entry.getKey());
toggleNbt.setInteger("State", entry.getValue().getState());
+227 -17
View File
@@ -28,28 +28,45 @@ import noppes.npcs.scripted.event.CustomNPCsEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class NPCSpawning {
private static Set<ChunkCoordIntPair> eligibleChunksForSpawning = Sets.newHashSet();
private static final byte CHUNK_SPAWN_RADIUS = 7;
private static final int SPAWN_ATTEMPTS_PER_CHUNK = 3;
private static final int NATURAL_CAP_PER_256_CHUNKS = 70;
private static final long RUNTIME_SPAWN_TICK_INTERVAL = 20L;
private static final int RUNTIME_SPAWN_CYCLE_TICKS = 400;
private static final String NATURAL_SPAWN_ID_TAG = "CNPCNaturalSpawnId";
private static final String NATURAL_SPAWN_NAME_TAG = "CNPCNaturalSpawnName";
private static final String NATURAL_SPAWN_TIME_TAG = "CNPCNaturalSpawnTime";
private static final Map<Long, Long> SPAWN_COOLDOWNS = new HashMap<Long, Long>();
private static final Map<Integer, RuntimeChunkState> RUNTIME_CHUNK_STATES = new HashMap<Integer, RuntimeChunkState>();
private static boolean animalSpawn;
private static boolean monsterSpawn;
private static boolean airSpawn;
private static boolean liquidSpawn;
private static class RuntimeChunkState {
public ArrayList<ChunkCoordIntPair> chunks = new ArrayList<ChunkCoordIntPair>();
public int index = 0;
public int signature = 0;
}
public static void findChunksForSpawning(WorldServer world) {
if (SpawnController.Instance.data.isEmpty() || world.getWorldInfo().getWorldTotalTime() % 400L != 0L)
if (SpawnController.Instance.data.isEmpty() || world.getWorldInfo().getWorldTotalTime() % RUNTIME_SPAWN_TICK_INTERVAL != 0L)
return;
eligibleChunksForSpawning.clear();
for (int i = 0; i < world.playerEntities.size(); ++i) {
EntityPlayer entityplayer = (EntityPlayer) world.playerEntities.get(i);
int j = MathHelper.floor_double(entityplayer.posX / 16.0D);
int k = MathHelper.floor_double(entityplayer.posZ / 16.0D);
byte size = 7;
byte size = CHUNK_SPAWN_RADIUS;
for (int x = -size; x <= size; ++x) {
for (int z = -size; z <= size; ++z) {
@@ -60,22 +77,29 @@ public class NPCSpawning {
}
}
}
if (countNPCs(world) > eligibleChunksForSpawning.size()) {
int cap = getScaledNaturalCap(eligibleChunksForSpawning.size());
int npcCount = countNaturalSpawnedNPCs(world);
if (npcCount >= cap) {
return;
}
ArrayList<ChunkCoordIntPair> tmp = new ArrayList(eligibleChunksForSpawning);
Collections.shuffle(tmp);
Iterator<ChunkCoordIntPair> iterator = tmp.iterator();
HashMap<Integer, Integer> spawnEntryCounts = getNaturalSpawnEntryCounts(world);
int chunkBudget = getRuntimeChunkBudget(eligibleChunksForSpawning.size());
List<ChunkCoordIntPair> chunksToProcess = getRuntimeChunkBatch(world, chunkBudget);
while (iterator.hasNext()) {
ChunkCoordIntPair chunkcoordintpair1 = iterator.next();
for (ChunkCoordIntPair chunkcoordintpair1 : chunksToProcess) {
if (npcCount >= cap) {
return;
}
ChunkPosition chunkposition = getChunk(world, chunkcoordintpair1.chunkXPos, chunkcoordintpair1.chunkZPos);
int j1 = chunkposition.chunkPosX;
int y = chunkposition.chunkPosY;
int l1 = chunkposition.chunkPosZ;
for (int i = 0; i < 3; i++) {
for (int i = 0; i < SPAWN_ATTEMPTS_PER_CHUNK; i++) {
if (npcCount >= cap) {
return;
}
int x = j1;
int z = l1;
byte b1 = 6;
@@ -85,25 +109,71 @@ public class NPCSpawning {
String name = world.getBiomeGenForCoords(x, z).biomeName;
SpawnData data = SpawnController.Instance.getRandomSpawnData(name, world.provider.dimensionId);
if (data == null || !canCreatureTypeSpawnAtLocation(data, world, x, y, z) || world.getClosestPlayer(x, y, z, 24.0D) != null)
if (data == null)
continue;
spawnData(data, world, x, y, z);
if (trySpawnWithEntryConfig(data, world, x, y, z, world.rand, spawnEntryCounts)) {
npcCount++;
}
}
}
}
public static int countNPCs(World world) {
private static int getRuntimeChunkBudget(int eligibleChunkCount) {
if (eligibleChunkCount <= 0) {
return 0;
}
int runsPerCycle = Math.max(1, (int) (RUNTIME_SPAWN_CYCLE_TICKS / RUNTIME_SPAWN_TICK_INTERVAL));
return Math.max(1, (int) Math.ceil((double) eligibleChunkCount / runsPerCycle));
}
private static List<ChunkCoordIntPair> getRuntimeChunkBatch(World world, int chunkBudget) {
ArrayList<ChunkCoordIntPair> result = new ArrayList<ChunkCoordIntPair>();
if (chunkBudget <= 0 || eligibleChunksForSpawning.isEmpty()) {
return result;
}
int dimensionId = world.provider.dimensionId;
RuntimeChunkState state = RUNTIME_CHUNK_STATES.get(dimensionId);
if (state == null) {
state = new RuntimeChunkState();
RUNTIME_CHUNK_STATES.put(dimensionId, state);
}
int signature = eligibleChunksForSpawning.hashCode();
if (state.chunks.isEmpty() || state.signature != signature || state.index >= state.chunks.size()) {
state.chunks = new ArrayList<ChunkCoordIntPair>(eligibleChunksForSpawning);
Collections.shuffle(state.chunks);
state.index = 0;
state.signature = signature;
}
int remaining = state.chunks.size() - state.index;
int count = Math.min(chunkBudget, Math.max(0, remaining));
for (int i = 0; i < count; i++) {
result.add(state.chunks.get(state.index++));
}
return result;
}
private static int countNaturalSpawnedNPCs(World world) {
int count = 0;
List<Entity> list = world.loadedEntityList;
for (Entity entity : list) {
if (entity instanceof EntityNPCInterface) {
if (entity instanceof EntityNPCInterface && !entity.isDead && entity.getEntityData().hasKey(NATURAL_SPAWN_ID_TAG)) {
count++;
}
}
return count;
}
private static int getScaledNaturalCap(int eligibleChunkCount) {
if (eligibleChunkCount <= 0) {
return 0;
}
return Math.max(1, NATURAL_CAP_PER_256_CHUNKS * eligibleChunkCount / 256);
}
protected static ChunkPosition getChunk(World world, int x, int z) {
Chunk chunk = world.getChunkFromChunkCoords(x, z);
int k = x * 16 + world.rand.nextInt(16);
@@ -112,9 +182,134 @@ public class NPCSpawning {
return new ChunkPosition(k, i1, l);
}
private static int getCap(World world) {
Set<ChunkCoordIntPair> chunkSet = Sets.newHashSet();
for (int i = 0; i < world.playerEntities.size(); ++i) {
EntityPlayer entityplayer = (EntityPlayer) world.playerEntities.get(i);
int j = MathHelper.floor_double(entityplayer.posX / 16.0D);
int k = MathHelper.floor_double(entityplayer.posZ / 16.0D);
byte size = CHUNK_SPAWN_RADIUS;
for (int x = -size; x <= size; ++x) {
for (int z = -size; z <= size; ++z) {
chunkSet.add(new ChunkCoordIntPair(x + j, z + k));
}
}
}
return getScaledNaturalCap(chunkSet.size());
}
private static HashMap<Integer, Integer> getNaturalSpawnEntryCounts(World world) {
HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
List<Entity> list = world.loadedEntityList;
for (Entity entity : list) {
if (entity == null || entity.isDead || !(entity instanceof EntityNPCInterface)) {
continue;
}
NBTTagCompound entityData = entity.getEntityData();
if (!entityData.hasKey(NATURAL_SPAWN_ID_TAG)) {
continue;
}
int spawnId = entityData.getInteger(NATURAL_SPAWN_ID_TAG);
Integer count = counts.get(spawnId);
counts.put(spawnId, count == null ? 1 : count + 1);
}
return counts;
}
private static long getSpawnCooldownKey(World world, int spawnId) {
return ((long) world.provider.dimensionId << 32) ^ (spawnId & 0xffffffffL);
}
private static boolean isSpawnOnCooldown(World world, SpawnData data) {
if (data.cooldownTicks <= 0 || data.id < 0) {
return false;
}
long key = getSpawnCooldownKey(world, data.id);
Long lastSpawnTick = SPAWN_COOLDOWNS.get(key);
if (lastSpawnTick == null) {
return false;
}
long tickDelta = world.getWorldInfo().getWorldTotalTime() - lastSpawnTick;
if (tickDelta < 0) {
SPAWN_COOLDOWNS.remove(key);
return false;
}
return tickDelta < data.cooldownTicks;
}
private static void markSpawnCooldown(World world, SpawnData data) {
if (data.cooldownTicks <= 0 || data.id < 0) {
return;
}
long key = getSpawnCooldownKey(world, data.id);
SPAWN_COOLDOWNS.put(key, world.getWorldInfo().getWorldTotalTime());
}
private static boolean isSpawnEntryAtCapacity(SpawnData data, Map<Integer, Integer> spawnEntryCounts) {
if (data.maxAlive <= 0 || data.id < 0) {
return false;
}
Integer currentCount = spawnEntryCounts.get(data.id);
return currentCount != null && currentCount >= data.maxAlive;
}
private static void incrementSpawnEntryCount(SpawnData data, Map<Integer, Integer> spawnEntryCounts) {
if (data.id < 0) {
return;
}
Integer currentCount = spawnEntryCounts.get(data.id);
spawnEntryCounts.put(data.id, currentCount == null ? 1 : currentCount + 1);
}
private static boolean hasNearbyPlayer(SpawnData data, World world, int x, int y, int z) {
if (data.playerMinDistance <= 0) {
return false;
}
return world.getClosestPlayer(x, y, z, data.playerMinDistance) != null;
}
private static boolean trySpawnWithEntryConfig(SpawnData data, World world, int x, int y, int z, Random rand, Map<Integer, Integer> spawnEntryCounts) {
if (y < data.spawnHeightMin || y > data.spawnHeightMax) {
return false;
}
if (isSpawnEntryAtCapacity(data, spawnEntryCounts) || isSpawnOnCooldown(world, data)) {
return false;
}
int attempts = Math.max(1, data.attemptsPerCycle);
for (int attempt = 0; attempt < attempts; attempt++) {
int attemptX = x;
int attemptZ = z;
if (attempt > 0) {
attemptX += rand.nextInt(5) - rand.nextInt(5);
attemptZ += rand.nextInt(5) - rand.nextInt(5);
}
if (!canCreatureTypeSpawnAtLocation(data, world, attemptX, y, attemptZ) || hasNearbyPlayer(data, world, attemptX, y, attemptZ)) {
continue;
}
if (spawnData(data, world, attemptX, y, attemptZ)) {
incrementSpawnEntryCount(data, spawnEntryCounts);
markSpawnCooldown(world, data);
return true;
}
}
return false;
}
public static void performWorldGenSpawning(World world, int x, int z, Random rand) {
int cap = getCap(world);
int npcCount = countNaturalSpawnedNPCs(world);
if (npcCount >= cap) {
return;
}
HashMap<Integer, Integer> spawnEntryCounts = getNaturalSpawnEntryCounts(world);
BiomeGenBase biome = world.getBiomeGenForCoords(x + 8, z + 8);
while (rand.nextFloat() < biome.getSpawningChance()) {
if (npcCount >= cap) {
return;
}
SpawnData data = SpawnController.Instance.getRandomSpawnData(biome.biomeName, world.provider.dimensionId);
if (data == null)
continue;
@@ -127,6 +322,9 @@ public class NPCSpawning {
int i2 = k1;
for (int k2 = 0; k2 < 4; ++k2) {
if (npcCount >= cap) {
return;
}
int l2 = world.getTopSolidOrLiquidBlock(j1, k1);
if (l2 > data.spawnHeightMax || l2 < data.spawnHeightMin) {
continue;
@@ -134,14 +332,16 @@ public class NPCSpawning {
l2 = l2 + (int) ((data.spawnHeightMax - l2) * Math.random());
}
if (!canCreatureTypeSpawnAtLocation(data, world, j1, l2, k1)) {
if (!trySpawnWithEntryConfig(data, world, j1, l2, k1, rand, spawnEntryCounts)) {
j1 += rand.nextInt(5) - rand.nextInt(5);
for (k1 += rand.nextInt(5) - rand.nextInt(5); j1 < x || j1 >= x + size || k1 < z || k1 >= z + size; k1 = i2 + rand.nextInt(5) - rand.nextInt(5)) {
j1 = l1 + rand.nextInt(5) - rand.nextInt(5);
}
} else if (spawnData(data, world, j1, l2, k1))
} else {
npcCount++;
break;
}
}
}
@@ -184,12 +384,23 @@ public class NPCSpawning {
if (spawnEntity instanceof EntityCustomNpc) {
EntityCustomNpc npc = (EntityCustomNpc) spawnEntity;
npc.stats.spawnCycle = 3;
if (data.despawnMode == SpawnData.DESPAWN_FORCE_PERSISTENT) {
npc.stats.canDespawn = false;
npc.stats.playerSetCanDespawn = false;
} else if (data.despawnMode == SpawnData.DESPAWN_FORCE_NATURAL) {
npc.stats.canDespawn = true;
npc.stats.playerSetCanDespawn = true;
}
npc.syncDespawnPersistence();
npc.ais.returnToStart = false;
npc.ais.startPos = new int[]{x, y, z};
npc.updateAI = true;
npc.updateClient = true;
npc.getNavigator().clearPathEntity();
}
entityliving.getEntityData().setInteger(NATURAL_SPAWN_ID_TAG, data.id);
entityliving.getEntityData().setString(NATURAL_SPAWN_NAME_TAG, data.name);
entityliving.getEntityData().setLong(NATURAL_SPAWN_TIME_TAG, world.getWorldInfo().getWorldTotalTime());
spawnEntity.setLocationAndAngles(x + 0.5, y, z + 0.5, world.rand.nextFloat() * 360.0F, 0.0F);
} catch (Exception exception) {
exception.printStackTrace();
@@ -239,4 +450,3 @@ public class NPCSpawning {
return animalSpawn || monsterSpawn || caveSpawn || liquidSpawn;
}
}
@@ -10,6 +10,7 @@ import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.util.AttributeAttackUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
@@ -105,7 +106,8 @@ public class ScriptPlayerEventHandler {
// Skip zeroing if the ability has its own movement (Charge/Dash/Slam)
if (playerData.abilityData.isMovementLocked()) {
Ability current = playerData.abilityData.getCurrentAbility();
if (current == null || !current.hasAbilityMovement()) {
if (current == null || !current.hasAbilityMovement()
|| current.getPhase() != AbilityPhase.ACTIVE) {
boolean sFlying = playerData.abilityData.wasFlyingAtLock()
|| AbilityController.Instance.isPlayerFlying(player);
@@ -120,6 +122,17 @@ public class ScriptPlayerEventHandler {
}
}
// Zero WASD input during ability-controlled movement to prevent
// moveEntityWithHeading from interfering with ability velocity
{
Ability current = playerData.abilityData.getCurrentAbility();
if (current != null && current.hasAbilityMovement()
&& current.getPhase() == AbilityPhase.ACTIVE) {
player.moveForward = 0;
player.moveStrafing = 0;
}
}
if (playerData.updateClient) {
SyncController.syncPlayerData((EntityPlayerMP) player, true);
playerData.updateClient = false;
@@ -629,7 +642,12 @@ public class ScriptPlayerEventHandler {
// Handle ability damage interactions (Guard counter, damage reduction)
PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving);
if (pData != null && pData.abilityData != null && pData.abilityData.isExecutingAbility()) {
event.ammount = pData.abilityData.onDamage(event.source, event.ammount);
if (pData.abilityData.isCurrentAbilityInvulnerable()) {
event.ammount = 0;
cancel = true;
} else {
event.ammount = pData.abilityData.onDamage(event.source, event.ammount);
}
}
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving);
@@ -4,6 +4,8 @@ import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSoundOperation;
import kamkeel.npcs.network.enums.EnumSyncAction;
@@ -30,7 +32,6 @@ import net.minecraft.util.MathHelper;
import net.minecraft.util.StatCollector;
import net.minecraft.village.MerchantRecipeList;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEvent;
@@ -153,13 +154,13 @@ public class ServerEventsHandler {
}
@SubscribeEvent
public void barrierDamageProtection(LivingAttackEvent event) {
public void barrierAbsorbDamage(LivingAttackEvent event) {
if (event.entityLiving == null || event.entityLiving.worldObj == null || event.entityLiving.worldObj.isRemote)
return;
EntityEnergyBarrier barrier = EntityEnergyBarrier.getProtectingBarrier(event.entityLiving);
if (barrier != null && barrier.isDamageFromOutside(event.source)) {
// Redirect the damage to the barrier instead of preventing it
EntityAbilityBarrier barrier = EntityAbilityBarrier.getAbsorbingBarrier(event.entityLiving);
if (barrier != null) {
// Redirect the caster's damage to their barrier
barrier.absorbDamage(event.ammount);
event.setCanceled(true);
}
@@ -189,9 +190,9 @@ public class ServerEventsHandler {
}
if (!blacklisted) return;
List<EntityEnergyBarrier> barriers = EntityEnergyBarrier.getActiveBarriers(player.worldObj);
for (EntityEnergyBarrier barrier : barriers) {
if (barrier instanceof kamkeel.npcs.entity.EntityEnergyDome && barrier.isEntityInside(player)) {
List<EntityAbilityBarrier> barriers = EntityAbilityBarrier.getActiveBarriers(player.worldObj);
for (EntityAbilityBarrier barrier : barriers) {
if (barrier instanceof EntityAbilityDome && barrier.isEntityInside(player)) {
event.setCanceled(true);
return;
}
@@ -529,7 +530,7 @@ public class ServerEventsHandler {
@SubscribeEvent
public void populateChunk(PopulateChunkEvent.Post event) {
NPCSpawning.performWorldGenSpawning(event.world, event.chunkX, event.chunkZ, event.rand);
NPCSpawning.performWorldGenSpawning(event.world, event.chunkX << 4, event.chunkZ << 4, event.rand);
}
@SubscribeEvent
@@ -25,6 +25,9 @@ import java.util.Map;
import java.util.Set;
public class FlyPathFinder extends PathFinder {
private static final float STRAIGHT_COST = 1.0F;
private static final float DIAGONAL_2D_COST = 1.4142135F;
private static final float DIAGONAL_3D_COST = 1.7320508F;
/**
* Used to find obstacles
*/
@@ -141,7 +144,7 @@ public class FlyPathFinder extends PathFinder {
private NPCPath addToPath(Entity p_75861_1_, NPCPathPoint p_75861_2_, NPCPathPoint p_75861_3_, NPCPathPoint p_75861_4_, float p_75861_5_) {
p_75861_2_.totalPathDistance = 0.0F;
p_75861_2_.distanceToNext = p_75861_2_.distanceToSquared(p_75861_3_);
p_75861_2_.distanceToNext = this.estimateCostToTarget(p_75861_2_, p_75861_3_);
p_75861_2_.distanceToTarget = p_75861_2_.distanceToNext;
this.path.clearPath();
this.path.addPoint(p_75861_2_);
@@ -161,7 +164,7 @@ public class FlyPathFinder extends PathFinder {
return this.createEntityPath(p_75861_2_, p_75861_3_);
}
if (pathpoint4.distanceToSquared(p_75861_3_) < pathpoint3.distanceToSquared(p_75861_3_)) {
if (this.estimateCostToTarget(pathpoint4, p_75861_3_) < this.estimateCostToTarget(pathpoint3, p_75861_3_)) {
pathpoint3 = pathpoint4;
}
@@ -170,12 +173,13 @@ public class FlyPathFinder extends PathFinder {
for (int j = 0; j < i; ++j) {
NPCPathPoint pathpoint5 = this.pathOptions[j];
float f1 = pathpoint4.totalPathDistance + pathpoint4.distanceToSquared(pathpoint5);
float f1 = pathpoint4.totalPathDistance + this.getTraversalCost(pathpoint4, pathpoint5)
+ this.getDirectionalPenalty(pathpoint4, pathpoint5, p_75861_3_);
if (!pathpoint5.isAssigned() || f1 < pathpoint5.totalPathDistance) {
pathpoint5.previous = pathpoint4;
pathpoint5.totalPathDistance = f1;
pathpoint5.distanceToNext = pathpoint5.distanceToSquared(p_75861_3_);
pathpoint5.distanceToNext = this.estimateCostToTarget(pathpoint5, p_75861_3_);
if (pathpoint5.isAssigned()) {
this.path.changeDistance(pathpoint5, pathpoint5.totalPathDistance + pathpoint5.distanceToNext);
@@ -194,6 +198,50 @@ public class FlyPathFinder extends PathFinder {
}
}
private float getTraversalCost(NPCPathPoint from, NPCPathPoint to) {
int dx = Math.abs(to.xCoord - from.xCoord);
int dy = Math.abs(to.yCoord - from.yCoord);
int dz = Math.abs(to.zCoord - from.zCoord);
int changedAxes = dx + dy + dz;
if (changedAxes <= 1) {
return STRAIGHT_COST;
}
if (changedAxes == 2) {
return DIAGONAL_2D_COST;
}
return DIAGONAL_3D_COST;
}
private float getDirectionalPenalty(NPCPathPoint from, NPCPathPoint to, NPCPathPoint goal) {
int stepX = to.xCoord - from.xCoord;
int stepY = to.yCoord - from.yCoord;
int stepZ = to.zCoord - from.zCoord;
int goalX = goal.xCoord - from.xCoord;
int goalY = goal.yCoord - from.yCoord;
int goalZ = goal.zCoord - from.zCoord;
int stepLen = Math.abs(stepX) + Math.abs(stepY) + Math.abs(stepZ);
int goalLen = Math.abs(goalX) + Math.abs(goalY) + Math.abs(goalZ);
if (stepLen == 0 || goalLen == 0) {
return 0.0F;
}
float alignment = (float) (stepX * goalX + stepY * goalY + stepZ * goalZ) / (float) (stepLen * goalLen);
return (1.0F - alignment) * 0.04F;
}
private float estimateCostToTarget(NPCPathPoint from, NPCPathPoint to) {
float dx = Math.abs(to.xCoord - from.xCoord);
float dy = Math.abs(to.yCoord - from.yCoord);
float dz = Math.abs(to.zCoord - from.zCoord);
float max = Math.max(dx, Math.max(dy, dz));
float min = Math.min(dx, Math.min(dy, dz));
float mid = dx + dy + dz - max - min;
return DIAGONAL_3D_COST * min + DIAGONAL_2D_COST * (mid - min) + STRAIGHT_COST * (max - mid);
}
/**
* populates pathOptions with available points and returns the number of options found (args: unused1, currentPoint,
* unused2, targetPoint, maxDistance)
@@ -7,6 +7,8 @@ import noppes.npcs.entity.EntityNPCFlying;
import noppes.npcs.entity.EntityNPCInterface;
public class FlyingMoveHelper extends EntityMoveHelper {
private static final double CLOSE_ENOUGH_SQ = 0.01D;
private static final float MAX_TURN_PER_TICK = 35.0F;
private final EntityNPCInterface entity;
private double posX;
@@ -38,22 +40,24 @@ public class FlyingMoveHelper extends EntityMoveHelper {
double d5 = MathHelper.sqrt_double(d4);
speed = Math.min(d5 / 5.0D, speed);
// its here louis!
// This is the hurt time that stuns the NPC!!!!!!
// if (this.entity.hurtTime == 0 && d4 > 0.5D) {
if (d4 >= 0.5D) {
this.entity.motionX += (speed * (d0 / d5) - this.entity.motionX) * speed;
this.entity.motionZ += (speed * (d2 / d5) - this.entity.motionZ) * speed;
if (d4 > CLOSE_ENOUGH_SQ && d5 > 1.0E-4D) {
double targetMotionX = speed * (d0 / d5);
double targetMotionZ = speed * (d2 / d5);
double horizontalLerp = Math.min(1.0D, Math.max(0.12D, speed * 0.6D));
this.entity.motionX += (targetMotionX - this.entity.motionX) * horizontalLerp;
this.entity.motionZ += (targetMotionZ - this.entity.motionZ) * horizontalLerp;
if (((EntityNPCFlying) this.entity).flyLimitAllow || !this.entity.ais.hasFlyLimit) {
this.entity.motionY = verticalSpeed * (d1 / d5);
if (this.entity.motionY > 0) {
this.entity.motionY += 0.1D;
double targetMotionY = verticalSpeed * (d1 / d5);
if (targetMotionY > 0.0D) {
targetMotionY += 0.05D;
}
double verticalLerp = Math.min(1.0D, Math.max(0.15D, verticalSpeed * 0.85D));
this.entity.motionY += (targetMotionY - this.entity.motionY) * verticalLerp;
}
this.entity.velocityChanged = true;
this.entity.rotationYaw = this.limitAngle(this.entity.rotationYaw, (float) ((Math.atan2(-d0, -d2) + Math.PI) * -(180F / Math.PI)), 20.0F);
this.entity.rotationYaw = this.limitAngle(this.entity.rotationYaw, (float) ((Math.atan2(-d0, -d2) + Math.PI) * -(180F / Math.PI)), MAX_TURN_PER_TICK);
}
}
}
@@ -21,6 +21,10 @@ import noppes.npcs.entity.EntityNPCInterface;
import javax.annotation.Nullable;
public class PathNavigateFlying extends PathNavigate {
private static final long MIN_REPATH_INTERVAL_TICKS = 8L;
private static final long MAX_REPATH_INTERVAL_TICKS = 30L;
private static final int PATH_REUSE_TARGET_DELTA_SQ = 2;
private static final int FINAL_NODE_REUSE_DELTA_SQ = 3;
private EntityNPCInterface theEntity;
private World worldObj;
@@ -83,16 +87,21 @@ public class PathNavigateFlying extends PathNavigate {
}
public void updatePath() {
if (this.worldObj.getTotalWorldTime() - this.lastTimeUpdated > 20L) {
if (this.targetPos != null) {
this.currentPath = null;
this.currentPath = this.getPathToXYZ(this.targetPos.getX(), this.targetPos.getY(), this.targetPos.getZ());
this.lastTimeUpdated = this.worldObj.getTotalWorldTime();
this.tryUpdatePath = false;
}
} else {
this.tryUpdatePath = true;
if (this.targetPos == null) {
this.tryUpdatePath = false;
return;
}
long now = this.worldObj.getTotalWorldTime();
if (now - this.lastTimeUpdated < this.getAdaptiveRepathInterval()) {
this.tryUpdatePath = true;
return;
}
this.currentPath = null;
this.currentPath = this.getPathToXYZ(this.targetPos.getX(), this.targetPos.getY(), this.targetPos.getZ());
this.lastTimeUpdated = now;
this.tryUpdatePath = false;
}
public void setAvoidsWater(boolean p_75491_1_) {
@@ -156,7 +165,8 @@ public class PathNavigateFlying extends PathNavigate {
BlockPos pos = new BlockPos(x, y, z);
if (!this.canNavigate()) {
return null;
} else if (this.currentPath != null && !this.currentPath.isFinished() && pos.equals(this.targetPos)) {
} else if (this.canReuseCurrentPath(pos)) {
this.targetPos = pos;
return this.currentPath;
} else {
this.targetPos = pos;
@@ -180,7 +190,8 @@ public class PathNavigateFlying extends PathNavigate {
return null;
} else {
BlockPos blockpos = new BlockPos(entity);
if (this.currentPath != null && !this.currentPath.isFinished() && blockpos.equals(this.targetPos)) {
if (this.canReuseCurrentPath(blockpos)) {
this.targetPos = blockpos;
return this.currentPath;
} else {
this.targetPos = blockpos;
@@ -215,6 +226,8 @@ public class PathNavigateFlying extends PathNavigate {
this.removeSunnyPath();
}
this.smoothCurrentPath();
if (this.currentPath.getCurrentPathLength() == 0) {
return false;
} else {
@@ -242,6 +255,72 @@ public class PathNavigateFlying extends PathNavigate {
return !this.isInLiquid() || (this.canSwim && this.isInLiquid());
}
private long getAdaptiveRepathInterval() {
if (this.targetPos == null) {
return MAX_REPATH_INTERVAL_TICKS;
}
double distance = this.theEntity.getDistance(this.targetPos.getX() + 0.5D, this.targetPos.getY(), this.targetPos.getZ() + 0.5D);
return (long) MathHelper.clamp_double(distance * 0.6D, MIN_REPATH_INTERVAL_TICKS, MAX_REPATH_INTERVAL_TICKS);
}
private boolean canReuseCurrentPath(BlockPos newTarget) {
if (this.currentPath == null || this.currentPath.isFinished() || this.targetPos == null) {
return false;
}
if (this.getBlockDistanceSq(this.targetPos, newTarget) <= PATH_REUSE_TARGET_DELTA_SQ) {
return true;
}
NPCPathPoint finalPoint = this.currentPath.getFinalPathPoint();
return finalPoint != null && this.getPointDistanceSq(finalPoint, newTarget) <= FINAL_NODE_REUSE_DELTA_SQ;
}
private int getBlockDistanceSq(BlockPos a, BlockPos b) {
int dx = a.getX() - b.getX();
int dy = a.getY() - b.getY();
int dz = a.getZ() - b.getZ();
return dx * dx + dy * dy + dz * dz;
}
private int getPointDistanceSq(NPCPathPoint point, BlockPos blockPos) {
int dx = point.xCoord - blockPos.getX();
int dy = point.yCoord - blockPos.getY();
int dz = point.zCoord - blockPos.getZ();
return dx * dx + dy * dy + dz * dz;
}
private void smoothCurrentPath() {
if (this.currentPath == null) {
return;
}
int pathLength = this.currentPath.getCurrentPathLength();
if (pathLength < 3) {
return;
}
int width = MathHelper.ceiling_double_int(this.theEntity.width);
int height = MathHelper.ceiling_double_int(this.theEntity.height + 1.0F);
NPCPathPoint[] points = this.currentPath.points;
int writeIndex = 1;
int anchorIndex = 0;
for (int readIndex = 2; readIndex < pathLength; readIndex++) {
Vec3 anchor = this.currentPath.getVectorFromIndex(this.theEntity, anchorIndex);
Vec3 probe = this.currentPath.getVectorFromIndex(this.theEntity, readIndex);
if (!this.isDirectPathBetweenPoints(anchor, probe, width, height)) {
points[writeIndex++] = points[readIndex - 1];
anchorIndex = readIndex - 1;
}
}
points[writeIndex++] = points[pathLength - 1];
this.currentPath.setCurrentPathLength(writeIndex);
if (this.currentPath.getCurrentPathIndex() >= writeIndex) {
this.currentPath.setCurrentPathIndex(Math.max(0, writeIndex - 1));
}
}
public void onUpdateNavigation() {
++this.totalTicks;
@@ -16,6 +16,7 @@ public class ClientAbilityState {
public static boolean hasAbilityMovement = false;
public static boolean positionLocked = false;
public static boolean wasFlyingAtLock = false;
public static boolean activePhase = false;
public static float lockedYaw = 0;
public static float lockedPitch = 0;
@@ -28,6 +29,7 @@ public class ClientAbilityState {
hasAbilityMovement = (flags & PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT) != 0;
positionLocked = (flags & PlayerAbilityStatePacket.FLAG_POSITION_LOCKED) != 0;
wasFlyingAtLock = (flags & PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK) != 0;
activePhase = (flags & PlayerAbilityStatePacket.FLAG_ACTIVE_PHASE) != 0;
lockedYaw = yaw;
lockedPitch = pitch;
}
@@ -56,6 +58,7 @@ public class ClientAbilityState {
hasAbilityMovement = false;
positionLocked = false;
wasFlyingAtLock = false;
activePhase = false;
lockedYaw = 0;
lockedPitch = 0;
}
@@ -102,7 +102,17 @@ public class ClientEventHandler {
// Ability Hotbar: Hold HUD key + scroll wheel to cycle
if (event.dwheel != 0 && ClientProxy.AbilityHudKey != null) {
int hudKeyCode = ClientProxy.AbilityHudKey.getKeyCode();
if (hudKeyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode)) {
boolean hudKeyHeld = false;
if (hudKeyCode > 0) {
hudKeyHeld = hudKeyCode < org.lwjgl.input.Keyboard.getKeyCount()
&& org.lwjgl.input.Keyboard.isKeyDown(hudKeyCode);
} else if (hudKeyCode < 0) {
int mouseButton = hudKeyCode + 100;
hudKeyHeld = mouseButton >= 0
&& mouseButton < org.lwjgl.input.Mouse.getButtonCount()
&& org.lwjgl.input.Mouse.isButtonDown(mouseButton);
}
if (hudKeyHeld) {
AbilityHotbarComponent comp = (AbilityHotbarComponent) ClientHudManager.getInstance()
.getHudComponents().get(EnumHudComponent.AbilityHotbar);
if (comp != null && comp.hasAnyAbilities()) {
@@ -12,11 +12,14 @@ import kamkeel.npcs.client.renderer.RenderAbilityLaser;
import kamkeel.npcs.client.renderer.RenderAbilityOrb;
import kamkeel.npcs.client.renderer.RenderAbilitySweeper;
import kamkeel.npcs.client.renderer.RenderAbilityZone;
import kamkeel.npcs.client.renderer.RenderEnergyDome;
import kamkeel.npcs.client.renderer.RenderEnergyPanel;
import kamkeel.npcs.client.renderer.RenderAbilityDome;
import kamkeel.npcs.client.renderer.RenderAbilityPanel;
import kamkeel.npcs.client.renderer.EnergyChargePreviewRenderer;
import kamkeel.npcs.client.renderer.RenderEnergyExplosion;
import kamkeel.npcs.client.renderer.RenderEnergySlicer;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.client.renderer.lightning.LightningHandler;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
@@ -24,8 +27,9 @@ import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
@@ -278,9 +282,10 @@ public class ClientProxy extends CommonProxy {
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyDome.class, new RenderEnergyDome());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyPanel.class, new RenderEnergyPanel());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDome.class, new RenderAbilityDome());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityPanel.class, new RenderAbilityPanel());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergySlicer.class, new RenderEnergySlicer());
RenderingRegistry.registerEntityRenderingHandler(EntityEnergyExplosion.class, new RenderEnergyExplosion());
RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc());
@@ -356,6 +361,10 @@ public class ClientProxy extends CommonProxy {
TelegraphManager.initClient();
MinecraftForge.EVENT_BUS.register(new TelegraphRenderer());
// Energy charge preview rendering system
EnergyChargePreviewManager.initClient();
MinecraftForge.EVENT_BUS.register(new EnergyChargePreviewRenderer());
// Lightning effect rendering system
MinecraftForge.EVENT_BUS.register(new LightningHandler());
@@ -7,7 +7,7 @@ import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.relauncher.Side;
import kamkeel.npcs.client.renderer.lightning.LightningBolt;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
@@ -53,6 +53,7 @@ public class ClientTickHandler {
private long buttonTime = 0L;
private final int[] ignoreKeys = new int[]{157, 29, 54, 42, 184, 56, 220, 219};
private boolean lastSpecialKeyDown = false;
private boolean wasMovementSuppressed = false;
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onClientTick(TickEvent.ClientTickEvent event) {
@@ -62,6 +63,9 @@ public class ClientTickHandler {
ClientCacheHandler.clearCache();
ClientAbilityState.reset();
RequestProperSpawnData.clear();
if (EnergyChargePreviewManager.ClientInstance != null) {
EnergyChargePreviewManager.ClientInstance.clear();
}
}
this.prevWorld = mc.theWorld;
}
@@ -80,9 +84,15 @@ public class ClientTickHandler {
lastSpecialKeyDown = specialKeyDown;
}
boolean suppressMovement = mc.currentScreen == null && ClientAbilityState.shouldSuppressMovementInput();
if (!suppressMovement && wasMovementSuppressed) {
syncMovementKeyStates(mc);
}
wasMovementSuppressed = suppressMovement;
// Suppress player input during ability-controlled phases.
// Only suppress when no GUI screen is open (screens already capture input).
if (mc.currentScreen == null && ClientAbilityState.shouldSuppressMovementInput()) {
if (suppressMovement) {
// Unpress movement keybinds at the source BEFORE updatePlayerMoveState() reads them.
KeyBinding.setKeyBindState(mc.gameSettings.keyBindForward.getKeyCode(), false);
KeyBinding.setKeyBindState(mc.gameSettings.keyBindBack.getKeyCode(), false);
@@ -164,6 +174,11 @@ public class ClientTickHandler {
TelegraphManager.ClientInstance.tick(mc.theWorld);
}
// Tick packet-driven energy charge previews
if (EnergyChargePreviewManager.ClientInstance != null) {
EnergyChargePreviewManager.ClientInstance.tick(mc.theWorld);
}
// Update lightning bolts for ability effects
LightningBolt.updateAll();
@@ -292,6 +307,27 @@ public class ClientTickHandler {
|| keyCode == mc.gameSettings.keyBindSprint.getKeyCode();
}
private void syncMovementKeyStates(Minecraft mc) {
syncKeyBindingState(mc.gameSettings.keyBindForward);
syncKeyBindingState(mc.gameSettings.keyBindBack);
syncKeyBindingState(mc.gameSettings.keyBindLeft);
syncKeyBindingState(mc.gameSettings.keyBindRight);
syncKeyBindingState(mc.gameSettings.keyBindJump);
syncKeyBindingState(mc.gameSettings.keyBindSneak);
syncKeyBindingState(mc.gameSettings.keyBindSprint);
}
private void syncKeyBindingState(KeyBinding keyBinding) {
int keyCode = keyBinding.getKeyCode();
boolean pressed;
if (keyCode < 0) {
pressed = Mouse.isButtonDown(keyCode + 100);
} else {
pressed = Keyboard.isKeyDown(keyCode);
}
KeyBinding.setKeyBindState(keyCode, pressed);
}
private boolean isIgnoredKey(int key) {
int[] var2 = this.ignoreKeys;
int var3 = var2.length;
@@ -127,7 +127,7 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
int iconWidth = effect.getWidth();
int iconHeight = effect.getHeight();
int width = data.getTotalWidth();
int height = data.getTotalWidth();
int height = data.getTotalHeight();
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
@@ -5,6 +5,7 @@ import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScrollWindow;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.SpawnData;
@@ -15,37 +16,97 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
public SubGuiSpawningOptions(SpawnData data) {
this.data = data;
setBackground("menubg.png");
xSize = 216;
xSize = 256;
ySize = 216;
closeOnEsc = true;
}
public void initGui() {
super.initGui();
int y = guiTop - 15;
int scrollX = guiLeft + 4;
int scrollY = guiTop + 4;
int scrollW = xSize - 8;
int scrollH = ySize - 34;
addButton(new GuiNpcButtonYesNo(10, guiLeft + 120, y += 22, data.animalSpawning));
addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", guiLeft + 4, y + 5));
GuiScrollWindow sw = new GuiScrollWindow(this, scrollX, scrollY, scrollW, scrollH, 0);
sw.drawDefaultBackground = false;
addScrollableGui(0, sw);
addButton(new GuiNpcButtonYesNo(11, guiLeft + 120, y += 22, data.monsterSpawning));
addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", guiLeft + 4, y + 5));
int labelX = 4;
int controlX = 132;
int y = 6;
addButton(new GuiNpcButtonYesNo(12, guiLeft + 120, y += 22, data.liquidSpawning));
addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", guiLeft + 4, y + 5));
sw.addButton(new GuiNpcButtonYesNo(10, controlX, y, data.animalSpawning));
sw.addLabel(new GuiNpcLabel(10, "spawning.animalSpawning", labelX, y + 5));
sw.getButton(10).setHoverText("tooltip.naturalspawns.options.animal");
y += 22;
addButton(new GuiNpcButtonYesNo(13, guiLeft + 120, y += 22, data.airSpawning));
addLabel(new GuiNpcLabel(13, "spawning.airSpawning", guiLeft + 4, y + 5));
sw.addButton(new GuiNpcButtonYesNo(11, controlX, y, data.monsterSpawning));
sw.addLabel(new GuiNpcLabel(11, "spawning.monsterSpawning", labelX, y + 5));
sw.getButton(11).setHoverText("tooltip.naturalspawns.options.monster");
y += 22;
addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMin));
addLabel(new GuiNpcLabel(14, "spawning.minHeight", guiLeft + 4, y + 5));
addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 22, 40, 20, "" + data.spawnHeightMax));
addLabel(new GuiNpcLabel(15, "spawning.maxHeight", guiLeft + 4, y + 5));
getTextField(14).integersOnly = true;
getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(15).integersOnly = true;
getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.addButton(new GuiNpcButtonYesNo(12, controlX, y, data.liquidSpawning));
sw.addLabel(new GuiNpcLabel(12, "spawning.liquidSpawning", labelX, y + 5));
sw.getButton(12).setHoverText("tooltip.naturalspawns.options.liquid");
y += 22;
addButton(new GuiNpcButton(100, guiLeft + 154, guiTop + 192, 60, 20, "gui.done"));
sw.addButton(new GuiNpcButtonYesNo(13, controlX, y, data.airSpawning));
sw.addLabel(new GuiNpcLabel(13, "spawning.airSpawning", labelX, y + 5));
sw.getButton(13).setHoverText("tooltip.naturalspawns.options.air");
y += 22;
sw.addTextField(new GuiNpcTextField(14, this, controlX, y, 60, 20, "" + data.spawnHeightMin));
sw.addLabel(new GuiNpcLabel(14, "spawning.minHeight", labelX, y + 5));
sw.getTextField(14).integersOnly = true;
sw.getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.getTextField(14).setHoverText("tooltip.naturalspawns.options.minHeight");
y += 22;
sw.addTextField(new GuiNpcTextField(15, this, controlX, y, 60, 20, "" + data.spawnHeightMax));
sw.addLabel(new GuiNpcLabel(15, "spawning.maxHeight", labelX, y + 5));
sw.getTextField(15).integersOnly = true;
sw.getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
sw.getTextField(15).setHoverText("tooltip.naturalspawns.options.maxHeight");
y += 22;
sw.addTextField(new GuiNpcTextField(16, this, controlX, y, 60, 20, "" + data.maxAlive));
sw.addLabel(new GuiNpcLabel(16, "spawning.maxAlive", labelX, y + 5));
sw.getTextField(16).integersOnly = true;
sw.getTextField(16).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.getTextField(16).setHoverText("tooltip.naturalspawns.options.maxAlive");
y += 22;
sw.addTextField(new GuiNpcTextField(17, this, controlX, y, 60, 20, "" + data.cooldownTicks));
sw.addLabel(new GuiNpcLabel(17, "spawning.cooldownTicks", labelX, y + 5));
sw.getTextField(17).integersOnly = true;
sw.getTextField(17).setMinMaxDefault(0, Integer.MAX_VALUE, 0);
sw.getTextField(17).setHoverText("tooltip.naturalspawns.options.cooldownTicks");
y += 22;
sw.addTextField(new GuiNpcTextField(18, this, controlX, y, 60, 20, "" + data.attemptsPerCycle));
sw.addLabel(new GuiNpcLabel(18, "spawning.attemptsPerCycle", labelX, y + 5));
sw.getTextField(18).integersOnly = true;
sw.getTextField(18).setMinMaxDefault(1, Integer.MAX_VALUE, 1);
sw.getTextField(18).setHoverText("tooltip.naturalspawns.options.attemptsPerCycle");
y += 22;
sw.addTextField(new GuiNpcTextField(19, this, controlX, y, 60, 20, "" + data.playerMinDistance));
sw.addLabel(new GuiNpcLabel(19, "spawning.playerMinDistance", labelX, y + 5));
sw.getTextField(19).integersOnly = true;
sw.getTextField(19).setMinMaxDefault(0, Integer.MAX_VALUE, 24);
sw.getTextField(19).setHoverText("tooltip.naturalspawns.options.playerMinDistance");
y += 22;
sw.addButton(new GuiNpcButton(20, controlX, y, 100, 20,
new String[]{"spawning.despawn.forceNatural", "spawning.despawn.preserve", "spawning.despawn.forcePersistent"}, data.despawnMode));
sw.addLabel(new GuiNpcLabel(20, "spawning.despawnMode", labelX, y + 5));
sw.getButton(20).setHoverText("tooltip.naturalspawns.options.despawnMode");
y += 22;
sw.maxScrollY = Math.max(0, y - sw.clipHeight + 8);
addButton(new GuiNpcButton(100, guiLeft + xSize - 64, guiTop + ySize - 24, 60, 20, "gui.done"));
}
@Override
@@ -64,6 +125,9 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
if (button.id == 13) {
data.airSpawning = button.getValue() == 1;
}
if (button.id == 20) {
data.setDespawnMode(button.getValue());
}
if (button.id == 100) {
close();
}
@@ -77,5 +141,17 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
if (textfield.id == 15) {
data.spawnHeightMax = textfield.getInteger();
}
if (textfield.id == 16) {
data.setMaxAlive(textfield.getInteger());
}
if (textfield.id == 17) {
data.setCooldownTicks(textfield.getInteger());
}
if (textfield.id == 18) {
data.setAttemptsPerCycle(textfield.getInteger());
}
if (textfield.id == 19) {
data.setPlayerMinDistance(textfield.getInteger());
}
}
}
@@ -4,8 +4,8 @@ import kamkeel.npcs.controllers.AbilityController;
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.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket;
import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket;
@@ -20,6 +20,8 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS;
public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener {
private static final int DECLARATIVE_ID_START = 1000;
@@ -42,6 +44,12 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
private static final int L_LABEL_X = 5;
private static final int ROW_H = 24;
// Condition buttons
private static final int COND_BASE = 50;
private static final int COND_STRIDE = 10;
private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10
private static final int BTN_ADD_COND = COND_END;
private final Ability ability;
private final IAbilityConfigCallback callback;
private int activeTab = TAB_GENERAL;
@@ -234,17 +242,19 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55));
y += 15;
for (int i = 0; i < conditions.size() && i < 3; i++) {
for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) {
AbilityCondition cond = conditions.get(i);
String condName = getConditionDisplayName(cond);
sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName));
sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit"));
sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X"));
GuiNpcButton condBtn = new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName);
condBtn.hoverableText = cond.getConditionSummary();
sw.addButton(condBtn);
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 1, L_LABEL_X + 145, y, 40, 20, "gui.edit"));
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE + 2, L_LABEL_X + 190, y, 20, 20, "X"));
y += 22;
}
if (conditions.size() < 3) {
sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add"));
if (conditions.size() < MAX_CONDITIONS) {
sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));;
y += ROW_H;
}
@@ -312,9 +322,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
}
private boolean handleConditionButton(int id) {
if (id >= 50 && id < 80) {
int condIndex = (id - 50) / 10;
int action = (id - 50) % 10;
if (id >= COND_BASE && id < COND_END) {
int condIndex = (id - COND_BASE) / COND_STRIDE;
int action = (id - COND_BASE) % COND_STRIDE;
if (action == 0 || action == 1) {
if (condIndex < conditions.size()) {
editingConditionIndex = condIndex;
@@ -328,8 +338,8 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
}
return true;
}
if (id == 80) {
if (conditions.size() < 3) {
if (id == BTN_ADD_COND) {
if (conditions.size() < MAX_CONDITIONS) {
editingConditionIndex = conditions.size();
setSubGui(new SubGuiConditionEdit(null));
}
@@ -84,8 +84,12 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGui
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiDuplicateNameConfirm) {
if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) {
SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui;
if (confirm.isConfirmed()) {
doSave();
} else if (confirm.isBack()) {
// Keep this save-confirm dialog open.
return;
} else {
close();
}
@@ -4,11 +4,11 @@ import kamkeel.npcs.controllers.AbilityController;
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.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.IChainedAbilityFieldProvider;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
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;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket;
@@ -32,6 +32,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS;
/**
* SubGui for editing a {@link ChainedAbility}.
@@ -70,9 +71,9 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
// Actual ID = COND_BASE + i * COND_STRIDE + offset
// offset 0 = name/click, 1 = edit, 2 = delete
private static final int COND_BASE = 50;
private static final int COND_END = 80;
private static final int COND_STRIDE = 10;
private static final int BTN_ADD_COND = 80;
private static final int COND_END = COND_BASE + MAX_CONDITIONS * COND_STRIDE; // 50 + N*10
private static final int BTN_ADD_COND = COND_END;
// ── Layout constants ──────────────────────────────────────────────────────
private static final int L_LABEL_X = 5;
@@ -427,7 +428,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55));
y += 15;
for (int i = 0; i < conditions.size() && i < 3; i++) {
for (int i = 0; i < conditions.size() && i < MAX_CONDITIONS; i++) {
AbilityCondition cond = conditions.get(i);
String condName = getConditionDisplayName(cond);
sw.addButton(new GuiNpcButton(COND_BASE + i * COND_STRIDE, L_LABEL_X, y, 140, 20, condName));
@@ -436,7 +437,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
y += 22;
}
if (conditions.size() < 3) {
if (conditions.size() < MAX_CONDITIONS) {
sw.addButton(new GuiNpcButton(BTN_ADD_COND, L_LABEL_X, y, 50, 20, "gui.add"));
y += ROW_H;
}
@@ -562,6 +563,8 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
return true;
case 2: // Up
if (entryIndex > 0) {
// Commit any focused delay field before reordering
GuiNpcTextField.unfocus();
ChainedAbilityEntry entry = entries.remove(entryIndex);
entries.add(entryIndex - 1, entry);
// Can't be concurrent at position 0
@@ -573,12 +576,16 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
return true;
case 3: // Down
if (entryIndex < entries.size() - 1) {
// Commit any focused delay field before reordering
GuiNpcTextField.unfocus();
ChainedAbilityEntry entry = entries.remove(entryIndex);
entries.add(entryIndex + 1, entry);
initGui();
}
return true;
case 4: // Delete
// Commit any focused delay field before removing
GuiNpcTextField.unfocus();
entries.remove(entryIndex);
initGui();
return true;
@@ -615,7 +622,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
return true;
}
if (id == BTN_ADD_COND) {
if (conditions.size() < 3) {
if (conditions.size() < MAX_CONDITIONS) {
editingConditionIndex = conditions.size();
setSubGui(new SubGuiConditionEdit(null));
}
@@ -2,12 +2,15 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.util.Register;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.*;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
@@ -15,59 +18,141 @@ import java.util.function.Supplier;
/**
* SubGui for editing a single AbilityCondition.
*
* Type selection stays manual (we need to swap the condition object).
* Field rendering is fully delegated to AbilityCondition#getAbilityDefinitions(),
* mirroring the pattern used in SubGuiAbilityConfig.
* Split-panel layout:
* Left – Mod namespace filter + scrollable condition type list
* Right – FieldDef configuration for the selected condition
*/
public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener {
public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldListener, ISubGuiListener, ICustomScrollListener {
private static final int DECLARATIVE_ID_START = 1000;
private static final int CLEAR_ID_START = 2000;
private static final int LABEL_ID_START = 3000;
private static final int BTN_TYPE = 1;
private static final int BTN_NAMESPACE = 1;
private static final int BTN_CANCEL = 10;
private static final int BTN_DONE = 11;
private static final int TF_SEARCH = 12;
// Left panel
private static final int LEFT_WIDTH = 110;
private static final int LEFT_MARGIN = 5;
// Right panel
private static final int RIGHT_GAP = 5;
private String searchText = "";
private AbilityCondition condition;
private AbilityCondition result;
private String selectedTypeId;
private final String[] conditionTypeIds;
private final String[] conditionTypeNames;
private int selectedTypeIndex = 0;
// Namespace filter
private int namespaceFilter = 0; // 0 = ALL, 1 = cnpc, 2+ = modded namespaces
private List<String> modNamespaces;
// Type list
private GuiCustomScroll scroll;
private final HashMap<String, String> displayNameToTypeId = new HashMap<>();
private String[] filteredTypeIds;
private AbilityFieldBuilder builder;
public SubGuiConditionEdit(AbilityCondition existing) {
this.result = null;
conditionTypeIds = AbilityController.Instance.getConditionTypes();
conditionTypeNames = new String[conditionTypeIds.length];
for (int i = 0; i < conditionTypeIds.length; i++) {
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(conditionTypeIds[i]);
conditionTypeNames[i] = factory != null ? factory.get().getName() : conditionTypeIds[i];
}
this.modNamespaces = getModNamespaces();
if (existing != null) {
for (int i = 0; i < conditionTypeIds.length; i++) {
if (conditionTypeIds[i].equals(existing.getTypeId())) {
selectedTypeIndex = i;
break;
}
}
this.condition = existing;
this.selectedTypeId = existing.getTypeId();
// Set namespace filter to match existing condition
setNamespaceForTypeId(selectedTypeId);
} else {
this.condition = spawnCondition(selectedTypeIndex);
// Default to first available condition
String[] allTypes = AbilityController.Instance.getConditionTypes();
if (allTypes.length > 0) {
this.selectedTypeId = allTypes[0];
this.condition = spawnCondition(selectedTypeId);
}
}
setBackground("menubg.png");
xSize = 240;
ySize = 180;
setBackground("menubg.png", 217);
xSize = 356;
ySize = 200;
}
private AbilityCondition spawnCondition(int typeIndex) {
if (typeIndex < 0 || typeIndex >= conditionTypeIds.length) return null;
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(conditionTypeIds[typeIndex]);
private List<String> getModNamespaces() {
List<String> result = new ArrayList<>();
List<String> registered = Register.REGISTERED_NAMESPACES.get("condition");
if (registered != null) {
result.addAll(registered);
}
return result;
}
private void setNamespaceForTypeId(String typeId) {
if (typeId == null) return;
String[] parts = typeId.split("\\.", 3);
if (parts.length < 2) return;
String ns = parts[1];
if ("cnpc".equals(ns)) {
namespaceFilter = 1;
} else {
for (int i = 0; i < modNamespaces.size(); i++) {
if (modNamespaces.get(i).equals(ns)) {
namespaceFilter = 2 + i;
return;
}
}
namespaceFilter = 0; // Fallback to ALL
}
}
private String getNamespaceFilterLabel() {
if (namespaceFilter == 0) return "ALL";
if (namespaceFilter == 1) return "CNPC";
int modIdx = namespaceFilter - 2;
if (modIdx >= 0 && modIdx < modNamespaces.size()) {
String ns = modNamespaces.get(modIdx);
String display = Register.NAMESPACE_DISPLAY_NAMES.get(ns);
return display != null ? display : ns.toUpperCase();
}
return "ALL";
}
private void cycleNamespaceFilter() {
namespaceFilter++;
// 0=ALL, 1=CNPC, 2..2+N-1=mod namespaces, then wrap
int max = 2 + modNamespaces.size();
if (namespaceFilter >= max) {
namespaceFilter = 0;
}
// Skip empty mod namespace slots
if (namespaceFilter >= 2) {
int modIdx = namespaceFilter - 2;
if (modIdx >= modNamespaces.size()) {
namespaceFilter = 0;
}
}
}
private String[] getFilteredTypes() {
if (namespaceFilter == 0) {
return AbilityController.Instance.getConditionTypes();
} else if (namespaceFilter == 1) {
return AbilityController.Instance.getConditionTypesByNamespace("cnpc");
} else {
int modIdx = namespaceFilter - 2;
if (modIdx >= 0 && modIdx < modNamespaces.size()) {
return AbilityController.Instance.getConditionTypesByNamespace(modNamespaces.get(modIdx));
}
return AbilityController.Instance.getConditionTypes();
}
}
private AbilityCondition spawnCondition(String typeId) {
if (typeId == null) return null;
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(typeId);
return factory != null ? factory.get() : null;
}
@@ -76,18 +161,58 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi
GuiNpcTextField.unfocus();
super.initGui();
int swX = guiLeft + 4;
int swY = guiTop + 5;
int swW = xSize - 8;
int swH = ySize - 35;
int leftX = guiLeft + LEFT_MARGIN;
int btnY = guiTop + ySize - 26;
int labelY = guiTop + 8;
addLabel(new GuiNpcLabel(0, "gui.type", guiLeft + 8, labelY + 5));
GuiNpcButton typeBtn = new GuiNpcButton(BTN_TYPE, guiLeft + 80, labelY, 155, 20, conditionTypeNames, selectedTypeIndex);
addButton(typeBtn);
// Namespace filter button (above left scroll only)
addButton(new GuiNpcButton(BTN_NAMESPACE, leftX, guiTop + 5, LEFT_WIDTH, 20, getNamespaceFilterLabel()));
swY += 26;
swH -= 26;
// Build filtered type list
filteredTypeIds = getFilteredTypes();
displayNameToTypeId.clear();
List<String> scrollList = new ArrayList<>();
for (String typeId : filteredTypeIds) {
Supplier<AbilityCondition> factory = AbilityController.Instance.getConditionType(typeId);
String displayName = factory != null ? I18n.format(factory.get().getName()) : typeId;
if (!searchText.isEmpty() && !displayName.toLowerCase().contains(searchText.toLowerCase())) continue;
scrollList.add(displayName);
displayNameToTypeId.put(displayName, typeId);
}
// Left panel: condition type scroll list (between namespace button and search bar)
int scrollTop = guiTop + 29;
int scrollBottom = btnY - 24;
int scrollHeight = scrollBottom - scrollTop;
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
}
scroll.guiLeft = leftX;
scroll.guiTop = scrollTop;
scroll.setSize(LEFT_WIDTH, scrollHeight);
scroll.setUnsortedList(scrollList);
// Pre-select current condition type in scroll
if (selectedTypeId != null) {
for (int i = 0; i < scrollList.size(); i++) {
String typeId = displayNameToTypeId.get(scrollList.get(i));
if (typeId != null && typeId.equals(selectedTypeId)) {
scroll.selected = i;
break;
}
}
}
addScroll(scroll);
// Search text field (below left scroll)
GuiNpcTextField searchField = new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, leftX, scrollBottom + 2, LEFT_WIDTH, 20, searchText);
searchField.setHoverText("gui.search");
addTextField(searchField);
// Right panel: condition config via FieldDef (full height from top to buttons)
int rightX = leftX + LEFT_WIDTH + RIGHT_GAP;
int rightW = xSize - LEFT_MARGIN * 2 - LEFT_WIDTH - RIGHT_GAP;
int rightTop = guiTop + 5;
int rightHeight = btnY - rightTop - 4;
List<FieldDef> fields = new ArrayList<>();
if (condition != null) {
@@ -96,25 +221,25 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi
builder = new AbilityFieldBuilder(this, fontRendererObj);
builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, LABEL_ID_START);
builder.contentRight(rightW);
builder.startY(5);
builder.buildScrollWindow(fields, rightX, rightTop, rightW, rightHeight);
builder.buildScrollWindow(fields, swX, swY, swW, swH);
int btnY = guiTop + ySize - 26;
addButton(new GuiNpcButton(BTN_CANCEL, guiLeft + 8, btnY, 60, 20, "gui.cancel"));
addButton(new GuiNpcButton(BTN_DONE, guiLeft + xSize - 68, btnY, 60, 20, "gui.done"));
// Bottom buttons
addButton(new GuiNpcButton(BTN_CANCEL, leftX, btnY, 60, 20, "gui.cancel"));
GuiNpcButton doneBtn = new GuiNpcButton(BTN_DONE, guiLeft + xSize - LEFT_MARGIN - 60, btnY, 60, 20, "gui.done");
if (condition == null || !condition.isConfigured()) {
doneBtn.setEnabled(false);
}
addButton(doneBtn);
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == BTN_TYPE) {
int newIndex = ((GuiNpcButton) guibutton).getValue();
if (newIndex != selectedTypeIndex) {
selectedTypeIndex = newIndex;
condition = spawnCondition(selectedTypeIndex);
}
if (id == BTN_NAMESPACE) {
cycleNamespaceFilter();
initGui();
return;
}
@@ -138,8 +263,34 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0 && scroll.hasSelected()) {
String displayName = scroll.getSelected();
String typeId = displayNameToTypeId.get(displayName);
if (typeId != null && !typeId.equals(selectedTypeId)) {
selectedTypeId = typeId;
condition = spawnCondition(selectedTypeId);
initGui();
}
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) {
// Same as single click — user still needs to configure fields
}
@Override
public void unFocused(GuiNpcTextField textField) {
if (textField.id == TF_SEARCH) {
String newText = textField.getText();
if (!newText.equals(searchText)) {
searchText = newText;
initGui();
}
return;
}
if (textField.id < DECLARATIVE_ID_START) return;
if (builder != null && builder.handleTextFieldEvent(textField.id, textField)) {
initGui();
@@ -10,7 +10,13 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
*/
public class SubGuiDuplicateNameConfirm extends SubGuiInterface {
private boolean confirmed = false;
public enum Result {
CONTINUE,
BACK,
CANCEL
}
private Result result = Result.CANCEL;
public SubGuiDuplicateNameConfirm() {
setBackground("menubg.png");
@@ -26,22 +32,38 @@ public class SubGuiDuplicateNameConfirm extends SubGuiInterface {
addLabel(new GuiNpcLabel(0, "ability.duplicate.name", guiLeft + 10, y));
y += 30;
addButton(new GuiNpcButton(0, guiLeft + 20, y, 80, 20, "gui.continue"));
addButton(new GuiNpcButton(1, guiLeft + 120, y, 80, 20, "gui.cancel"));
addButton(new GuiNpcButton(0, guiLeft + 10, y, 65, 20, "gui.continue"));
addButton(new GuiNpcButton(1, guiLeft + 78, y, 65, 20, "gui.back"));
addButton(new GuiNpcButton(2, guiLeft + 146, y, 65, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
confirmed = true;
result = Result.CONTINUE;
close();
} else if (guibutton.id == 1) {
confirmed = false;
result = Result.BACK;
close();
} else if (guibutton.id == 2) {
result = Result.CANCEL;
close();
}
}
public Result getResult() {
return result;
}
public boolean isConfirmed() {
return confirmed;
return result == Result.CONTINUE;
}
public boolean isBack() {
return result == Result.BACK;
}
public boolean isCancelled() {
return result == Result.CANCEL;
}
}
@@ -118,10 +118,11 @@ public class FieldDef {
return def;
}
public static FieldDef subGuiField(String label, Supplier<SubGuiInterface> factory, Consumer<SubGuiInterface> resultHandler) {
@SuppressWarnings("unchecked")
public static <T> FieldDef subGuiField(String label, Supplier<T> factory, Consumer<T> resultHandler) {
FieldDef def = new FieldDef(label, FieldType.SUB_GUI);
def.subGuiFactory = factory;
def.subGuiResultHandler = resultHandler;
def.subGuiFactory = (Supplier<SubGuiInterface>) (Supplier<?>) factory;
def.subGuiResultHandler = (Consumer<SubGuiInterface>) (Consumer<?>) resultHandler;
return def;
}
@@ -245,6 +245,9 @@ public class GuiFieldBuilder {
case STRING: {
String sVal = def.getValue() != null ? def.getValue().toString() : "";
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, sVal);
if ("gui.name".equals(def.getLabel())) {
tf.setFileNameSafe();
}
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
@@ -344,6 +347,9 @@ public class GuiFieldBuilder {
String translated = StatCollector.translateToLocal(def.getLabel());
int labelW = fontRenderer.getStringWidth(translated);
int fieldX = colLLabel + labelW + labelPadding;
// Clamp field width so it doesn't extend under the scrollbar
int maxW = contentRight - fieldX - 15;
if (maxW > 0 && fieldW > maxW) fieldW = maxW;
renderFieldAt(def, colLLabel, fieldX, fieldW, y);
}
@@ -173,7 +173,7 @@ public class GuiNPCManageEffects extends GuiNPCInterface2 implements ICustomScro
int iconWidth = effect.getWidth();
int iconHeight = effect.getHeight();
int width = data.getTotalWidth();
int height = data.getTotalWidth();
int height = data.getTotalHeight();
func_152125_a(x, y, iconX, iconY, iconWidth, iconHeight, iconRenderSize, iconRenderSize, width, height);
@@ -3,7 +3,7 @@ package noppes.npcs.client.gui.global;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityVariant;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket;
import kamkeel.npcs.network.packets.request.ability.ChainedAbilitiesGetPacket;
@@ -24,8 +24,8 @@ import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect;
import noppes.npcs.client.gui.advanced.SubGuiAbilityVariantSelect;
import noppes.npcs.client.gui.advanced.SubGuiChainedAbilityConfig;
import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm;
import noppes.npcs.client.gui.util.AbilityPreviewExecutor;
import noppes.npcs.client.gui.util.GuiAbilityInterface;
import kamkeel.npcs.controllers.data.ability.preview.AbilityPreviewExecutor;
import kamkeel.npcs.controllers.data.ability.gui.GuiAbilityInterface;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -104,7 +104,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
// ==================== PENDING SAVE ====================
private Ability pendingSaveAbility = null;
private boolean pendingNewCreation = false;
// ==================== PENDING VARIANT ====================
private String pendingTypeId = null;
@@ -511,13 +510,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
Ability newAbility = AbilityController.Instance.create(pendingTypeId);
if (newAbility != null) {
gui.getVariants().get(idx).apply(newAbility);
if (hasDuplicateName(newAbility)) {
pendingSaveAbility = newAbility;
pendingNewCreation = true;
pendingTypeId = null;
setSubGui(new SubGuiDuplicateNameConfirm());
return true;
}
pendingTypeId = null;
openConfig(newAbility);
return true;
@@ -544,12 +536,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
if (variants.size() == 1) {
variants.get(0).apply(newAbility);
}
if (hasDuplicateName(newAbility)) {
pendingSaveAbility = newAbility;
pendingNewCreation = true;
setSubGui(new SubGuiDuplicateNameConfirm());
return true;
}
openConfig(newAbility);
return true;
}
@@ -561,27 +547,22 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
* @return true if a SubGui was opened (caller should return early, skipping initGui)
*/
private boolean handleDuplicateNameClosed(SubGuiDuplicateNameConfirm gui) {
if (gui.isConfirmed() && pendingSaveAbility != null) {
if (pendingNewCreation) {
openConfig(pendingSaveAbility);
pendingSaveAbility = null;
pendingNewCreation = false;
return true;
} else {
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT()));
pendingSaveAbility = null;
}
} else if (pendingSaveAbility != null) {
if (pendingNewCreation) {
pendingSaveAbility = null;
pendingNewCreation = false;
} else {
Ability ability = pendingSaveAbility;
pendingSaveAbility = null;
setSubGui(ability.createConfigGui(this));
return true;
}
if (pendingSaveAbility == null) return false;
if (gui.isConfirmed()) {
PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT()));
pendingSaveAbility = null;
return false;
}
if (gui.isBack()) {
Ability ability = pendingSaveAbility;
pendingSaveAbility = null;
setSubGui(ability.createConfigGui(this));
return true;
}
pendingSaveAbility = null;
return false;
}
@@ -590,7 +571,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
*/
private boolean handlePendingSave() {
if (hasDuplicateName(pendingSaveAbility)) {
pendingNewCreation = false;
setSubGui(new SubGuiDuplicateNameConfirm());
return true;
}
@@ -62,6 +62,12 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
this.addButton(new GuiNpcButton(1, guiLeft + 358, guiTop + 38, 58, 20, "gui.add"));
this.addButton(new GuiNpcButton(2, guiLeft + 358, guiTop + 61, 58, 20, "gui.remove"));
getButton(1).setHoverText("tooltip.naturalspawns.main.addProfile");
getButton(2).setHoverText("tooltip.naturalspawns.main.removeProfile");
if (getTextField(55) != null) {
getTextField(55).setHoverText("tooltip.naturalspawns.main.search");
}
if (this.spawn.id >= 0)
showSpawn();
@@ -74,15 +80,18 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
int y = guiTop + 30;
addLabel(new GuiNpcLabel(3, "spawning.biomes", guiLeft + 4, y));
addButton(new GuiNpcButton(3, guiLeft + 40, y - 5, 50, 20, "selectServer.edit"));
getButton(3).setHoverText("tooltip.naturalspawns.main.biomes");
addLabel(new GuiNpcLabel(11, StatCollector.translateToLocal("Dimensions"), guiLeft + 95, y));
addButton(new GuiNpcButton(11, guiLeft + 150, y - 5, 50, 20, "selectServer.edit"));
getButton(11).setHoverText("tooltip.naturalspawns.main.dimensions");
addLabel(new GuiNpcLabel(4, "spawning.options", guiLeft + 4, y += 22));
addButton(new GuiNpcButton(4, guiLeft + 90, y - 5, 50, 20, "selectServer.edit"));
getButton(4).setHoverText("tooltip.naturalspawns.main.options");
addSlider(new GuiNpcSlider(this, 5, guiLeft + 4, y += 17, 180, 20, (float) this.spawn.itemWeight / 100));
addExtra(new GuiHoverText(1, "spawning.naturalInfo", guiLeft + 188, y + 5));
addExtra(new GuiHoverText(1, "spawning.naturalInfoPerformance", guiLeft + 188, y + 5));
this.spawnEntryScroll.guiLeft = guiLeft + 4;
this.spawnEntryScroll.guiTop = y + 40;
@@ -96,13 +105,17 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
addScroll(this.spawnEntryScroll);
addButton(new GuiNpcButton(21, guiLeft + 6, y += 20, 20, 20, "+"));
getButton(21).setHoverText("tooltip.naturalspawns.main.addEntry");
if (this.spawnEntryScroll.hasSelected()) {
int selected = Integer.parseInt(this.spawnEntryScroll.getSelected());
addButton(new GuiNpcButton(22, guiLeft + 32, y, 20, 20, "-"));
getButton(22).setHoverText("tooltip.naturalspawns.main.removeEntry");
GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, "" + selected);
num.integersOnly = true;
addTextField(num);
getTextField(25).setHoverText("tooltip.naturalspawns.main.slot");
addButton(new GuiNpcButton(26, guiLeft + 92, y, 100, 20, this.getTitle(this.spawn.spawnCompounds.get(selected))));
getButton(26).setHoverText("tooltip.naturalspawns.main.selectEntry");
}
}
@@ -4,11 +4,12 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket;
import net.minecraft.client.Minecraft;
import noppes.npcs.client.ClientProxy;
import noppes.npcs.client.ClientAbilityState;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution;
@@ -30,6 +31,7 @@ public class AbilityHotbarComponent extends HudComponent {
private static final int BASE_SLOT_SIZE = 24;
private static final int BASE_SPACING = 28;
private static final int EDIT_HANDLE_SIZE = 10;
private AbilityHotbarSlotRenderer[] slots = new AbilityHotbarSlotRenderer[TOTAL_SLOTS];
@@ -189,6 +191,7 @@ public class AbilityHotbarComponent extends HudComponent {
int centerX = overlayWidth / 2;
int centerY = overlayHeight / 2;
boolean activePhase = ClientAbilityState.activePhase;
// Compute text visibility: 0=Shown, 1=Hidden, 2=Held
boolean showText;
@@ -246,16 +249,16 @@ public class AbilityHotbarComponent extends HudComponent {
if (rawSlotIndex == -1) {
// Deselect slot — draw empty marker
drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha);
drawDeselectSlot(cx, cy, scaledSize, isCenter, slotAlpha, activePhase);
} else {
slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText);
slots[rawSlotIndex].drawCarousel(mc, sr, slotCooldown, cx, cy, scaledSize, isCenter, slotAlpha, showText, activePhase);
}
}
GL11.glPopMatrix();
}
private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha) {
private void drawDeselectSlot(int cx, int cy, int size, boolean isCenter, float alpha, boolean activePhase) {
float radius = size / 2f;
float baseAlpha = isCenter ? 0.9f : 0.6f;
float a = baseAlpha * alpha;
@@ -268,7 +271,13 @@ public class AbilityHotbarComponent extends HudComponent {
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if (isCenter) {
if (activePhase) {
if (isCenter) {
GL11.glColor4f(0.65f, 0.14f, 0.14f, a);
} else {
GL11.glColor4f(0.38f, 0.10f, 0.10f, a);
}
} else if (isCenter) {
GL11.glColor4f(0.5f, 0.2f, 0.2f, a);
} else {
GL11.glColor4f(0.3f, 0.3f, 0.3f, a);
@@ -292,7 +301,13 @@ public class AbilityHotbarComponent extends HudComponent {
}
// Draw X mark
if (isCenter) {
if (activePhase) {
if (isCenter) {
GL11.glColor4f(1.0f, 0.45f, 0.35f, alpha);
} else {
GL11.glColor4f(0.75f, 0.30f, 0.30f, alpha * 0.8f);
}
} else if (isCenter) {
GL11.glColor4f(0.8f, 0.4f, 0.4f, alpha);
} else {
GL11.glColor4f(0.5f, 0.5f, 0.5f, alpha * 0.8f);
@@ -416,25 +431,18 @@ public class AbilityHotbarComponent extends HudComponent {
int modeLabelW = fr.getStringWidth(modeLabel);
fr.drawStringWithShadow(modeLabel, overlayWidth / 2 - modeLabelW / 2, overlayHeight + 2, 0xAA888888);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(0.2f, 0.8f, 0.2f, 0.8f);
GL11.glLineWidth(1.0f);
GL11.glBegin(GL11.GL_LINE_LOOP);
GL11.glVertex2f(0, 0);
GL11.glVertex2f(overlayWidth, 0);
GL11.glVertex2f(overlayWidth, overlayHeight);
GL11.glVertex2f(0, overlayHeight);
GL11.glEnd();
net.minecraft.client.gui.Gui.drawRect(0, 0, overlayWidth, overlayHeight, 0x22000000);
drawRectOutline(0, 0, overlayWidth, overlayHeight, 0xCC66CC66);
GL11.glColor4f(0.8f, 0.8f, 0.8f, 0.9f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(overlayWidth - 10, overlayHeight - 10);
GL11.glVertex2f(overlayWidth, overlayHeight - 10);
GL11.glVertex2f(overlayWidth, overlayHeight);
GL11.glVertex2f(overlayWidth - 10, overlayHeight);
GL11.glEnd();
int handleLeft = overlayWidth - EDIT_HANDLE_SIZE;
int handleTop = overlayHeight - EDIT_HANDLE_SIZE;
net.minecraft.client.gui.Gui.drawRect(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFFE0E0E0);
drawRectOutline(handleLeft, handleTop, overlayWidth, overlayHeight, 0xFF5A5A5A);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 2, handleTop + 7, handleLeft + 8, handleTop + 8, 0xAA666666);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 4, handleTop + 5, handleLeft + 8, handleTop + 6, 0xAA666666);
net.minecraft.client.gui.Gui.drawRect(handleLeft + 6, handleTop + 3, handleLeft + 8, handleTop + 4, 0xAA666666);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_TEXTURE_2D);
@@ -596,7 +604,20 @@ public class AbilityHotbarComponent extends HudComponent {
private boolean isHudKeyHeld() {
if (ClientProxy.AbilityHudKey == null) return false;
int keyCode = ClientProxy.AbilityHudKey.getKeyCode();
return keyCode != 0 && org.lwjgl.input.Keyboard.isKeyDown(keyCode);
if (keyCode == 0 || keyCode == -1) return false;
// Mouse bindings are encoded as negative key codes (offset by 100).
if (keyCode < -1) {
int mouseButton = keyCode + 100;
return mouseButton >= 0
&& mouseButton < org.lwjgl.input.Mouse.getButtonCount()
&& org.lwjgl.input.Mouse.isButtonDown(mouseButton);
}
// Guard against invalid/out-of-range keyboard codes to avoid Buffer.checkIndex crashes.
return keyCode > 0
&& keyCode < org.lwjgl.input.Keyboard.getKeyCount()
&& org.lwjgl.input.Keyboard.isKeyDown(keyCode);
}
public boolean hasAnyAbilities() {
@@ -680,4 +701,11 @@ public class AbilityHotbarComponent extends HudComponent {
updateAbilities();
lastUpdateTime = Minecraft.getSystemTime();
}
private void drawRectOutline(int left, int top, int right, int bottom, int color) {
net.minecraft.client.gui.Gui.drawRect(left, top, right, top + 1, color);
net.minecraft.client.gui.Gui.drawRect(left, bottom - 1, right, bottom, color);
net.minecraft.client.gui.Gui.drawRect(left, top, left + 1, bottom, color);
net.minecraft.client.gui.Gui.drawRect(right - 1, top, right, bottom, color);
}
}
@@ -3,8 +3,8 @@ package noppes.npcs.client.gui.hud.ability;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
@@ -48,7 +48,7 @@ public class AbilityHotbarSlotRenderer extends Gui {
public void drawCarousel(Minecraft mc, ScaledResolution sr, float cooldownProgress,
int cx, int cy, int size, boolean isCenter, float slotAlpha,
boolean showText) {
boolean showText, boolean activePhase) {
float nameAlpha = this.nameAlpha;
boolean isHorizontal = ConfigClient.AbilityHotbarHorizontal;
if (size <= 0 || slotAlpha <= 0) return;
@@ -61,21 +61,54 @@ public class AbilityHotbarSlotRenderer extends Gui {
boolean altTexture = ConfigClient.AbilityHotbarAltTexture;
if (altTexture) {
drawRoundedRect(-radius, -radius, radius, radius, 0.6f, 0.6f, 0.6f, 0.75f * alpha, false);
float fillR;
float fillG;
float fillB;
float outlineR;
float outlineG;
float outlineB;
if (activePhase) {
if (isCenter) {
drawRoundedRect(-radius, -radius, radius, radius, 0.8f, 0.8f, 0.2f, alpha, true);
fillR = 0.95f;
fillG = 0.26f;
fillB = 0.22f;
outlineR = 1.0f;
outlineG = 0.52f;
outlineB = 0.28f;
} else {
drawRoundedRect(-radius, -radius, radius, radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true);
fillR = 0.36f;
fillG = 0.14f;
fillB = 0.14f;
outlineR = 0.65f;
outlineG = 0.22f;
outlineB = 0.20f;
}
} else if (isCenter) {
fillR = 0.8f;
fillG = 0.8f;
fillB = 0.2f;
outlineR = 0.8f;
outlineG = 0.8f;
outlineB = 0.2f;
} else {
if (isCenter) {
drawCircle(radius, 0.8f, 0.8f, 0.2f, 0.66f * alpha, false);
drawCircle(radius, 0.8f, 0.8f, 0.2f, alpha, true);
} else {
drawCircle(radius, 1f, 1f, 1f, 0.66f * alpha, false);
drawCircle(radius, 0.4f, 0.4f, 0.4f, alpha * 0.8f, true);
}
fillR = 0.4f;
fillG = 0.4f;
fillB = 0.4f;
outlineR = 1f;
outlineG = 1f;
outlineB = 1f;
}
if (altTexture) {
float baseR = activePhase ? 0.30f : 0.6f;
float baseG = activePhase ? 0.12f : 0.6f;
float baseB = activePhase ? 0.12f : 0.6f;
drawRoundedRect(-radius, -radius, radius, radius, baseR, baseG, baseB, 0.75f * alpha, false);
drawRoundedRect(-radius, -radius, radius, radius, fillR, fillG, fillB, alpha * 0.8f, true);
} else {
drawCircle(radius, outlineR, outlineG, outlineB, 0.66f * alpha, false);
drawCircle(radius, fillR, fillG, fillB, alpha * 0.8f, true);
}
// Ability icon
@@ -3,9 +3,9 @@ package noppes.npcs.client.gui.hud.ability;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.AbilityIconData;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.Tessellator;
@@ -88,10 +88,16 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
AuctionListing listing = tradesContainer.getListingAt(slot);
AuctionClaim claim = tradesContainer.getClaimAt(slot);
if (listing != null && tradesContainer.isSellingAt(slot) && mouseButton == 1) {
// Right-click on own listing = show cancel
setPending(slot, PendingOp.CANCEL);
NoppesUtil.clickSound();
if (listing != null && tradesContainer.isSellingAt(slot)) {
if (mouseButton == 0) {
// Left-click on own listing = view details
AuctionActionPacket.openBidding(listing.id);
NoppesUtil.clickSound();
} else if (mouseButton == 1) {
// Right-click on own listing = show cancel
setPending(slot, PendingOp.CANCEL);
NoppesUtil.clickSound();
}
} else if (listing != null && tradesContainer.isBiddingAt(slot) && mouseButton == 0) {
// Left-click on active bid = open bidding GUI to increase bid
AuctionActionPacket.openBidding(listing.id);
@@ -315,16 +321,13 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
AuctionListing listing = tradesContainer.getListingAt(slot);
AuctionClaim claim = tradesContainer.getClaimAt(slot);
if (listing != null) {
if (tradesContainer.isSellingAt(slot)) {
tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.trades.activeListing"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel"));
} else if (tradesContainer.isBiddingAt(slot)) {
tooltip.add(EnumChatFormatting.AQUA + StatCollector.translateToLocal("auction.trades.activeBid"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.winningBid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToIncrease"));
}
} else if (claim != null) {
// Slots with items have tooltips handled by AuctionTooltipHandler via ItemTooltipEvent
if (listing != null) return;
if (claim != null && (claim.type == EnumClaimType.ITEM ||
(claim.type == EnumClaimType.REFUND && claim.item != null))) return;
// Non-item slots (currency claims, refund without item, unavailable)
if (claim != null) {
switch (claim.type) {
case CURRENCY:
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.soldClaim"));
@@ -342,20 +345,6 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.outbidBy") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName);
}
tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName());
// Show rebid option if item is present (active listing)
if (claim.item != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund"));
return; // Skip the generic claim message
}
break;
case ITEM:
if (claim.isReturned) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expiredClaim"));
} else {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.wonClaim"));
}
break;
}
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.leftClickToClaim"));
@@ -2,8 +2,8 @@ package noppes.npcs.client.gui.player.inventory;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSavePacket;
import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket;
@@ -2,7 +2,7 @@ package noppes.npcs.client.gui.player.inventory;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.util.GuiCustomScroll;
@@ -1,636 +0,0 @@
package noppes.npcs.client.gui.util;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.ChainedAbilityEntry;
import kamkeel.npcs.controllers.data.ability.PreviewEntityHandler;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Client-side executor for previewing abilities in the GUI.
* <p>
* Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick)
* with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true.
* <p>
* Lifecycle:
* 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn
* 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated
* 3. EXTENDED phase - 100 extra ticks to observe results (entities continue updating)
* 4. IDLE - preview complete
*/
@SideOnly(Side.CLIENT)
public class AbilityPreviewExecutor implements PreviewEntityHandler {
// ==================== PREVIEW STATE ====================
private Ability previewAbility;
private EntityNPCInterface previewNpc;
/**
* Executor's own phase tracking (separate from ability.getPhase())
*/
private enum ExecutorPhase {IDLE, WINDUP, ACTIVE, EXTENDED, CHAIN_DELAY}
private ExecutorPhase executorPhase = ExecutorPhase.IDLE;
private int currentTick = 0;
private boolean playing = false;
private boolean paused = false;
// ==================== TIMING ====================
private static final int EXTENDED_DURATION = 100;
private int maxPreviewDuration = 200;
// ==================== FAKE TARGET ====================
private EntityNPCInterface fakeTarget;
private static final double TARGET_DISTANCE = 5.0;
// ==================== NPC START POSITION ====================
private double npcStartX, npcStartY, npcStartZ;
// ==================== PREVIEW CONTENT ====================
private TelegraphInstance previewTelegraph;
private List<Entity> previewEntities = new ArrayList<>();
// ==================== CHAIN PREVIEW ====================
private ChainedAbility previewChain;
private List<Ability> chainAbilities;
private List<Integer> chainDelays;
private int chainIndex = -1;
private int chainDelayRemaining = 0;
private boolean chainWindUpAll = true;
// ==================== CALLBACKS ====================
private GuiAbilityInterface parentGui;
public AbilityPreviewExecutor() {
}
public void setParentGui(GuiAbilityInterface gui) {
this.parentGui = gui;
}
/**
* Start previewing a single ability using unified execution.
* Sets previewMode=true on the ability, then calls its real methods.
*/
public void startPreview(Ability ability, EntityNPCInterface npc) {
stop();
this.previewNpc = npc;
this.playing = true;
this.paused = false;
// Save NPC start position for restoring later
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
// Create invisible fake target NPC for targeting
createFakeTarget(npc);
// Start tracking NPC movement
if (parentGui != null) {
parentGui.startTrackingMovement();
}
beginAbilityPreview(ability);
}
/**
* Start previewing a chained ability — plays all entries in sequence with delays.
* Each entry is resolved and deep-copied to avoid modifying originals.
*/
public void startChainPreview(ChainedAbility chain, EntityNPCInterface npc) {
stop();
this.previewNpc = npc;
this.playing = true;
this.paused = false;
this.previewChain = chain;
this.chainWindUpAll = chain.isWindUpAll();
// Save NPC start position for restoring later
this.npcStartX = npc.posX;
this.npcStartY = npc.posY;
this.npcStartZ = npc.posZ;
// Resolve all entries to deep-copied abilities
chainAbilities = new ArrayList<>();
chainDelays = new ArrayList<>();
for (ChainedAbilityEntry entry : chain.getEntries()) {
Ability resolved = entry.resolve();
if (resolved != null && AbilityController.Instance != null) {
Ability copy = AbilityController.Instance.fromNBT(resolved.writeNBT());
if (copy != null) {
chainAbilities.add(copy);
chainDelays.add(entry.getDelayTicks());
}
}
}
if (chainAbilities.isEmpty()) {
playing = false;
return;
}
// Create invisible fake target NPC for targeting
createFakeTarget(npc);
// Start tracking NPC movement
if (parentGui != null) {
parentGui.startTrackingMovement();
}
chainIndex = 0;
beginAbilityPreview(chainAbilities.get(0));
}
/**
* Begin previewing a single ability (shared by single and chain preview).
* Cleans up the previous ability if any (for chain advancement).
*/
private void beginAbilityPreview(Ability ability) {
// Clean up previous ability if any (for chain advancement)
if (previewAbility != null) {
previewAbility.cleanup();
previewAbility.setPreviewMode(false);
previewAbility.setPreviewEntityHandler(null);
previewAbility.reset();
}
this.previewAbility = ability;
this.currentTick = 0;
this.maxPreviewDuration = ability.getMaxPreviewDuration();
// Enable preview mode on the ability
ability.setPreviewMode(true);
ability.setPreviewEntityHandler(this);
// Use the ability's real start() method with the fake target
ability.start(fakeTarget);
// Skip windup for non-first chain entries when windUpAll is false
boolean skipWindup = previewChain != null && !chainWindUpAll && chainIndex > 0;
if (ability.getWindUpTicks() <= 0 || skipWindup) {
// No windup — go straight to active
this.executorPhase = ExecutorPhase.ACTIVE;
transitionToActive();
} else {
// Normal windup flow
this.executorPhase = ExecutorPhase.WINDUP;
// Create telegraph for preview
previewTelegraph = ability.createTelegraph(previewNpc, fakeTarget);
// Start windup animation
Animation windUpAnim = ability.getWindUpAnimation();
if (windUpAnim != null) {
AnimationData data = previewNpc.display.animationData;
data.setEnabled(true);
data.setAnimation(windUpAnim);
data.animation.paused = false;
}
}
}
/**
* Create an invisible fake target NPC placed in front of the preview NPC.
*/
private void createFakeTarget(EntityNPCInterface npc) {
if (npc.worldObj == null) return;
try {
fakeTarget = new EntityCustomNpc(npc.worldObj);
float facingYaw = GuiAbilityInterface.NPC_FACING_YAW;
double yawRad = Math.toRadians(facingYaw);
double targetX = npc.posX - Math.sin(yawRad) * TARGET_DISTANCE;
double targetY = npc.posY;
double targetZ = npc.posZ + Math.cos(yawRad) * TARGET_DISTANCE;
fakeTarget.setPosition(targetX, targetY, targetZ);
fakeTarget.prevPosX = targetX;
fakeTarget.prevPosY = targetY;
fakeTarget.prevPosZ = targetZ;
} catch (Exception e) {
fakeTarget = null;
}
}
public EntityLivingBase getFakeTarget() {
return fakeTarget;
}
public void play() {
if (previewAbility == null || executorPhase == ExecutorPhase.IDLE) {
return;
}
playing = true;
paused = false;
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
if (data.animation != null) {
data.animation.paused = false;
}
}
}
public void pause() {
paused = true;
// Immediately sync prevPos to pos for NPC and all entities to prevent interpolation jitter
syncPrevPositions();
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
if (data.animation != null) {
data.animation.paused = true;
}
}
}
/**
* Sync prevPos to pos for the NPC and all preview entities.
* Prevents rendering interpolation jitter when standing still or paused.
*/
private void syncPrevPositions() {
if (previewNpc != null) {
previewNpc.prevPosX = previewNpc.posX;
previewNpc.prevPosY = previewNpc.posY;
previewNpc.prevPosZ = previewNpc.posZ;
}
for (Entity entity : previewEntities) {
if (entity != null && !entity.isDead) {
entity.prevPosX = entity.posX;
entity.prevPosY = entity.posY;
entity.prevPosZ = entity.posZ;
}
}
}
public void stop() {
// Clean up the ability
if (previewAbility != null) {
previewAbility.cleanup();
previewAbility.setPreviewMode(false);
previewAbility.setPreviewEntityHandler(null);
previewAbility.reset();
}
playing = false;
paused = false;
executorPhase = ExecutorPhase.IDLE;
currentTick = 0;
// Clear chain state
previewChain = null;
chainAbilities = null;
chainDelays = null;
chainIndex = -1;
chainDelayRemaining = 0;
previewTelegraph = null;
if (parentGui != null) {
for (Entity entity : previewEntities) {
parentGui.removePreviewEntity(entity);
}
parentGui.stopTrackingMovement();
parentGui.setPreviewTelegraph(null);
}
previewEntities.clear();
// Reset NPC position to start position (undo movement from Slam/Charge/Dash)
if (previewNpc != null && npcStartX != 0 && npcStartY != 0 && npcStartZ != 0) {
previewNpc.posX = npcStartX;
previewNpc.posY = npcStartY;
previewNpc.posZ = npcStartZ;
previewNpc.prevPosX = npcStartX;
previewNpc.prevPosY = npcStartY;
previewNpc.prevPosZ = npcStartZ;
previewNpc.motionX = 0;
previewNpc.motionY = 0;
previewNpc.motionZ = 0;
}
fakeTarget = null;
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(new Animation());
data.animation.paused = false;
}
}
/**
* Tick the preview forward. Calls real ability methods.
*/
public void tick() {
if (!playing || previewAbility == null || previewNpc == null) {
return;
}
if (paused) {
// Sync prevPos to pos for NPC and all entities to prevent interpolation jitter while paused
syncPrevPositions();
return;
}
// Sync NPC's prevPos to current pos BEFORE any updates to prevent jitter when standing still
previewNpc.prevPosX = previewNpc.posX;
previewNpc.prevPosY = previewNpc.posY;
previewNpc.prevPosZ = previewNpc.posZ;
currentTick++;
if (previewTelegraph != null) {
previewTelegraph.tick(null);
}
tickEntities();
switch (executorPhase) {
case WINDUP:
tickWindup();
break;
case ACTIVE:
tickActive();
break;
case EXTENDED:
tickExtended();
break;
case CHAIN_DELAY:
tickChainDelay();
break;
default:
break;
}
}
private void tickWindup() {
// Call the REAL windup tick method
previewAbility.onWindUpTick(previewNpc, fakeTarget, currentTick);
if (currentTick >= previewAbility.getWindUpTicks()) {
transitionToActive();
}
}
private void tickActive() {
// Call the REAL active tick method
previewAbility.onActiveTick(previewNpc, fakeTarget, currentTick);
// Simulate physics for movement abilities
simulatePhysics();
// Check if the ability signaled completion (phase went to IDLE)
if (previewAbility.getPhase() == AbilityPhase.IDLE) {
if (hasNextChainEntry()) {
transitionToChainDelay();
} else {
transitionToExtended();
}
return;
}
// Safety timeout
if (currentTick >= maxPreviewDuration) {
if (hasNextChainEntry()) {
transitionToChainDelay();
} else {
transitionToExtended();
}
}
}
private void tickExtended() {
// Continue ticking entities so they can finish their animations
if (currentTick >= EXTENDED_DURATION) {
playing = false;
}
}
// ==================== CHAIN ADVANCEMENT ====================
private boolean hasNextChainEntry() {
return previewChain != null && chainAbilities != null && chainIndex < chainAbilities.size() - 1;
}
private void transitionToChainDelay() {
executorPhase = ExecutorPhase.CHAIN_DELAY;
currentTick = 0;
// Use the NEXT entry's delay
int nextIndex = chainIndex + 1;
chainDelayRemaining = (nextIndex < chainDelays.size()) ? chainDelays.get(nextIndex) : 0;
// Clear current animation
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(new Animation());
}
}
private void tickChainDelay() {
if (chainDelayRemaining > 0) {
chainDelayRemaining--;
return;
}
advanceChainEntry();
}
private void advanceChainEntry() {
chainIndex++;
if (chainIndex >= chainAbilities.size()) {
transitionToExtended();
return;
}
beginAbilityPreview(chainAbilities.get(chainIndex));
}
private void transitionToActive() {
executorPhase = ExecutorPhase.ACTIVE;
currentTick = 0;
previewTelegraph = null;
// Call the REAL onExecute method (fires entities, initiates movement, etc.)
previewAbility.onExecute(previewNpc, fakeTarget);
// Start active animation
Animation activeAnim = previewAbility.getActiveAnimation();
if (activeAnim != null && previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(activeAnim);
data.animation.paused = false;
}
}
private void transitionToExtended() {
executorPhase = ExecutorPhase.EXTENDED;
currentTick = 0;
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(new Animation());
}
}
/**
* Simulate basic physics for movement abilities (Slam, Charge, Dash).
* Applies gravity, drag, and ground clamping to NPC position.
*/
private void simulatePhysics() {
if (!previewAbility.hasAbilityMovement()) return;
if (previewNpc == null) return;
// Save previous position for interpolation
previewNpc.prevPosX = previewNpc.posX;
previewNpc.prevPosY = previewNpc.posY;
previewNpc.prevPosZ = previewNpc.posZ;
// Apply velocity
previewNpc.posX += previewNpc.motionX;
previewNpc.posY += previewNpc.motionY;
previewNpc.posZ += previewNpc.motionZ;
// Apply gravity
previewNpc.motionY -= 0.08;
previewNpc.motionY *= 0.98;
// Apply horizontal drag
previewNpc.motionX *= 0.91;
previewNpc.motionZ *= 0.91;
// Ground clamp: if below start position and falling, stop
if (previewNpc.posY < npcStartY && previewNpc.motionY < 0) {
previewNpc.posY = npcStartY;
previewNpc.motionY = 0;
previewNpc.onGround = true;
}
previewNpc.fallDistance = 0;
}
private void tickEntities() {
Iterator<Entity> iter = previewEntities.iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity == null || entity.isDead) {
if (parentGui != null) {
parentGui.removePreviewEntity(entity);
}
iter.remove();
continue;
}
entity.onUpdate();
}
}
// ==================== PreviewEntityHandler ====================
@Override
public void onEntitySpawned(Entity entity) {
if (entity == null) return;
previewEntities.add(entity);
if (parentGui != null) {
parentGui.addPreviewEntity(entity);
}
}
@Override
public void onEntityRemoved(Entity entity) {
if (entity == null) return;
previewEntities.remove(entity);
if (parentGui != null) {
parentGui.removePreviewEntity(entity);
}
}
// ==================== GETTERS ====================
public boolean isPlaying() {
return playing;
}
public boolean isPaused() {
return paused;
}
public boolean isActive() {
return playing || paused;
}
public boolean isChainPreview() {
return previewChain != null;
}
public AbilityPhase getPhase() {
switch (executorPhase) {
case WINDUP:
return AbilityPhase.WINDUP;
case ACTIVE:
return AbilityPhase.ACTIVE;
default:
return AbilityPhase.IDLE;
}
}
public int getCurrentTick() {
return currentTick;
}
public TelegraphInstance getTelegraph() {
return previewTelegraph;
}
public List<Entity> getPreviewEntities() {
return previewEntities;
}
public Ability getPreviewAbility() {
return previewAbility;
}
public EntityNPCInterface getPreviewNpc() {
return previewNpc;
}
public String getStatusString() {
if (!playing && !paused) {
return "Stopped";
}
String chainPrefix = "";
if (previewChain != null && chainAbilities != null) {
chainPrefix = "Chain " + (chainIndex + 1) + "/" + chainAbilities.size() + " - ";
}
if (paused) {
return chainPrefix + "Paused";
} else if (executorPhase == ExecutorPhase.WINDUP) {
return chainPrefix + "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0);
} else if (executorPhase == ExecutorPhase.ACTIVE) {
return chainPrefix + "Active: " + currentTick + "/" + maxPreviewDuration;
} else if (executorPhase == ExecutorPhase.EXTENDED) {
return chainPrefix + "Extended: " + currentTick + "/" + EXTENDED_DURATION;
} else if (executorPhase == ExecutorPhase.CHAIN_DELAY) {
return chainPrefix + "Delay: " + chainDelayRemaining;
}
return "";
}
}
@@ -1,409 +0,0 @@
package noppes.npcs.client.gui.util;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import noppes.npcs.client.ClientEventHandler;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.ArrayList;
import java.util.List;
/**
* Base GUI class for ability preview with fixed camera.
* <p>
* Key concepts:
* - NPC positioned on left side of preview area
* - NPC faces a fixed direction (NPC_FACING_YAW)
* - Viewing direction can be rotated (rotates entire 3D space)
* - Fixed zoom level
* - Preview entities rendered in same coordinate space as NPC
* - NPC position changes (e.g. slam jump) tracked and rendered
*/
public class GuiAbilityInterface extends GuiNPCInterface2 {
// ==================== FIXED CAMERA SETTINGS ====================
/**
* Fixed camera zoom level (higher = more zoomed in)
*/
protected static float CAMERA_ZOOM = 45.0f;
/**
* NPC facing direction - affects anchor points and visual facing
*/
protected static float NPC_FACING_YAW = 160.0f;
/**
* Camera pitch (slight downward angle)
*/
protected static float CAMERA_PITCH = 10.0f;
// ==================== VIEWING ROTATION ====================
/**
* Viewing direction rotation (rotates entire 3D space)
*/
protected static float viewRotation = 0.0f;
private GuiNpcButton btnLeft, btnRight;
// ==================== NPC STATE ====================
public EntityNPCInterface npc;
/**
* NPC starting position (saved when preview starts, used to track movement)
*/
protected double npcStartX, npcStartY, npcStartZ;
/**
* Whether we're tracking NPC movement
*/
protected boolean trackingNpcMovement = false;
/**
* Entities to render in preview space
*/
protected List<Entity> previewEntities = new ArrayList<>();
/**
* Current telegraph to render in preview
*/
protected TelegraphInstance previewTelegraph;
// ==================== LAYOUT ====================
/**
* Preview area bounds
*/
protected int previewX, previewY, previewWidth, previewHeight;
/**
* NPC render position on screen
*/
protected int npcScreenX, npcScreenY;
public int xOffset = 0;
public int yOffset = 0;
public GuiAbilityInterface(EntityNPCInterface npc) {
this(npc, true);
}
/**
* @param npc The NPC for preview rendering
* @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden.
* Use false when opened from the global menu without a real NPC.
*/
public GuiAbilityInterface(EntityNPCInterface npc, boolean hasMenuNpc) {
super(hasMenuNpc ? npc : null);
this.npc = npc;
this.drawDefaultBackground = false;
CAMERA_ZOOM = 30f;
NPC_FACING_YAW = 310f;
CAMERA_PITCH = 5f;
}
@Override
public void initGui() {
super.initGui();
// Calculate preview area (left side of GUI)
previewX = guiLeft + 10;
previewY = guiTop + 10;
previewWidth = 200;
previewHeight = 180;
// NPC position: left side of preview, slightly below center
npcScreenX = previewX + (int) (previewWidth * 0.33f) + xOffset;
npcScreenY = previewY + (int) (previewHeight * 0.85f) + yOffset;
// Viewing rotation buttons (below preview area)
int btnY = guiTop + 192;
addButton(btnLeft = new GuiNpcButton(680, guiLeft + 10, btnY, 20, 20, "<"));
addButton(btnRight = new GuiNpcButton(681, guiLeft + 32, btnY, 20, 20, ">"));
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
// Handle held rotation buttons
if (Mouse.isButtonDown(0)) {
if (btnLeft != null && btnLeft.mousePressed(mc, mouseX, mouseY)) {
viewRotation += partialTicks * 2;
} else if (btnRight != null && btnRight.mousePressed(mc, mouseX, mouseY)) {
viewRotation -= partialTicks * 2;
}
}
// Draw background and UI elements
super.drawScreen(mouseX, mouseY, partialTicks);
// Draw the 3D preview
drawPreview(mouseX, mouseY, partialTicks);
}
/**
* Draw the 3D preview with NPC and entities.
*/
protected void drawPreview(int mouseX, int mouseY, float partialTicks) {
if (hasSubGui())
return;
GL11.glColor4f(1, 1, 1, 1);
// Enable scissor to clip rendering to preview area
GL11.glEnable(GL11.GL_SCISSOR_TEST);
setScissorClip(previewX, previewY, previewWidth, previewHeight);
// Always use the standard NPC animation renderer for ability preview
EntityLivingBase renderEntity = this.npc;
// Set NPC facing direction (affects anchor points and visual facing)
npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW;
npc.prevRotationYaw = npc.rotationYaw = NPC_FACING_YAW;
npc.prevRotationYawHead = npc.rotationYawHead = NPC_FACING_YAW;
// Also set on render entity
renderEntity.prevRenderYawOffset = renderEntity.renderYawOffset = NPC_FACING_YAW;
renderEntity.prevRotationYaw = renderEntity.rotationYaw = NPC_FACING_YAW;
renderEntity.prevRotationYawHead = renderEntity.rotationYawHead = NPC_FACING_YAW;
renderEntity.rotationPitch = 0;
// Calculate NPC position delta for movement rendering (e.g. slam jump)
// Interpolate with partial ticks for smooth movement between frames
double npcDeltaX = 0, npcDeltaY = 0, npcDeltaZ = 0;
if (trackingNpcMovement) {
double interpX = npc.prevPosX + (npc.posX - npc.prevPosX) * partialTicks;
double interpY = npc.prevPosY + (npc.posY - npc.prevPosY) * partialTicks;
double interpZ = npc.prevPosZ + (npc.posZ - npc.prevPosZ) * partialTicks;
npcDeltaX = interpX - npcStartX;
npcDeltaY = interpY - npcStartY;
npcDeltaZ = interpZ - npcStartZ;
}
// ==================== BEGIN 3D RENDERING ====================
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
GL11.glPushMatrix();
// Move to NPC render position on screen
GL11.glTranslatef(npcScreenX, npcScreenY, 300F);
// Apply zoom (scale)
GL11.glScalef(-CAMERA_ZOOM, CAMERA_ZOOM, CAMERA_ZOOM);
// Flip for screen coordinates (Y is inverted)
GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F);
// Apply slight camera pitch (looking down at scene)
GL11.glRotatef(CAMERA_PITCH, 1.0F, 0.0F, 0.0F);
// Apply VIEWING rotation (rotates entire space, not just NPC)
GL11.glRotatef(viewRotation, 0.0F, 1.0F, 0.0F);
// Setup lighting (standard item lighting for consistent colors)
GL11.glRotatef(135F, 0.0F, 1.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glRotatef(-135F, 0.0F, 1.0F, 0.0F);
// Adjust for entity offset
GL11.glTranslatef(0.0F, renderEntity.yOffset, 0.0F);
RenderManager.instance.playerViewY = 180F;
ClientEventHandler.renderingEntityInGUI = true;
// Render the NPC at its position delta (for movement like slam jumps)
RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks);
// Render preview entities at their positions relative to NPC start position
renderPreviewEntities(partialTicks);
// Render telegraph in preview space
renderPreviewTelegraph(partialTicks);
ClientEventHandler.renderingEntityInGUI = false;
GL11.glPopMatrix();
// Cleanup GL state
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GL11.glDisable(GL11.GL_TEXTURE_2D);
OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit);
// Disable scissor
GL11.glDisable(GL11.GL_SCISSOR_TEST);
// Clear depth buffer so UI renders on top
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
}
/**
* Render preview entities in the same coordinate space as the NPC.
* Called WITHIN the 3D matrix transformation.
*/
protected void renderPreviewEntities(float partialTicks) {
// Save current GL state that NPC render may have changed
boolean lightingWasEnabled = GL11.glIsEnabled(GL11.GL_LIGHTING);
// Use the start position as the reference point for entity offsets
double refX = trackingNpcMovement ? npcStartX : npc.posX;
double refY = trackingNpcMovement ? npcStartY : npc.posY;
double refZ = trackingNpcMovement ? npcStartZ : npc.posZ;
for (Entity entity : previewEntities) {
if (entity == null || entity.isDead) continue;
// Calculate entity position relative to reference (NPC start position)
double offsetX = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - refX;
double offsetY = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - refY;
double offsetZ = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - refZ;
// The NPC model was translated by npc.yOffset, so we need to subtract it
offsetY -= npc.yOffset;
// Reset GL state before each entity to ensure colors render correctly
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GL11.glDisable(GL11.GL_LIGHTING);
try {
RenderManager.instance.renderEntityWithPosYaw(entity, offsetX, offsetY, offsetZ, entity.rotationYaw, partialTicks);
} catch (Exception e) {
// Ignore rendering errors
}
}
// Restore lighting state for any subsequent rendering
if (lightingWasEnabled) {
GL11.glEnable(GL11.GL_LIGHTING);
}
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
/**
* Render the telegraph in the 3D preview space.
* Called within the GL matrix transformation.
*/
protected void renderPreviewTelegraph(float partialTicks) {
if (previewTelegraph == null) return;
if (TelegraphRenderer.Instance == null) return;
// Telegraph position is in world coords - convert to preview space
double refX = trackingNpcMovement ? npcStartX : npc.posX;
double refY = trackingNpcMovement ? npcStartY : npc.posY;
double refZ = trackingNpcMovement ? npcStartZ : npc.posZ;
double offsetX = previewTelegraph.getInterpolatedX(partialTicks) - refX;
double offsetY = previewTelegraph.getInterpolatedY(partialTicks) - refY;
double offsetZ = previewTelegraph.getInterpolatedZ(partialTicks) - refZ;
// Adjust for NPC yOffset (same as entities)
offsetY -= npc.yOffset;
TelegraphRenderer.Instance.renderTelegraphInGUI(previewTelegraph, offsetX, offsetY, offsetZ, 1.0f, partialTicks);
}
public void setPreviewTelegraph(TelegraphInstance telegraph) {
this.previewTelegraph = telegraph;
}
/**
* Set scissor clip for preview area.
*/
protected void setScissorClip(int x, int y, int width, int height) {
ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
int scale = sr.getScaleFactor();
int scaledY = mc.displayHeight - (y + height) * scale;
GL11.glScissor(x * scale, scaledY, width * scale, height * scale);
}
// ==================== MOVEMENT TRACKING ====================
/**
* Start tracking NPC movement from current position.
*/
public void startTrackingMovement() {
npcStartX = npc.posX;
npcStartY = npc.posY;
npcStartZ = npc.posZ;
trackingNpcMovement = true;
}
/**
* Stop tracking NPC movement.
*/
public void stopTrackingMovement() {
trackingNpcMovement = false;
}
// ==================== PREVIEW ENTITY MANAGEMENT ====================
public void addPreviewEntity(Entity entity) {
if (entity != null && !previewEntities.contains(entity)) {
previewEntities.add(entity);
}
}
public void removePreviewEntity(Entity entity) {
previewEntities.remove(entity);
}
public void clearPreviewEntities() {
previewEntities.clear();
}
public List<Entity> getPreviewEntities() {
return previewEntities;
}
public float getNpcFacingYaw() {
return NPC_FACING_YAW;
}
// ==================== BACKGROUND ====================
@Override
protected void drawBackground() {
super.drawBackground();
drawGradientRect(previewX, previewY, previewX + previewWidth, previewY + previewHeight,
0xc0101010, 0xd0101010);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
// ==================== STANDARD OVERRIDES ====================
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
public void keyTyped(char par1, int par2) {
boolean hadSubGui = hasSubGui();
super.keyTyped(par1, par2);
if (par2 == 1 && !hadSubGui) {
close();
}
}
public void close() {
this.mc.displayGuiScreen((GuiScreen) null);
this.mc.setIngameFocus();
}
@Override
public void save() {
}
@Override
protected void actionPerformed(GuiButton btn) {
if (btn.id == 670) {
close();
}
}
}
@@ -80,9 +80,10 @@ public class GuiEffectBar extends GuiScreen {
int iconWidth = entry.effect.getWidth();
int iconHeight = entry.effect.getHeight();
int texWidth = imageData.getTotalWidth();
int texHeight = imageData.getTotalHeight();
// Use iconYOffset to vertically center the icon
func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texWidth);
func_152125_a(x + 2, drawY + iconYOffset, iconU, iconV, iconWidth, iconHeight, iconRenderSize, iconRenderSize, texWidth, texHeight);
GL11.glDisable(GL11.GL_DEPTH_TEST);
Minecraft.getMinecraft().getTextureManager().bindTexture(specialIcons);
@@ -190,7 +191,7 @@ public class GuiEffectBar extends GuiScreen {
if (imageData != null && imageData.imageLoaded()) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
imageData.bindTexture();
func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalWidth());
func_152125_a(tooltipX + (maxWidth - iconSize) / 2, textY + 4, hoveredEffect.iconX, hoveredEffect.iconY, hoveredEffect.getWidth(), hoveredEffect.getHeight(), iconSize, iconSize, imageData.getTotalWidth(), imageData.getTotalHeight());
}
textureManager.bindTexture(specialIcons);
@@ -96,7 +96,10 @@ public class GuiMenuTopButton extends GuiNpcButton {
@Override
public boolean mousePressed(Minecraft minecraft, int i, int j) {
boolean bo = !active && getVisible() && hover;
int h = this.height - (active ? 0 : 2);
boolean bo = !active && getVisible()
&& i >= xPosition && j >= yPosition
&& i < xPosition + getWidth() && j < yPosition + h;
if (bo && listener != null) {
listener.actionPerformed(this);
return false;
@@ -417,6 +417,12 @@ public abstract class GuiNPCInterface extends GuiScreen {
}
}
for(GuiScrollWindow guiScrollableComponent : scrollWindows.values()) {
if (guiScrollableComponent.isMouseOver(mouseX, mouseY)) {
guiScrollableComponent.drawHoverTexts(mouseX, mouseY);
}
}
for (GuiScreen gui : extra.values())
gui.drawScreen(i, j, f);
@@ -82,7 +82,8 @@ public class GuiNpcButton extends GuiButton {
}
public void setHoverText(String text) {
this.hoverableText = StatCollector.translateToLocal(text);
String translated = StatCollector.translateToLocal(text);
this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n");
}
public int getValue() {
@@ -201,13 +202,30 @@ public class GuiNpcButton extends GuiButton {
Minecraft mc = Minecraft.getMinecraft();
String displayString = StatCollector.translateToLocal(hoverableText);
GL11.glColor4f(1, 1, 1, 1);
List<String> lines = TextSplitter.splitText(displayString, 30);
List<String> lines = splitHoverText(displayString, 30);
drawHoveringText(lines, i, j, mc);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
}
private List<String> splitHoverText(String text, int maxLineLength) {
List<String> lines = new ArrayList<String>();
if (text == null || text.isEmpty())
return lines;
String normalized = text.replace("\\n", "\n");
String[] explicitLines = normalized.split("\\r?\\n", -1);
for (String line : explicitLines) {
if (line.isEmpty()) {
lines.add("");
continue;
}
lines.addAll(TextSplitter.splitText(line, maxLineLength));
}
return lines;
}
protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) {
if (mc.fontRenderer == null || textLines.isEmpty())
return;
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.util;
import kamkeel.npcs.util.TextSplitter;
import kamkeel.npcs.util.FileNameHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiScreen;
@@ -11,6 +12,7 @@ import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.ArrayList;
import java.util.List;
public class GuiNpcTextField extends GuiTextField {
@@ -26,6 +28,7 @@ public class GuiNpcTextField extends GuiTextField {
public float minFloat = 0, maxFloat = Float.MAX_VALUE, defFloat = 0;
protected static GuiNpcTextField activeTextfield = null;
public boolean canEdit = true;
private boolean fileNameSafe = false;
public String hoverableText = "";
private boolean wasHovered = false;
private int hoverCount = 0;
@@ -71,6 +74,11 @@ public class GuiNpcTextField extends GuiTextField {
public boolean textboxKeyTyped(char c, int i) {
if (!canEdit || !isFocused())
return false;
if (fileNameSafe && !GuiScreen.isCtrlKeyDown() && !isFileNameCharAllowed(c, i)) {
return false;
}
// Allow Ctrl shortcuts (select all, copy, paste, cut) to bypass char filter
if (GuiScreen.isCtrlKeyDown()) {
// For Ctrl+V (paste) on numeric fields, filter clipboard to valid chars
@@ -87,7 +95,17 @@ public class GuiNpcTextField extends GuiTextField {
}
return true;
}
return super.textboxKeyTyped(c, i);
if (i == 47 && fileNameSafe) {
String clipboard = GuiScreen.getClipboardString();
if (clipboard != null) {
String filtered = filterFileNameClipboard(clipboard);
if (!filtered.isEmpty())
writeText(filtered);
}
return true;
}
boolean handled = super.textboxKeyTyped(c, i);
return handled;
}
if (!charAllowed(c, i))
return false;
@@ -179,6 +197,9 @@ public class GuiNpcTextField extends GuiTextField {
else if (getFloat() > maxFloat)
setText(maxFloat + "");
}
if (fileNameSafe) {
normalizeFileNameText();
}
setCursorPositionZero();
if (listener != null)
listener.unFocused(this);
@@ -238,8 +259,54 @@ public class GuiNpcTextField extends GuiTextField {
return this;
}
public GuiNpcTextField setFileNameSafe() {
fileNameSafe = true;
normalizeFileNameText();
return this;
}
private boolean isSpecialNavigationKey(int keyCode) {
for (int allowed : allowedSpecialChars) {
if (allowed == keyCode) {
return true;
}
}
return false;
}
private boolean isFileNameCharAllowed(char c, int keyCode) {
if (isSpecialNavigationKey(keyCode) || c < 32) {
return true;
}
return Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == ' ';
}
private String filterFileNameClipboard(String clipboard) {
StringBuilder filtered = new StringBuilder(clipboard.length());
for (int idx = 0; idx < clipboard.length(); idx++) {
char c = clipboard.charAt(idx);
if (Character.isLetterOrDigit(c) || c == '_' || c == '-') {
filtered.append(c);
} else if (Character.isWhitespace(c)) {
filtered.append(' ');
}
}
return filtered.toString();
}
private void normalizeFileNameText() {
String current = getText();
String sanitized = FileNameHelper.sanitizeTextInput(current);
if (sanitized.equals(current)) return;
int cursor = getCursorPosition();
setText(sanitized);
setCursorPosition(Math.min(cursor, sanitized.length()));
}
public void setHoverText(String text) {
this.hoverableText = StatCollector.translateToLocal(text);
String translated = StatCollector.translateToLocal(text);
this.hoverableText = translated == null ? "" : translated.replace("\\n", "\n");
}
public boolean hasHoverText() {
@@ -252,10 +319,14 @@ public class GuiNpcTextField extends GuiTextField {
}
public void drawHover(int mouseX, int mouseY, boolean hasSubGui) {
drawHover(mouseX, mouseY, mouseX, mouseY, hasSubGui);
}
public void drawHover(int hitMouseX, int hitMouseY, int tooltipMouseX, int tooltipMouseY, boolean hasSubGui) {
if (hasSubGui || !enabled || hoverableText.isEmpty())
return;
boolean isHovered = isMouseOver(mouseX, mouseY);
boolean isHovered = isMouseOver(hitMouseX, hitMouseY);
if (!isHovered) {
wasHovered = false;
hoverCount = 0;
@@ -273,13 +344,30 @@ public class GuiNpcTextField extends GuiTextField {
GL11.glPushMatrix();
Minecraft mc = Minecraft.getMinecraft();
GL11.glColor4f(1, 1, 1, 1);
List<String> lines = TextSplitter.splitText(hoverableText, 30);
drawHoveringText(lines, mouseX, mouseY, mc);
List<String> lines = splitHoverText(hoverableText, 30);
drawHoveringText(lines, tooltipMouseX, tooltipMouseY, mc);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
}
private List<String> splitHoverText(String text, int maxLineLength) {
List<String> lines = new ArrayList<String>();
if (text == null || text.isEmpty())
return lines;
String normalized = text.replace("\\n", "\n");
String[] explicitLines = normalized.split("\\r?\\n", -1);
for (String line : explicitLines) {
if (line.isEmpty()) {
lines.add("");
continue;
}
lines.addAll(TextSplitter.splitText(line, maxLineLength));
}
return lines;
}
protected void drawHoveringText(List<String> textLines, int x, int y, Minecraft mc) {
if (mc.fontRenderer == null || textLines.isEmpty())
return;
@@ -251,12 +251,6 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
}
GL11.glPopMatrix();
// Draw hover texts in screen space (after scissor/translation are undone)
// so tooltips are not clipped and are positioned correctly
if (isMouseOver(mouseX, mouseY)) {
drawHoverTexts(mouseX, mouseY);
}
}
public void drawScreen(int mouseX, int mouseY, float partialTicks, int mouseScroll) {
@@ -293,16 +287,21 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
* Draws hover texts for buttons in screen space (called after GL scissor/translate are undone).
* Hover state was already computed during drawComponents with scroll-local coords.
*/
private void drawHoverTexts(int mouseX, int mouseY) {
public void drawHoverTexts(int mouseX, int mouseY) {
boolean subGui = parent.hasSubGui();
for (GuiNpcButton button : buttons.values()) {
if (!button.hoverableText.isEmpty()) {
button.drawHover(mouseX, mouseY, subGui);
}
}
// Label hover: convert screen mouse to scroll-local coords for hit testing
int localMouseX = mouseX - xPos;
int localMouseY = (int) (mouseY - yPos + scrollY);
for (GuiNpcTextField textField : textfields.values()) {
if (textField.hasHoverText()) {
textField.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui);
}
}
// Label hover: convert screen mouse to scroll-local coords for hit testing
for (GuiNpcLabel label : labels.values()) {
if (!label.hoverableText.isEmpty()) {
label.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui, fontRendererObj);
@@ -1,6 +1,6 @@
package noppes.npcs.client.gui.util;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
/**
* Callback for when a chained ability is saved from the config SubGui.
@@ -422,7 +422,7 @@ public class ModelMPM extends ModelNPCMale {
Minecraft.getMinecraft().entityRenderer.disableLightmap((double) 0);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, overlayData.getAlpha());
glColor(overlayData.getColor(), overlayData.getAlpha());
GL11.glDepthMask(!npc.isInvisible());
@@ -522,6 +522,14 @@ public class ModelMPM extends ModelNPCMale {
}
private static void glColor(int color, float alpha) {
float r = ((color >> 16) & 0xFF) / 255.0F;
float g = ((color >> 8) & 0xFF) / 255.0F;
float b = (color & 0xFF) / 255.0F;
GL11.glColor4f(r, g, b, alpha);
}
@Override
public void setRotationAngles(float limbSwing, float limbSwingAmount,
float ageInTicks, float netHeadYaw, float headPitch,
@@ -79,7 +79,7 @@ public class RenderCNPCPlayer extends RenderPlayer {
RenderHelper.disableStandardItemLighting();
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, overlayData.alpha);
glColor(overlayData.getColor(), overlayData.getAlpha());
GL11.glDepthMask(!player.isInvisible());
@@ -97,6 +97,14 @@ public class RenderCNPCPlayer extends RenderPlayer {
return true;
}
private static void glColor(int color, float alpha) {
float r = ((color >> 16) & 0xFF) / 255.0F;
float g = ((color >> 8) & 0xFF) / 255.0F;
float b = (color & 0xFF) / 255.0F;
GL11.glColor4f(r, g, b, alpha);
}
public void postRenderOverlay() {
GL11.glPopMatrix();
@@ -482,7 +482,7 @@ public class RenderNPCInterface extends RenderLiving {
Minecraft.getMinecraft().entityRenderer.disableLightmap((double) 0);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, overlayData.getAlpha());
glColor(overlayData.getColor(), overlayData.getAlpha());
GL11.glDepthMask(!npc.isInvisible());
@@ -521,6 +521,14 @@ public class RenderNPCInterface extends RenderLiving {
}
}
private static void glColor(int color, float alpha) {
float r = ((color >> 16) & 0xFF) / 255.0F;
float g = ((color >> 8) & 0xFF) / 255.0F;
float b = (color & 0xFF) / 255.0F;
GL11.glColor4f(r, g, b, alpha);
}
@Override
protected float handleRotationFloat(EntityLivingBase par1EntityLiving, float par2) {
EntityNPCInterface npc = (EntityNPCInterface) par1EntityLiving;
@@ -17,6 +17,7 @@ public class ConfigClient {
public final static String MODEL = "Model";
public final static String TEXTURE = "Texture";
public final static String HUD = "Hud";
public final static String RENDERING = "Rendering";
/**
@@ -52,6 +53,10 @@ public class ConfigClient {
public static Property HideEffectsBarProperty;
public static boolean HideEffectsBar = false;
// Rendering Properties
public static Property LowResExplosionProperty;
public static boolean LowResExplosion = false;
/**
* Questing Properties
**/
@@ -277,6 +282,14 @@ public class ConfigClient {
HideEffectsBarProperty = config.get(VISUAL, "Hide Effects Bar", false, "Hides CNPC+ Inventory Effects Bar");
HideEffectsBar = HideEffectsBarProperty.getBoolean(false);
LowResExplosionProperty = config.get(
RENDERING,
"Low Res Explosion",
false,
"Disables most Energy Explosion voxel rendering and keeps particle effects only."
);
LowResExplosion = LowResExplosionProperty.getBoolean(false);
DialogSpeedProperty = config.get(VISUAL, "Dialog Speed", true, "Only set for gradual dialogs");
DialogSpeed = DialogSpeedProperty.getInt(10);
@@ -10,8 +10,14 @@ public class ConfigEnergy {
public static Configuration config;
public final static String DOMES = "Domes";
public final static String EXPLOSIONS = "Explosions";
public static String[] DomeItemBlacklist;
/**
* Server-side toggle for energy projectile terrain destruction.
* Disabled by default to avoid block grief.
*/
public static boolean EnableEnergyExplosionBlockDamage;
public static void init(File configFile) {
config = new Configuration(configFile);
@@ -26,6 +32,13 @@ public class ConfigEnergy {
+ "Format: modid:itemname (e.g., minecraft:ender_pearl)"
);
EnableEnergyExplosionBlockDamage = config.getBoolean(
"Enable Energy Explosion Block Damage", EXPLOSIONS,
false,
"If true, explosive ENERGY projectile abilities can destroy terrain.\n"
+ "This is intended for server-side use and is disabled by default."
);
} catch (Exception e) {
FMLLog.log(Level.ERROR, e, "CustomNPC+ has had a problem loading its energy configuration");
} finally {
@@ -223,11 +223,14 @@ public class SpawnController implements INaturalSpawnsHandler {
}
public INaturalSpawn[] getSpawns(String biome) {
return getSpawnList(biome).toArray(new INaturalSpawn[]{});
List<SpawnData> biomeSpawns = getSpawnList(biome);
if (biomeSpawns == null)
return new INaturalSpawn[]{};
return biomeSpawns.toArray(new INaturalSpawn[]{});
}
public void addSpawn(INaturalSpawn spawn) {
((SpawnData) spawn).id = 0;
((SpawnData) spawn).id = -1;
this.saveSpawnData((SpawnData) spawn);
}
@@ -2,10 +2,10 @@ package noppes.npcs.controllers.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.ToggleEntry;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.data.entry.AbilityToggleEntry;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket;
@@ -90,6 +90,16 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
*/
private transient byte lastSyncedFlags = 0;
/**
* World time when the last ability was activated (for double-press cancel detection).
*/
private transient long lastAbilityActivationTime = -1;
/**
* Ticks after activation during which a second key press will cancel the ability.
*/
private static final int CANCEL_WINDOW_TICKS = 10;
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════════════
@@ -257,6 +267,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
currentAbility = null;
currentAbilityKey = null;
currentTarget = null;
lastAbilityActivationTime = -1;
syncAbilityStateClear(playerData.player);
}
@@ -272,6 +283,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
currentAbility = null;
currentAbilityKey = null;
currentTarget = null;
lastAbilityActivationTime = -1;
syncAbilityStateClear(playerData.player);
}
@@ -377,6 +389,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
currentAbilityKey = key;
currentTarget = null;
lastAbilityActivationTime = getWorldTime();
return startChain((ChainedAbility) action, null);
}
@@ -412,6 +425,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
currentAbility = ability;
currentAbilityKey = key;
currentTarget = null; // Players don't have auto-targets
lastAbilityActivationTime = getWorldTime();
ability.start(null);
if (ability.getPhase() == AbilityPhase.ACTIVE) {
@@ -661,6 +675,38 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
interruptCurrentAbility(null, 0);
}
/**
* Try to cancel the current ability via double-press.
* Only succeeds if within the cancel window and not in DAZED phase.
* Also handles cancellation during chain delay (between chain entries).
*
* @return true if the ability was cancelled
*/
public boolean tryCancelAbility() {
boolean hasExecutingAbility = currentAbility != null && currentAbility.isExecuting();
boolean isInChainDelay = currentChain != null && chainDelayRemaining > 0;
if (!hasExecutingAbility && !isInChainDelay) return false;
// Don't allow cancel during DAZED
if (hasExecutingAbility) {
AbilityPhase phase = currentAbility.getPhase();
if (phase == AbilityPhase.DAZED) return false;
if (phase != AbilityPhase.WINDUP && phase != AbilityPhase.ACTIVE
&& phase != AbilityPhase.BURST_DELAY) return false;
}
long worldTime = getWorldTime();
if (lastAbilityActivationTime < 0 || (worldTime - lastAbilityActivationTime) > CANCEL_WINDOW_TICKS) {
// Outside cancel window — update time so a quick follow-up press can cancel
lastAbilityActivationTime = worldTime;
return false;
}
cancelCurrentAbility();
return true;
}
// ═══════════════════════════════════════════════════════════════════
// ENTITY RECONSTRUCTION RESET
// ═══════════════════════════════════════════════════════════════════
@@ -700,6 +746,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
currentAbility = null;
currentAbilityKey = null;
currentTarget = null;
lastAbilityActivationTime = -1;
if (clearCooldowns) {
cooldownEndTime = 0;
@@ -759,6 +806,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (currentAbility == null || !currentAbility.isExecuting()) {
return amount;
}
if (currentAbility.isInvulnerableForCurrentPhase()) {
return 0;
}
net.minecraft.entity.Entity sourceEntity = source.getEntity();
EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null;
@@ -890,6 +940,9 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
if (wasFlyingAtLock) {
flags |= PlayerAbilityStatePacket.FLAG_WAS_FLYING_AT_LOCK;
}
if (currentAbility.getPhase() == AbilityPhase.ACTIVE) {
flags |= PlayerAbilityStatePacket.FLAG_ACTIVE_PHASE;
}
return flags;
}
@@ -947,7 +1000,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
// Active toggles (compound format with state)
NBTTagList toggleList = new NBTTagList();
for (Map.Entry<String, ToggleEntry> entry : activeToggles.entrySet()) {
for (Map.Entry<String, AbilityToggleEntry> entry : activeToggles.entrySet()) {
NBTTagCompound toggleNbt = new NBTTagCompound();
toggleNbt.setString("Key", entry.getKey());
toggleNbt.setInteger("State", entry.getValue().getState());
@@ -2,7 +2,6 @@ package noppes.npcs.controllers.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -10,8 +10,10 @@ public class SkinOverlay implements ISkinOverlay {
public boolean glow = true;
public boolean blend = true;
public float alpha = 1.0F;
public float size = 1.0F;
public int color = 0xFFFFFF;
public float speedX = 0.0F;
public float speedY = 0.0F;
@@ -78,6 +80,15 @@ public class SkinOverlay implements ISkinOverlay {
return size;
}
public void setColor(int color) {
this.color = Math.max(0, color);
this.updateClient();
}
public int getColor() {
return color;
}
public void setTextureScale(float scaleX, float scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
@@ -131,6 +142,11 @@ public class SkinOverlay implements ISkinOverlay {
this.blend = compound.getBoolean("SkinOverlayBlend");
this.alpha = compound.getFloat("SkinOverlayAlpha");
this.size = compound.getFloat("SkinOverlaySize");
if(compound.hasKey("SkinOverlayColor")){
this.color = compound.getInteger("SkinOverlayColor");
} else {
this.color = 0xFFFFFF;
}
this.speedX = compound.getFloat("SkinOverlaySpeedX");
this.speedY = compound.getFloat("SkinOverlaySpeedY");
this.scaleX = compound.getFloat("SkinOverlayScaleX");
@@ -146,6 +162,7 @@ public class SkinOverlay implements ISkinOverlay {
compound.setBoolean("SkinOverlayBlend", this.getBlend());
compound.setFloat("SkinOverlayAlpha", this.getAlpha());
compound.setFloat("SkinOverlaySize", this.getSize());
compound.setInteger("SkinOverlayColor", this.getColor());
compound.setFloat("SkinOverlaySpeedX", this.getSpeedX());
compound.setFloat("SkinOverlaySpeedY", this.getSpeedY());
compound.setFloat("SkinOverlayScaleX", this.getTextureScaleX());
@@ -21,6 +21,10 @@ import java.util.Map;
import java.util.Set;
public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
public static final int DESPAWN_FORCE_NATURAL = INaturalSpawn.DESPAWN_FORCE_NATURAL;
public static final int DESPAWN_PRESERVE_TEMPLATE = INaturalSpawn.DESPAWN_PRESERVE_TEMPLATE;
public static final int DESPAWN_FORCE_PERSISTENT = INaturalSpawn.DESPAWN_FORCE_PERSISTENT;
public List<String> biomes = new ArrayList<>();
public HashSet<Integer> dimensions = new HashSet<>();
public int id = -1;
@@ -35,6 +39,11 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
public int spawnHeightMin;
public int spawnHeightMax = 100;
public int maxAlive = 0;
public int cooldownTicks = 0;
public int attemptsPerCycle = 1;
public int playerMinDistance = 24;
public int despawnMode = DESPAWN_FORCE_NATURAL;
public SpawnData() {
super(10);
@@ -74,6 +83,19 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
} else {
spawnHeightMax = compound.getInteger("HeightMax");
}
maxAlive = compound.hasKey("MaxAlive") ? Math.max(0, compound.getInteger("MaxAlive")) : 0;
cooldownTicks = compound.hasKey("CooldownTicks") ? Math.max(0, compound.getInteger("CooldownTicks")) : 0;
attemptsPerCycle = compound.hasKey("AttemptsPerCycle") ? Math.max(1, compound.getInteger("AttemptsPerCycle")) : 1;
playerMinDistance = compound.hasKey("PlayerMinDistance") ? Math.max(0, compound.getInteger("PlayerMinDistance")) : 24;
if (compound.hasKey("DespawnMode")) {
despawnMode = compound.getInteger("DespawnMode");
} else {
despawnMode = DESPAWN_FORCE_NATURAL;
}
if (despawnMode < DESPAWN_FORCE_NATURAL || despawnMode > DESPAWN_FORCE_PERSISTENT) {
despawnMode = DESPAWN_FORCE_NATURAL;
}
}
public NBTTagCompound writeNBT(NBTTagCompound compound) {
@@ -98,6 +120,11 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
compound.setInteger("HeightMin", spawnHeightMin);
compound.setInteger("HeightMax", spawnHeightMax);
compound.setInteger("MaxAlive", maxAlive);
compound.setInteger("CooldownTicks", cooldownTicks);
compound.setInteger("AttemptsPerCycle", attemptsPerCycle);
compound.setInteger("PlayerMinDistance", playerMinDistance);
compound.setInteger("DespawnMode", despawnMode);
return compound;
}
@@ -204,4 +231,46 @@ public class SpawnData extends WeightedRandom.Item implements INaturalSpawn {
public void setBiomes(String[] biomes) {
this.biomes = new ArrayList<>(Arrays.asList(biomes));
}
public void setMaxAlive(int maxAlive) {
this.maxAlive = Math.max(0, maxAlive);
}
public int getMaxAlive() {
return this.maxAlive;
}
public void setCooldownTicks(int ticks) {
this.cooldownTicks = Math.max(0, ticks);
}
public int getCooldownTicks() {
return this.cooldownTicks;
}
public void setAttemptsPerCycle(int attempts) {
this.attemptsPerCycle = Math.max(1, attempts);
}
public int getAttemptsPerCycle() {
return this.attemptsPerCycle;
}
public void setPlayerMinDistance(int distance) {
this.playerMinDistance = Math.max(0, distance);
}
public int getPlayerMinDistance() {
return this.playerMinDistance;
}
public void setDespawnMode(int mode) {
if (mode < DESPAWN_FORCE_NATURAL || mode > DESPAWN_FORCE_PERSISTENT)
mode = DESPAWN_FORCE_NATURAL;
this.despawnMode = mode;
}
public int getDespawnMode() {
return this.despawnMode;
}
}
@@ -62,26 +62,27 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
} else if (heightOffGround > this.ais.flyHeightLimit) {
aboveLimit = true;
}
if (aboveLimit && this.ais.hasFlyLimit || (heightOffGround < Math.ceil(this.height) && this.motionY == 0)) {
if (aboveLimit && this.ais.hasFlyLimit) {
this.flyLimitAllow = false;
if (!this.getNavigator().noPath() && this.motionY > 0) {
if (this.motionY > 0) {
this.motionY = 0;
} else {
setNpcFlyingState(false);
super.moveEntityWithHeading(p_70612_1_, p_70612_2_);
return;
}
} else if (heightOffGround < Math.ceil(this.height) && this.motionY == 0) {
this.flyLimitAllow = false;
setNpcFlyingState(false);
super.moveEntityWithHeading(p_70612_1_, p_70612_2_);
return;
}
this.flyLimitAllow = true;
setNpcFlyingState(true);
double d3 = this.motionY;
super.moveEntityWithHeading(p_70612_1_, p_70612_2_);
this.motionY = d3;
double desiredMotionY = this.motionY;
if (this.getNavigator().noPath()) {
this.motionY = -Math.abs(this.ais.flyGravity);
desiredMotionY = -Math.abs(this.ais.flyGravity);
}
this.motionY = desiredMotionY;
super.moveEntityWithHeading(p_70612_1_, p_70612_2_);
this.motionY = desiredMotionY;
this.updateLimbSwing();
}
@@ -90,11 +91,13 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
this.prevLimbSwingAmount = this.limbSwingAmount;
double distanceX = this.posX - this.prevPosX;
double distanceZ = this.posZ - this.prevPosZ;
float distance = MathHelper.sqrt_double(distanceX * distanceX + distanceZ * distanceZ) * 4.0F;
float distance = MathHelper.sqrt_double(distanceX * distanceX + distanceZ * distanceZ);
float swingScale = this.getNavigator().noPath() ? 0.35F : 0.9F;
distance *= swingScale;
if (distance > 1.0F) {
distance = 1.0F;
}
this.limbSwingAmount += (distance - this.limbSwingAmount) * 0.4F;
this.limbSwingAmount += (distance - this.limbSwingAmount) * 0.18F;
this.limbSwing += this.limbSwingAmount;
}
@@ -120,15 +123,16 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
} else if (heightOffGround > this.ais.flyHeightLimit) {
aboveLimit = true;
}
if (aboveLimit && this.ais.hasFlyLimit || (heightOffGround < Math.ceil(this.height) && this.motionY == 0)) {
if (aboveLimit && this.ais.hasFlyLimit) {
this.flyLimitAllow = false;
if (!this.getNavigator().noPath() && this.motionY > 0) {
if (this.motionY > 0) {
this.motionY = 0;
} else {
setNpcFlyingState(false);
super.performMountedMovement(strafe, forward, moveSpeed);
return;
}
} else if (heightOffGround < Math.ceil(this.height) && this.motionY == 0) {
this.flyLimitAllow = false;
setNpcFlyingState(false);
super.performMountedMovement(strafe, forward, moveSpeed);
return;
}
this.flyLimitAllow = true;
setNpcFlyingState(true);
@@ -138,13 +142,13 @@ public abstract class EntityNPCFlying extends EntityNPCInterface {
return;
}
double d3 = this.motionY;
super.performMountedMovement(strafe, forward, moveSpeed);
this.motionY = d3;
double desiredMotionY = this.motionY;
if (this.getNavigator().noPath()) {
this.motionY = -Math.abs(this.ais.flyGravity);
desiredMotionY = -Math.abs(this.ais.flyGravity);
}
this.motionY = desiredMotionY;
super.performMountedMovement(strafe, forward, moveSpeed);
this.motionY = desiredMotionY;
this.updateLimbSwing();
}
@@ -231,8 +231,8 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
public FlyingMoveHelper flyMoveHelper = new FlyingMoveHelper(this);
public PathNavigate flyNavigator = new PathNavigateFlying(this, worldObj);
@SideOnly(Side.CLIENT)
public int immediateSpawnDataFixAttempts = 0;
// For Client-Side Use Only
public int clientFixAttempts = 0;
public EntityNPCInterface(World world) {
super(world);
@@ -255,7 +255,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
setFaction(faction.id);
setSize(1, 1);
this.updateTasks();
this.func_110163_bv();
this.syncDespawnPersistence();
if (!this.isRemote() && this.wrappedNPC == null) {
this.wrappedNPC = new ScriptNpc<>(this);
@@ -659,6 +659,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
if (damagesource.damageType != null && damagesource.damageType.equals("outOfWorld") && isKilled()) {
reset();
}
if (this.abilities != null && this.abilities.isCurrentAbilityInvulnerable()) {
return false;
}
// Check for custom weapon attack speed - bypass immunity if enough time has passed
Entity sourceEntity = damagesource.getEntity();
@@ -1200,7 +1203,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(ConfigMain.NpcNavRange);
this.updateTasks();
this.func_110163_bv();
this.syncDespawnPersistence();
}
@Override
@@ -1401,6 +1404,26 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
field_20062_v += d1 * 0.25D;
}
@Override
protected void despawnEntity() {
syncDespawnPersistence();
super.despawnEntity();
}
public void syncDespawnPersistence() {
if (stats == null) {
if (!this.persistenceRequired) {
this.func_110163_bv();
}
return;
}
if (stats.canDespawn) {
this.persistenceRequired = false;
} else if (!this.persistenceRequired) {
this.func_110163_bv();
}
}
@Override
protected boolean canDespawn() {
return stats.canDespawn;
@@ -1803,6 +1826,11 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
compound.setBoolean("DeadBody", stats.hideKilledBody);
compound.setInteger("StandingState", ais.standingType.ordinal());
compound.setInteger("MovingState", ais.movingType.ordinal());
compound.setInteger("MovingType", ais.movementType);
compound.setDouble("FlySpeed", ais.flySpeed);
compound.setDouble("FlyGravity", ais.flyGravity);
compound.setBoolean("HasFlyLimit", ais.hasFlyLimit);
compound.setInteger("FlyHeightLimit", ais.flyHeightLimit);
compound.setInteger("Orientation", ais.orientation);
compound.setFloat("OffsetY", ais.bodyOffsetY);
compound.setInteger("Role", advanced.role.ordinal());
@@ -1834,22 +1862,38 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
try {
readSpawnData(ByteBufUtils.readNBT(buf));
} catch (IOException e) {
RequestProperSpawnData.reportMissingData(this);
if (this.worldObj != null && this.worldObj.isRemote) {
RequestProperSpawnData.reportMissingData(this);
}
}
}
public void readSpawnData(NBTTagCompound compound) {
if ((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))) {
RequestProperSpawnData.reportMissingData(this);
return;
if (this.worldObj != null && this.worldObj.isRemote) {
if(requestClientFix(compound))
return;
}
immediateSpawnDataFixAttempts = 0;
stats.maxHealth = compound.getDouble("MaxHealth");
ais.setWalkingSpeed(compound.getInteger("Speed"));
stats.hideKilledBody = compound.getBoolean("DeadBody");
ais.standingType = EnumStandingType.values()[compound.getInteger("StandingState") % EnumStandingType.values().length];
ais.movingType = EnumMovingType.values()[compound.getInteger("MovingState") % EnumMovingType.values().length];
if (compound.hasKey("MovingType", Constants.NBT.TAG_INT)) {
ais.movementType = compound.getInteger("MovingType");
}
if (compound.hasKey("FlySpeed", Constants.NBT.TAG_DOUBLE)) {
ais.flySpeed = compound.getDouble("FlySpeed");
}
if (compound.hasKey("FlyGravity", Constants.NBT.TAG_DOUBLE)) {
ais.flyGravity = compound.getDouble("FlyGravity");
}
if (compound.hasKey("HasFlyLimit", Constants.NBT.TAG_BYTE)) {
ais.hasFlyLimit = compound.getBoolean("HasFlyLimit");
}
if (compound.hasKey("FlyHeightLimit", Constants.NBT.TAG_INT)) {
ais.flyHeightLimit = compound.getInteger("FlyHeightLimit");
}
ais.orientation = compound.getInteger("Orientation");
ais.bodyOffsetY = compound.getFloat("OffsetY");
@@ -1922,6 +1966,15 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
}
}
public boolean requestClientFix(NBTTagCompound compound){
if((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))){
RequestProperSpawnData.reportMissingData(this);
return true;
}
clientFixAttempts = 0;
return false;
}
public boolean canBreatheUnderwater() {
return stats.drowningType != 1;
}
@@ -1,13 +1,13 @@
package noppes.npcs.items;
import kamkeel.npcs.controllers.data.ability.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.EnergyAnchorData;
import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.EnergyTrajectoryData;
import kamkeel.npcs.controllers.data.ability.enums.AnchorPoint;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyAnchorData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyCombatData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyDisplayData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyHomingData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLifespanData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyLightningData;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyTrajectoryData;
import kamkeel.npcs.entity.EntityAbilityOrb;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
@@ -1,9 +1,11 @@
package noppes.npcs.mixin;
import kamkeel.npcs.util.AttributeItemUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.player.GuiAuctionInterface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
@@ -28,9 +30,14 @@ public abstract class MixinItemStack {
@Inject(method = "getTooltip", at = @At("TAIL"), cancellable = true)
public void getAttributeTooltip(EntityPlayer player, boolean advanced, CallbackInfoReturnable<List<String>> cir) {
boolean override = false;
if (Minecraft.getMinecraft().currentScreen instanceof GuiAuctionInterface) {
override = true;
}
List<String> tooltip = cir.getReturnValue();
if (hasTagCompound() && getTagCompound().hasKey(TAG_RPGCORE)) {
cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound()));
cir.setReturnValue(AttributeItemUtil.getToolTip(tooltip, getTagCompound(), override));
}
}
}
@@ -86,6 +86,9 @@ public abstract class MixinModelRenderer {
float prevAngleX = this.rotateAngleX;
float prevAngleY = this.rotateAngleY;
float prevAngleZ = this.rotateAngleZ;
float prevOffsetX = this.offsetX;
float prevOffsetY = this.offsetY;
float prevOffsetZ = this.offsetZ;
boolean changedAngles = false;
try {
@@ -149,6 +152,11 @@ public abstract class MixinModelRenderer {
GL11.glPopMatrix();
}
// Mirror vanilla ModelRenderer behavior: always undo offset translation.
// Without this, models that animate via offsetX/Y/Z (e.g. witch nose while drinking)
// leak transforms into subsequent renders.
GL11.glTranslatef(-this.offsetX, -this.offsetY, -this.offsetZ);
if (changedAngles) {
this.rotationPointX = prevPointX;
this.rotationPointY = prevPointY;
@@ -156,6 +164,9 @@ public abstract class MixinModelRenderer {
this.rotateAngleX = prevAngleX;
this.rotateAngleY = prevAngleY;
this.rotateAngleZ = prevAngleZ;
this.offsetX = prevOffsetX;
this.offsetY = prevOffsetY;
this.offsetZ = prevOffsetZ;
}
}
}
+16 -8
View File
@@ -9,9 +9,13 @@ import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.TelegraphController;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityDome;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityPanel;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.block.Block;
import net.minecraft.command.CommandHandler;
import net.minecraft.entity.Entity;
@@ -126,9 +130,13 @@ import noppes.npcs.scripted.entity.ScriptArrow;
import noppes.npcs.scripted.entity.ScriptDBCPlayer;
import noppes.npcs.scripted.entity.ScriptEnergyBeam;
import noppes.npcs.scripted.entity.ScriptEnergyDisc;
import noppes.npcs.scripted.entity.ScriptEnergyDome;
import noppes.npcs.scripted.entity.ScriptEnergyLaser;
import noppes.npcs.scripted.entity.ScriptEnergyOrb;
import noppes.npcs.scripted.entity.ScriptEnergyPanel;
import noppes.npcs.scripted.entity.ScriptEnergyProjectile;
import noppes.npcs.scripted.entity.ScriptEnergySlicer;
import noppes.npcs.scripted.entity.ScriptEnergySweeper;
import noppes.npcs.scripted.entity.ScriptEntity;
import noppes.npcs.scripted.entity.ScriptEntityItem;
import noppes.npcs.scripted.entity.ScriptFishHook;
@@ -472,16 +480,16 @@ public class NpcAPI extends AbstractNpcAPI {
data = new ScriptEntityData(new ScriptEnergyDisc<>((EntityAbilityDisc) entity));
else if (entity instanceof EntityAbilityLaser)
data = new ScriptEntityData(new ScriptEnergyLaser<>((EntityAbilityLaser) entity));
else if (entity instanceof kamkeel.npcs.entity.EntityEnergySlicer)
data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergySlicer<>((kamkeel.npcs.entity.EntityEnergySlicer) entity));
else if (entity instanceof EntityEnergySlicer)
data = new ScriptEntityData(new ScriptEnergySlicer<>((EntityEnergySlicer) entity));
else if (entity instanceof EntityEnergyProjectile)
data = new ScriptEntityData(new ScriptEnergyProjectile((EntityEnergyProjectile) entity));
else if (entity instanceof kamkeel.npcs.entity.EntityEnergyDome)
data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergyDome<>((kamkeel.npcs.entity.EntityEnergyDome) entity));
else if (entity instanceof kamkeel.npcs.entity.EntityEnergyPanel)
data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergyPanel<>((kamkeel.npcs.entity.EntityEnergyPanel) entity));
else if (entity instanceof kamkeel.npcs.entity.EntityAbilitySweeper)
data = new ScriptEntityData(new noppes.npcs.scripted.entity.ScriptEnergySweeper<>((kamkeel.npcs.entity.EntityAbilitySweeper) entity));
else if (entity instanceof EntityAbilityDome)
data = new ScriptEntityData(new ScriptEnergyDome<>((EntityAbilityDome) entity));
else if (entity instanceof EntityAbilityPanel)
data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityAbilityPanel) entity));
else if (entity instanceof EntityAbilitySweeper)
data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityAbilitySweeper) entity));
else
data = new ScriptEntityData(new ScriptEntity<>(entity));
entity.registerExtendedProperties("ScriptedObject", data);
@@ -789,7 +789,7 @@ public class ScriptDBCPlayer<T extends EntityPlayerMP> extends ScriptPlayer<T> i
}
public void setRace(byte race) {
if (race < 0 || race > 1)
if (race < 0 || race > 5)
return;
player.getEntityData().getCompoundTag("PlayerPersisted").setByte("jrmcRace", race);
@@ -1,15 +1,15 @@
package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityAbilityBarrier;
import kamkeel.npcs.entity.EntityAbilityDome;
import noppes.npcs.api.entity.IEnergyBarrier;
import noppes.npcs.scripted.constants.EntityType;
/**
* Base script wrapper for energy barrier entities (Dome, Panel).
* All shared methods delegate directly to EntityEnergyBarrier base.
* All shared methods delegate directly to EntityAbilityBarrier base.
*/
public class ScriptEnergyBarrier<T extends EntityEnergyBarrier> extends ScriptEnergyAbility<T> implements IEnergyBarrier {
public class ScriptEnergyBarrier<T extends EntityAbilityBarrier> extends ScriptEnergyAbility<T> implements IEnergyBarrier {
public ScriptEnergyBarrier(T entity) {
super(entity);
@@ -89,6 +89,14 @@ public class ScriptEnergyBarrier<T extends EntityEnergyBarrier> extends ScriptEn
entity.getBarrierData().defaultMultiplier = multiplier;
}
public boolean isSolid() {
return entity.getBarrierData().solid;
}
public void setSolid(boolean solid) {
entity.getBarrierData().solid = solid;
}
public boolean isKnockbackEnabled() {
return entity.getBarrierData().knockbackEnabled;
}
@@ -105,15 +113,31 @@ public class ScriptEnergyBarrier<T extends EntityEnergyBarrier> extends ScriptEn
entity.getBarrierData().knockbackStrength = strength;
}
public int getKnockbackTarget() {
return entity.getBarrierData().knockbackTarget;
public boolean isAbsorbing() {
return entity.getBarrierData().absorbing;
}
public void setKnockbackTarget(int target) {
entity.getBarrierData().knockbackTarget = target;
public void setAbsorbing(boolean absorbing) {
entity.getBarrierData().absorbing = absorbing;
}
public boolean isReflect() {
return entity.getBarrierData().reflect;
}
public void setReflect(boolean reflect) {
entity.getBarrierData().reflect = reflect;
}
public float getReflectStrengthPct() {
return entity.getBarrierData().reflectStrengthPct;
}
public void setReflectStrengthPct(float strengthPct) {
entity.getBarrierData().setReflectStrengthPct(strengthPct);
}
public int getBarrierType() {
return entity instanceof EntityEnergyDome ? 0 : 1;
return entity instanceof EntityAbilityDome ? 0 : 1;
}
}
@@ -1,10 +1,10 @@
package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityAbilityDome;
import noppes.npcs.api.entity.IEnergyDome;
import noppes.npcs.scripted.constants.EntityType;
public class ScriptEnergyDome<T extends EntityEnergyDome> extends ScriptEnergyBarrier<T> implements IEnergyDome {
public class ScriptEnergyDome<T extends EntityAbilityDome> extends ScriptEnergyBarrier<T> implements IEnergyDome {
public ScriptEnergyDome(T entity) {
super(entity);
@@ -1,10 +1,10 @@
package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityAbilityPanel;
import noppes.npcs.api.entity.IEnergyPanel;
import noppes.npcs.scripted.constants.EntityType;
public class ScriptEnergyPanel<T extends EntityEnergyPanel> extends ScriptEnergyBarrier<T> implements IEnergyPanel {
public class ScriptEnergyPanel<T extends EntityAbilityPanel> extends ScriptEnergyBarrier<T> implements IEnergyPanel {
public ScriptEnergyPanel(T entity) {
super(entity);
@@ -52,6 +52,6 @@ public class ScriptEnergyPanel<T extends EntityEnergyPanel> extends ScriptEnergy
}
public boolean isLaunched() {
return entity.getMode() == EntityEnergyPanel.PanelMode.LAUNCHED;
return entity.getMode() == EntityAbilityPanel.PanelMode.LAUNCHED;
}
}
@@ -161,6 +161,30 @@ public class ScriptEnergyProjectile<T extends EntityEnergyProjectile> extends Sc
entity.setExplosionDamageFalloff(falloff);
}
public int getHitType() {
return entity.getHitType();
}
public void setHitType(int hitType) {
entity.setHitType(hitType);
}
public int getMultiHitDelayTicks() {
return entity.getMultiHitDelayTicks();
}
public void setMultiHitDelayTicks(int delayTicks) {
entity.setMultiHitDelayTicks(delayTicks);
}
public int getMaxHits() {
return entity.getMaxHits();
}
public void setMaxHits(int maxHits) {
entity.setMaxHits(maxHits);
}
// ==================== MOVEMENT ====================
public float getSpeed() {
@@ -45,14 +45,6 @@ public class ScriptEnergySlicer<T extends EntityEnergySlicer> extends ScriptEner
entity.setSliceThickness(thickness);
}
public boolean isPiercing() {
return entity.isPiercing();
}
public void setPiercing(boolean piercing) {
entity.setPiercing(piercing);
}
// ==================== FIRE ====================
@Override
@@ -1109,6 +1109,7 @@ public class ScriptNpc<T extends EntityNPCInterface> extends ScriptLiving<T> imp
public void setNaturallyDespawns(boolean canDespawn) {
npc.stats.canDespawn = canDespawn;
npc.stats.playerSetCanDespawn = canDespawn;
npc.syncDespawnPersistence();
}
public boolean spawnedFromSoulStone() {