Merge remote-tracking branch 'origin/syntax-highlighter-unified' into syntax-highlighter-unified

This commit is contained in:
bigguy345 committed 2026-03-04 12:54:29 +02:00
commit 2821b5da09
92 files changed
+3051 -344

No files matched your search

@@ -1079,6 +1079,7 @@ public abstract class AbstractDataAbilities {
rollChainCooldown(currentChain);
interruptCooldownRolled = true;
fireChainInterruptEvent(currentChain, chainEntryIndex, getTarget(), source, damage);
currentChain.clearInstanceScript();
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -1138,6 +1139,7 @@ public abstract class AbstractDataAbilities {
// Roll cooldown
if (currentChain != null) {
rollChainCooldown(currentChain);
currentChain.clearInstanceScript();
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -1336,6 +1338,7 @@ public abstract class AbstractDataAbilities {
if (currentChain != null) {
rollChainCooldown(currentChain);
fireChainCompleteEvent(currentChain, chainEntryIndex, getTarget());
currentChain.clearInstanceScript();
}
currentChain = null;
chainEntryIndex = -1;
+1 -1
View File
@@ -124,7 +124,7 @@ import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta12")
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta13")
public class CustomNpcs {
@SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")
+71 -17
View File
@@ -4,6 +4,7 @@ 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.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.enums.RotationMode;
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;
@@ -87,6 +88,7 @@ public class DataAbilities extends AbstractDataAbilities {
*/
private transient boolean hitScanActive = false;
private transient EntityLivingBase hitScanTarget = null;
private transient float currentTrackDelay = 0;
/**
* Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15
@@ -227,9 +229,19 @@ public class DataAbilities extends AbstractDataAbilities {
protected void onPostPhaseTick(Ability ability, EntityLivingBase target) {
// Update hit scan state - actual facing is deferred to applyRotationControl()
// which runs AFTER super.onLivingUpdate() to override AI look helper
if (ability != null && ability.isExecuting()
&& ability.isHitScanForCurrentPhase() && target != null) {
enableHitScan(target);
if (ability != null && ability.isExecuting() && target != null) {
if (ability.isHitScanForCurrentPhase()) {
enableHitScan(target, ability.getTrackDelay());
} else {
// Release hit scan if it was previously active
if (hitScanActive) {
releaseRotationControl();
}
// FREE mode: use AI look helper during ability execution since combat AI may not run
if (ability.getRotationMode() == RotationMode.FREE) {
npc.getLookHelper().setLookPositionWithEntity(target, 30.0F, 30.0F);
}
}
} else if (hitScanActive) {
releaseRotationControl();
}
@@ -287,6 +299,7 @@ public class DataAbilities extends AbstractDataAbilities {
if (positionLocked) releaseLockedPosition();
}
// Clear chain and concurrent state
if (currentChain != null) currentChain.clearInstanceScript();
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -576,6 +589,7 @@ public class DataAbilities extends AbstractDataAbilities {
lastTarget = null;
}
// Also clear chain state
if (currentChain != null) currentChain.clearInstanceScript();
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -867,34 +881,74 @@ public class DataAbilities extends AbstractDataAbilities {
/**
* Enable hit scan tracking for the given target.
*/
private void enableHitScan(EntityLivingBase target) {
private void enableHitScan(EntityLivingBase target, float trackDelay) {
if (!hitScanActive) {
hitScanActive = true;
npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG);
}
hitScanTarget = target;
currentTrackDelay = trackDelay;
}
/**
* Snap the NPC to face the target instantly.
* Face the target with optional track delay.
* When trackDelay <= 0, snaps instantly (legacy behavior).
* When trackDelay > 0, lerps toward the target each tick.
*/
private void faceTarget(EntityLivingBase target) {
private void faceTarget(EntityLivingBase target, float trackDelay) {
double dx = target.posX - npc.posX;
double dz = target.posZ - npc.posZ;
double dy = (target.posY + target.getEyeHeight() * 0.5) - (npc.posY + npc.getEyeHeight());
double distXZ = Math.sqrt(dx * dx + dz * dz);
float yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI);
float pitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI);
float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI);
float targetPitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI);
npc.rotationYaw = yaw;
npc.rotationYawHead = yaw;
npc.renderYawOffset = yaw;
npc.rotationPitch = pitch;
npc.prevRotationYaw = yaw;
npc.prevRotationYawHead = yaw;
npc.prevRenderYawOffset = yaw;
npc.prevRotationPitch = pitch;
if (trackDelay <= 0) {
// Instant snap (legacy behavior)
npc.rotationYaw = targetYaw;
npc.rotationYawHead = targetYaw;
npc.renderYawOffset = targetYaw;
npc.rotationPitch = targetPitch;
npc.prevRotationYaw = targetYaw;
npc.prevRotationYawHead = targetYaw;
npc.prevRenderYawOffset = targetYaw;
npc.prevRotationPitch = targetPitch;
} else {
float lerpFactor = 1.0f / (1.0f + trackDelay);
// Wrap yaw difference to [-180, 180] for correct interpolation
float yawDiff = wrapAngle(targetYaw - npc.rotationYawHead);
float pitchDiff = targetPitch - npc.rotationPitch;
float newYaw = npc.rotationYawHead + yawDiff * lerpFactor;
float newPitch = npc.rotationPitch + pitchDiff * lerpFactor;
// Set prev to current before updating (for smooth client interpolation)
npc.prevRotationYaw = npc.rotationYaw;
npc.prevRotationYawHead = npc.rotationYawHead;
npc.prevRenderYawOffset = npc.renderYawOffset;
npc.prevRotationPitch = npc.rotationPitch;
npc.rotationYaw = newYaw;
npc.rotationYawHead = newYaw;
npc.renderYawOffset = newYaw;
npc.rotationPitch = newPitch;
}
}
/**
* Snap the NPC to face the target instantly (no delay).
*/
private void faceTarget(EntityLivingBase target) {
faceTarget(target, 0);
}
private static float wrapAngle(float angle) {
angle = angle % 360.0f;
if (angle >= 180.0f) angle -= 360.0f;
if (angle < -180.0f) angle += 360.0f;
return angle;
}
/**
@@ -922,7 +976,7 @@ public class DataAbilities extends AbstractDataAbilities {
// Server: apply the appropriate rotation
if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) {
faceTarget(hitScanTarget);
faceTarget(hitScanTarget, currentTrackDelay);
} else if (rotationLocked) {
npc.rotationYaw = lockedYaw;
npc.rotationYawHead = lockedYawHead;
+4 -2
View File
@@ -887,7 +887,8 @@ public class EventHooks {
IAbilityEvent abilityEvent = (IAbilityEvent) event;
// 1. Internal ability script (fires for ALL — both NPC and Player)
AbilityScript abScript = ability.getScriptHandler();
// Use per-instance script so each execution has isolated variable state
AbilityScript abScript = ability.getOrCreateInstanceScript();
if (abScript != null) {
abScript.callScript(abilityEvent.getHookName(), event);
}
@@ -916,7 +917,8 @@ public class EventHooks {
IChainEvent chainEvent = (IChainEvent) event;
// 1. Internal chain script (fires first)
ChainedAbilityScript chainScript = chain.getScriptHandler();
// Use per-instance script so each execution has isolated variable state
ChainedAbilityScript chainScript = chain.getOrCreateInstanceScript();
if (chainScript != null) {
chainScript.callScript(chainEvent.getHookName(), event);
}
@@ -794,11 +794,10 @@ public class NoppesUtilServer {
HashMap<String, Integer> map = new HashMap<String, Integer>();
AbilityController controller = AbilityController.Instance;
if (controller != null) {
int index = 0;
for (String name : controller.getAbilityNames()) {
Ability ability = controller.getAbility(name);
if (ability != null) {
map.put(ability.getName(), index++);
map.put(ability.getName(), ability.getAllowedBy().ordinal());
}
}
}
@@ -809,11 +808,10 @@ public class NoppesUtilServer {
HashMap<String, Integer> map = new HashMap<String, Integer>();
AbilityController controller = AbilityController.Instance;
if (controller != null) {
int index = 0;
for (String name : controller.getCustomAbilityNames()) {
Ability ability = controller.getCustomAbility(name);
if (ability == null || !ability.getAllowedBy().allowsNpc()) continue;
map.put(name, index++);
if (ability == null) continue;
map.put(name, ability.getAllowedBy().ordinal());
}
}
sendScrollData(player, map, EnumScrollData.CUSTOM_ABILITIES);
@@ -8,6 +8,7 @@ import cpw.mods.fml.relauncher.Side;
import kamkeel.npcs.addon.DBCAddon;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.tracker.PlayerAttributeTracker;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCounter;
@@ -623,8 +624,21 @@ public class ScriptPlayerEventHandler {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.source.getEntity());
float attackAmount = event.ammount;
if (ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable())
attackAmount = AttributeAttackUtil.calculateOutgoing((EntityPlayer) event.source.getEntity(), attackAmount);
AttributeAttackUtil.lastAttackCritted = null;
if (ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable()) {
EntityPlayer attackPlayer = (EntityPlayer) event.source.getEntity();
attackAmount = AttributeAttackUtil.calculateOutgoing(attackPlayer, attackAmount);
// For vanilla/modded mob targets, roll crit once and store for LivingHurtEvent
if (!(event.entityLiving instanceof EntityPlayerMP) && !(event.entityLiving instanceof EntityNPCInterface)) {
PlayerAttributeTracker tracker = AttributeController.getTracker(attackPlayer);
if (AttributeAttackUtil.rollCrit(tracker)) {
AttributeAttackUtil.lastAttackCritted = true;
attackAmount = AttributeAttackUtil.applyCritDamage(attackAmount, tracker);
} else {
AttributeAttackUtil.lastAttackCritted = false;
}
}
}
noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent pevent1 = new noppes.npcs.scripted.event.player.PlayerEvent.AttackEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.source.getEntity()), event.entityLiving, attackAmount, event.source);
cancel = cancel || EventHooks.onPlayerAttack(handler, pevent1);
@@ -663,6 +677,15 @@ public class ScriptPlayerEventHandler {
event.ammount = AttributeAttackUtil.calculateDamagePlayerToPlayer((EntityPlayer) source, (EntityPlayer) event.entityLiving, event.ammount);
} else if (!(event.entityLiving instanceof EntityNPCInterface) && source instanceof EntityPlayer) {
event.ammount = AttributeAttackUtil.calculateOutgoing((EntityPlayer) source, event.ammount);
if (AttributeAttackUtil.lastAttackCritted != null) {
// Use the crit decision from LivingAttackEvent
if (AttributeAttackUtil.lastAttackCritted)
event.ammount = AttributeAttackUtil.applyCritDamage(event.ammount, AttributeController.getTracker((EntityPlayer) source));
AttributeAttackUtil.lastAttackCritted = null;
} else {
// Fallback: roll independently (no preceding LivingAttackEvent)
event.ammount = AttributeAttackUtil.applyCrit(event.ammount, AttributeController.getTracker((EntityPlayer) source));
}
}
}
@@ -188,8 +188,11 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler, ISc
}
@Override
public void sync() {
sendSavePacket(-1, getScripts().size(), getNBT(new NBTTagCompound()));
public void sync(String sessionToken) {
NBTTagCompound compound = getNBT(new NBTTagCompound());
if (sessionToken != null && !sessionToken.isEmpty())
compound.setString("ScriptSessionToken", sessionToken);
sendSavePacket(-1, getScripts().size(), compound);
}
@Override
@@ -167,7 +167,9 @@ public class GuiScript extends GuiScriptInterface {
container == null ? "" : container.script);
}
activeArea.setLanguage(script.getLanguage());
// Use the container's language for syntax highlighting, fall back to handler default
String language = (container != null) ? container.getLanguage() : script.getLanguage();
activeArea.setLanguage(language);
activeArea.setScriptContext(getScriptContext());
// Set editor globals based on the active NPC hook
@@ -224,16 +226,19 @@ public class GuiScript extends GuiScriptInterface {
addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20,
consoleOptions.toArray(new String[0]), activeConsole));
addLabel(new GuiNpcLabel(1, "script.language", guiLeft + 232, guiTop + 30));
addLabel(new GuiNpcLabel(1, "script.default", guiLeft + 232, guiTop + 30));
List<String> languageOptions = getLanguageOptions();
addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20,
languageOptions.toArray(new String[0]), getLanguageIndex(languageOptions)));
getButton(103).enabled = languageOptions.size() > 0;
addLabel(new GuiNpcLabel(2, "gui.enabled", guiLeft + 232, guiTop + 53));
addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20,
new String[]{"gui.no", "gui.yes"}, script.enabled ? 1 : 0));
// Disable language/enabled controls until server data actually arrives
getButton(103).enabled = serverDataReceived && languageOptions.size() > 0;
getButton(104).enabled = serverDataReceived;
if (MinecraftServer.getServer() != null)
addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder"));
}
@@ -335,9 +340,13 @@ public class GuiScript extends GuiScriptInterface {
}
if (guibutton.id == 107) {
ScriptContainer container = getCurrentContainer();
if (container == null)
script.setNPCScript(activeTab, container = new ScriptContainer(this.script));
setSubGui(new GuiScriptList(languages.get(script.scriptLanguage), container));
if (container == null) {
container = new ScriptContainer(this.script);
container.setLanguage(script.getLanguage());
script.setNPCScript(activeTab, container);
}
String lang = container.getLanguage();
setSubGui(new GuiScriptList(languages.get(lang), container));
}
}
@@ -345,8 +354,11 @@ public class GuiScript extends GuiScriptInterface {
protected void setScript() {
if (showScript) {
ScriptContainer container = getCurrentContainer();
if (container == null)
script.setNPCScript(activeTab, container = new ScriptContainer(this.script));
if (container == null) {
container = new ScriptContainer(this.script);
container.setLanguage(script.getLanguage());
script.setNPCScript(activeTab, container);
}
String text = getTextField(2).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
@@ -357,6 +369,8 @@ public class GuiScript extends GuiScriptInterface {
@Override
public void setGuiData(NBTTagCompound compound) {
script.readFromNBT(compound);
if (compound.hasKey("ScriptSessionToken"))
scriptSessionToken = compound.getString("ScriptSessionToken");
loadLanguagesData(compound);
loaded = true;
}
@@ -365,7 +379,10 @@ public class GuiScript extends GuiScriptInterface {
public void save() {
if (loaded) {
setScript();
NPCScriptPacket.Save(script.writeToNBT(new NBTTagCompound()));
NBTTagCompound compound = script.writeToNBT(new NBTTagCompound());
if (scriptSessionToken != null)
compound.setString("ScriptSessionToken", scriptSessionToken);
NPCScriptPacket.Save(compound);
}
}
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket;
@@ -21,6 +22,7 @@ import noppes.npcs.constants.EnumScrollData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
@@ -98,14 +100,18 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
}
private List<String> getFilteredList() {
if (search.isEmpty()) {
return new ArrayList<>(rawData.keySet());
}
List<String> list = new ArrayList<>();
for (String name : rawData.keySet()) {
if (name.toLowerCase().contains(search.toLowerCase())) {
list.add(name);
for (Map.Entry<String, Integer> entry : rawData.entrySet()) {
String name = entry.getKey();
// Only show NPC-valid abilities (NPC_ONLY or BOTH)
UserType ut = UserType.fromOrdinal(entry.getValue());
if (!ut.allowsNpc()) continue;
if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) {
continue;
}
list.add(name);
}
return list;
}
@@ -0,0 +1,250 @@
package noppes.npcs.client.gui.advanced;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.Magic;
import noppes.npcs.controllers.data.MagicData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Sub-GUI for editing magic splits on an Ability.
* Dual-scroll layout: available magics on left, assigned magics on right.
* Only split values (no flat damage) are editable.
*/
public class SubGuiAbilityMagic extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
public MagicData magicData;
private GuiCustomScroll availableScroll;
private GuiCustomScroll assignedScroll;
/** Maps display name → magic ID for all available magics. */
private final HashMap<String, Integer> allMagic = new HashMap<>();
/** Maps formatted display string (right scroll) → base display name. */
private final HashMap<String, String> assignedDisplayToName = new HashMap<>();
private String search = "";
private GuiNpcTextField splitField;
public SubGuiAbilityMagic(MagicData data) {
this.magicData = data;
setBackground("menubg.png");
xSize = 420;
ySize = 222;
// Load all available magics from the controller
MagicController controller = MagicController.getInstance();
for (Map.Entry<Integer, Magic> entry : controller.magics.entrySet()) {
allMagic.put(entry.getValue().getDisplayName(), entry.getKey());
}
}
@Override
public void initGui() {
super.initGui();
int scrollW = 150;
int scrollH = 140;
int leftX = guiLeft + 10;
int rightX = guiLeft + 250;
int topY = guiTop + 20;
// Title
addLabel(new GuiNpcLabel(0, "ability.magic.editor", guiLeft + 10, guiTop + 5));
// Left scroll: available magics
if (availableScroll == null) {
availableScroll = new GuiCustomScroll(this, 0);
availableScroll.setSize(scrollW, scrollH);
}
availableScroll.guiLeft = leftX;
availableScroll.guiTop = topY;
availableScroll.setList(getSearchList());
addScroll(availableScroll);
// Search field below left scroll
addTextField(new GuiNpcTextField(4, this, fontRendererObj, leftX, topY + scrollH + 5, scrollW, 20, search));
// Right scroll: assigned magics
if (assignedScroll == null) {
assignedScroll = new GuiCustomScroll(this, 1);
assignedScroll.setSize(scrollW, scrollH);
}
assignedScroll.guiLeft = rightX;
assignedScroll.guiTop = topY;
updateAssignedList();
addScroll(assignedScroll);
// Arrow buttons between scrolls
int midX = guiLeft + 175;
addButton(new GuiNpcButton(70, midX, topY + 40, 55, 20, ">"));
addButton(new GuiNpcButton(71, midX, topY + 62, 55, 20, "<"));
// Standardize button
addButton(new GuiNpcButton(72, midX, topY + 90, 55, 20, "magic.dist"));
getButton(72).setHoverText("magic.distInfo");
// Split field below right scroll
int tfY = topY + scrollH + 5;
addLabel(new GuiNpcLabel(5002, "magic.split", rightX - 57, tfY + 5));
splitField = new GuiNpcTextField(73, this, fontRendererObj, rightX, tfY, 60, 20, "");
splitField.setFloatsOnly();
splitField.setMinMaxDefaultFloat(0, 1, 0);
splitField.enabled = false;
addTextField(splitField);
// Done button
addButton(new GuiNpcButton(80, guiLeft + xSize / 2 - 40, guiTop + ySize - 34, 80, 20, "gui.done"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
// Add magic
if (guibutton.id == 70) {
if (availableScroll.hasSelected()) {
String selected = availableScroll.getSelected();
Integer id = allMagic.get(selected);
if (id != null && !magicData.hasMagic(id)) {
magicData.addMagic(id, 0, 0);
}
}
updateAssignedList();
return;
}
// Remove magic
if (guibutton.id == 71) {
if (assignedScroll.hasSelected()) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
magicData.removeMagic(id);
}
}
updateAssignedList();
if (splitField != null) {
splitField.setText("");
splitField.enabled = false;
}
return;
}
// Standardize splits
if (guibutton.id == 72) {
if (magicData.getMagics().size() > 0) {
int count = magicData.getMagics().size();
float stdSplit = 1.0f / count;
for (Integer key : magicData.getMagics().keySet()) {
magicData.getMagic(key).split = stdSplit;
}
// Update field if something is selected
if (assignedScroll.getSelected() != null && splitField != null) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
splitField.setText(magicData.getMagic(id).split + "");
}
}
updateAssignedList();
}
return;
}
// Done
if (guibutton.id == 80) {
close();
return;
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(4) != null && getTextField(4).isFocused()) {
if (search.equals(getTextField(4).getText()))
return;
search = getTextField(4).getText().toLowerCase();
availableScroll.setList(getSearchList());
availableScroll.resetScroll();
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll == assignedScroll) {
if (assignedScroll.getSelected() != null) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
if (splitField != null) {
splitField.setText(magicData.getMagic(id).split + "");
splitField.enabled = true;
}
}
}
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
}
@Override
public void unFocused(GuiNpcTextField textField) {
if (textField.id == 73) {
if (assignedScroll != null && assignedScroll.getSelected() != null) {
Integer id = resolveAssignedId(assignedScroll.getSelected());
if (id != null && magicData.hasMagic(id)) {
try {
float split = Float.parseFloat(textField.getText());
magicData.getMagic(id).split = split;
updateAssignedList();
} catch (NumberFormatException e) {
}
}
}
}
}
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(allMagic.keySet());
}
List<String> list = new ArrayList<>();
for (String name : allMagic.keySet()) {
if (name.toLowerCase().contains(search))
list.add(name);
}
return list;
}
/**
* Resolves the magic ID from a right-scroll selection (which may be formatted as "Name - XX%").
*/
private Integer resolveAssignedId(String selection) {
if (selection == null) return null;
String baseName = assignedDisplayToName.get(selection);
if (baseName == null) baseName = selection;
return allMagic.get(baseName);
}
private void updateAssignedList() {
assignedDisplayToName.clear();
List<String> selected = new ArrayList<>();
for (Map.Entry<String, Integer> entry : allMagic.entrySet()) {
if (magicData.hasMagic(entry.getValue())) {
float split = magicData.getMagic(entry.getValue()).split;
String display = entry.getKey() + " - " + Math.round(split * 100) + "%";
assignedDisplayToName.put(display, entry.getKey());
selected.add(display);
}
}
if (assignedScroll != null) {
assignedScroll.setList(selected);
}
}
}
@@ -1,5 +1,6 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import net.minecraft.client.gui.GuiButton;
@@ -15,6 +16,7 @@ import noppes.npcs.constants.EnumScrollData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
@@ -93,14 +95,18 @@ public class SubGuiAbilitySelect extends SubGuiInterface implements ICustomScrol
merged.putAll(builtInData);
}
if (search.isEmpty()) {
return new ArrayList<>(merged.keySet());
}
List<String> list = new ArrayList<>();
for (String name : merged.keySet()) {
if (name.toLowerCase().contains(search.toLowerCase())) {
list.add(name);
for (Map.Entry<String, Integer> entry : merged.entrySet()) {
String name = entry.getKey();
// Only show NPC-valid abilities (NPC_ONLY or BOTH)
UserType ut = UserType.fromOrdinal(entry.getValue());
if (!ut.allowsNpc()) continue;
if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) {
continue;
}
list.add(name);
}
return list;
}
@@ -4,6 +4,7 @@ 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.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.network.PacketClient;
import java.util.UUID;
@@ -48,6 +49,7 @@ import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
@@ -72,6 +74,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
private static final int BTN_PREVIEW_PLAY = 91;
private static final int BTN_PREVIEW_PAUSE = 92;
private static final int BTN_PREVIEW_STOP = 93;
private static final int BTN_USER_TYPE_FILTER = 11;
// ── TextField / Label IDs ─────────────────────────────────────────────────
private static final int TF_SEARCH = 55;
@@ -99,6 +102,11 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
private boolean showingChained = false;
private boolean currentIsBuiltIn = false;
// ==================== USER TYPE FILTER ====================
// 0 = Both, 1 = NPC Only, 2 = Player Only
private int userTypeFilter = 0;
private static final String[] USER_TYPE_FILTER_LABELS = {"gui.both", "gui.npcs", "gui.players"};
// ==================== CHAINED DATA ====================
private HashMap<String, Integer> chainedData = new HashMap<>();
private ChainedAbility selectedChain = null;
@@ -176,6 +184,11 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
// Search bar
addTextField(new GuiNpcTextField(TF_SEARCH, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search));
// User type filter button (only for Custom and Built-in views)
if (!showingChained) {
addButton(new GuiNpcButton(BTN_USER_TYPE_FILTER, guiLeft + 368, guiTop + 192, 45, 20, USER_TYPE_FILTER_LABELS[userTypeFilter]));
}
// Check if we have something to preview
if (showingChained) {
if (selectedChain == null || selected == null || selectedChain.getEntries().isEmpty()) {
@@ -213,14 +226,23 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
private List<String> getSearchList() {
HashMap<String, Integer> data = getCurrentData();
if (search.isEmpty()) {
return new ArrayList<>(data.keySet());
}
List<String> list = new ArrayList<>();
for (String name : data.keySet()) {
if (name.toLowerCase().contains(search.toLowerCase())) {
list.add(name);
for (Map.Entry<String, Integer> entry : data.entrySet()) {
String name = entry.getKey();
// Apply search filter
if (!search.isEmpty() && !name.toLowerCase().contains(search.toLowerCase())) {
continue;
}
// Apply UserType filter (only for Custom and Built-in views)
if (!showingChained && userTypeFilter != 0) {
UserType ut = UserType.fromOrdinal(entry.getValue());
if (userTypeFilter == 1 && !ut.allowsNpc()) continue;
if (userTypeFilter == 2 && !ut.allowsPlayer()) continue;
}
list.add(name);
}
return list;
}
@@ -278,6 +300,16 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface
int id = guibutton.id;
// User type filter: Both → NPC → Player → Both
if (id == BTN_USER_TYPE_FILTER) {
userTypeFilter = (userTypeFilter + 1) % 3;
if (scroll != null) {
scroll.setList(getSearchList());
}
initGui();
return;
}
// Toggle: Custom → Built-in → Chained → Custom
if (id == BTN_TOGGLE_VIEW) {
if (!showingBuiltIn && !showingChained) {
@@ -25,11 +25,17 @@ import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import tconstruct.client.tabs.AbstractTab;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.Magic;
import noppes.npcs.controllers.data.MagicData;
import noppes.npcs.controllers.data.MagicEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
private final ResourceLocation resource = new ResourceLocation("customnpcs", "textures/gui/standardbg.png");
@@ -92,6 +98,11 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
private AbilityIcon cachedDetailIcon = null;
private int cachedDetailIndex = -1;
// ═══ Info panel scroll ═══
private int infoScrollOffset = 0;
private int infoContentHeight = 0;
private int lastInfoIndex = -1;
// ═══ Hotbar state ═══
private int hoveredSlotIndex = -1;
private AbilityIcon[] hotbarIcons = new AbilityIcon[AbilityHotbarData.TOTAL_SLOTS];
@@ -436,11 +447,17 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
int infoIndex = hoveredGridIndex >= 0 ? hoveredGridIndex : selectedIndex;
if (infoIndex < 0 || infoIndex >= filteredKeys.size()) return;
// Reset scroll when ability changes
if (infoIndex != lastInfoIndex) {
infoScrollOffset = 0;
lastInfoIndex = infoIndex;
}
FontRenderer fr = mc.fontRenderer;
int panelInnerLeft = guiLeft + infoLeft + infoPad;
int panelInnerTop = guiTop + infoTop + infoPad;
int panelInnerWidth = (infoRight - infoLeft) - infoPad * 2;
int y = panelInnerTop;
int panelHeight = infoBottom - infoTop;
// Cached icon for detail preview
if (cachedDetailIndex != infoIndex) {
@@ -448,14 +465,28 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
cachedDetailIndex = infoIndex;
}
Ability ability = filteredAbilities.get(infoIndex);
// Get toggle state for icon rendering and state display
int toggleState = 0;
PlayerData togglePlayerData = ClientCacheHandler.playerData;
Ability infoAbility = filteredAbilities.get(infoIndex);
if (infoAbility != null && infoAbility.isToggleable() && togglePlayerData != null && togglePlayerData.abilityData != null) {
if (ability != null && ability.isToggleable() && togglePlayerData != null && togglePlayerData.abilityData != null) {
toggleState = togglePlayerData.abilityData.getToggleState(filteredKeys.get(infoIndex));
}
// GL Scissor to clip info panel content
ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
int scaleFactor = sr.getScaleFactor();
int scissorX = (guiLeft + infoLeft) * scaleFactor;
int scissorY = mc.displayHeight - (guiTop + infoBottom) * scaleFactor;
int scissorW = (infoRight - infoLeft) * scaleFactor;
int scissorH = panelHeight * scaleFactor;
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(scissorX, scissorY, scissorW, scissorH);
int y = panelInnerTop - infoScrollOffset;
// Preview icon (centered, state-aware for multi-state toggles)
if (cachedDetailIcon != null) {
float drawSize = cachedDetailIcon.getDrawSize();
@@ -490,9 +521,8 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
}
y += 4;
// Type info
Ability ability = filteredAbilities.get(infoIndex);
if (ability != null) {
// Type info
String typeId = ability.getTypeId();
if (typeId != null && !typeId.isEmpty()) {
String translated = StatCollector.translateToLocal(typeId);
@@ -503,6 +533,7 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
}
}
// Toggle info
if (ability.isToggleable()) {
String toggleText = "[" + StatCollector.translateToLocal("gui.toggle") + "]";
int textW = fr.getStringWidth(toggleText);
@@ -510,12 +541,11 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
y += fr.FONT_HEIGHT + 3;
}
// Toggle state (uses pre-computed toggleState)
// Toggle state
if (ability.isToggleable()) {
String stateText;
String prefix;
if (toggleState > 0) {
// Active — check for state label (multi-state toggles like Ki Weapon)
String stateLabel = ability.getToggleStateLabel(toggleState);
stateText = stateLabel != null ? stateLabel : StatCollector.translateToLocal("gui.toggle.active");
prefix = "\u00A72";
@@ -528,20 +558,110 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
y += fr.FONT_HEIGHT + 3;
}
// Cooldown info
// Cooldown info — yellow if per-ability cooldown
if (ability.getCooldownTicks() > 0) {
float seconds = ability.getCooldownTicks() / 20.0f;
String cdText = StatCollector.translateToLocal("ability.cooldown") + ": " + String.format("%.1f", seconds) + "s";
int textW2 = fr.getStringWidth(cdText);
fr.drawStringWithShadow("\u00A77" + cdText, panelInnerLeft + (panelInnerWidth - textW2) / 2, y, 0xAAAAAA);
boolean perAbility = ability.isPerAbilityCooldown();
String cdColor = perAbility ? "\u00A7e" : "\u00A77";
int cdColorInt = perAbility ? 0xFFFF55 : 0xAAAAAA;
fr.drawStringWithShadow(cdColor + cdText, panelInnerLeft + (panelInnerWidth - textW2) / 2, y, cdColorInt);
y += fr.FONT_HEIGHT + 3;
if (ability.isPerAbilityCooldown()) {
if (perAbility) {
String perText = "[" + StatCollector.translateToLocal("ability.perAbilityCooldown") + "]";
int ptW = fr.getStringWidth(perText);
fr.drawStringWithShadow("\u00A7e" + perText, panelInnerLeft + (panelInnerWidth - ptW) / 2, y, 0xFFFF55);
y += fr.FONT_HEIGHT + 3;
}
}
// Damage info
float baseDamage = ability.getDisplayDamage();
if (baseDamage > 0) {
float displayDamage = baseDamage;
if (AbilityController.Instance != null && mc.thePlayer != null) {
displayDamage = AbilityController.Instance.fireModifyProjectileDamage(ability, mc.thePlayer, baseDamage);
}
String label = ability.isDisplayDamageDPS()
? StatCollector.translateToLocal("gui.dps")
: StatCollector.translateToLocal("ability.preview.damage");
String dmgText = label + ": " + String.format("%.1f", displayDamage);
int textW = fr.getStringWidth(dmgText);
fr.drawStringWithShadow("\u00A7c" + dmgText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xFF5555);
y += fr.FONT_HEIGHT + 3;
}
// Barrier health
float baseHealth = ability.getDisplayBarrierHealth();
if (baseHealth > 0) {
float displayHealth = baseHealth;
if (AbilityController.Instance != null && mc.thePlayer != null) {
displayHealth = AbilityController.Instance.fireModifyBarrierHealth(ability, mc.thePlayer, baseHealth);
}
String healthText = StatCollector.translateToLocal("ability.preview.health") + ": " + String.format("%.0f", displayHealth);
int textW = fr.getStringWidth(healthText);
fr.drawStringWithShadow("\u00A7a" + healthText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FF55);
y += fr.FONT_HEIGHT + 3;
}
// Barrier reflection
if (ability.isDisplayReflect()) {
String reflectText = StatCollector.translateToLocal("ability.reflect") + ": " + String.format("%.0f%%", ability.getDisplayReflectStrength());
int textW = fr.getStringWidth(reflectText);
fr.drawStringWithShadow("\u00A7d" + reflectText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0xFF55FF);
y += fr.FONT_HEIGHT + 3;
}
// Barrier absorbing
if (ability.isDisplayAbsorbing()) {
String absorbText = "[" + StatCollector.translateToLocal("ability.absorbing") + "]";
int textW = fr.getStringWidth(absorbText);
fr.drawStringWithShadow("\u00A7b" + absorbText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x55FFFF);
y += fr.FONT_HEIGHT + 3;
}
// Magic info
if (ability.hasMagic()) {
y += 2;
MagicData magicData = ability.getMagicData();
if (magicData.isEmpty()) {
String magicText = StatCollector.translateToLocal("ability.preview.magic.casters");
int textW = fr.getStringWidth(magicText);
fr.drawStringWithShadow("\u00A79" + magicText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x5555FF);
y += fr.FONT_HEIGHT + 3;
} else {
for (Map.Entry<Integer, MagicEntry> entry : magicData.getMagics().entrySet()) {
Magic magic = MagicController.getInstance() != null
? MagicController.getInstance().getMagic(entry.getKey()) : null;
String magicName = magic != null ? magic.getDisplayName() : "Magic #" + entry.getKey();
String splitText = magicName + ": " + Math.round(entry.getValue().split * 100) + "%";
int textW = fr.getStringWidth(splitText);
fr.drawStringWithShadow("\u00A79" + splitText, panelInnerLeft + (panelInnerWidth - textW) / 2, y, 0x5555FF);
y += fr.FONT_HEIGHT + 1;
}
y += 2;
}
}
}
// Track content height for scroll limits
infoContentHeight = (y + infoScrollOffset) - panelInnerTop + infoPad * 2;
GL11.glDisable(GL11.GL_SCISSOR_TEST);
// Scroll indicator
if (infoContentHeight > panelHeight) {
int maxScroll = Math.max(1, infoContentHeight - panelHeight);
if (infoScrollOffset > maxScroll) infoScrollOffset = maxScroll;
float scrollPercent = (float) infoScrollOffset / maxScroll;
int barHeight = panelHeight - 4;
int thumbHeight = Math.max(8, barHeight * panelHeight / infoContentHeight);
int thumbY = guiTop + infoTop + 2 + (int) ((barHeight - thumbHeight) * scrollPercent);
int barX = guiLeft + infoRight - 3;
drawRect(barX, guiTop + infoTop + 2, barX + 2, guiTop + infoTop + 2 + barHeight, 0x40FFFFFF);
drawRect(barX, thumbY, barX + 2, thumbY + thumbHeight, 0xA0FFFFFF);
}
}
@@ -903,11 +1023,26 @@ public class GuiAbilities extends GuiCNPCInventory implements ISubGuiListener {
int wheel = Mouse.getEventDWheel();
if (wheel != 0) {
int maxScroll = getMaxScrollRow();
if (wheel > 0) {
scrollRow = Math.max(0, scrollRow - 1);
int mouseX = Mouse.getEventX() * width / mc.displayWidth;
int mouseY = height - Mouse.getEventY() * height / mc.displayHeight - 1;
if (mouseX >= guiLeft + infoLeft && mouseX < guiLeft + infoRight
&& mouseY >= guiTop + infoTop && mouseY < guiTop + infoBottom) {
// Info panel scroll
int panelHeight = infoBottom - infoTop;
int maxInfoScroll = Math.max(0, infoContentHeight - panelHeight);
if (wheel > 0) {
infoScrollOffset = Math.max(0, infoScrollOffset - 10);
} else {
infoScrollOffset = Math.min(maxInfoScroll, infoScrollOffset + 10);
}
} else {
scrollRow = Math.min(maxScroll, scrollRow + 1);
int maxScroll = getMaxScrollRow();
if (wheel > 0) {
scrollRow = Math.max(0, scrollRow - 1);
} else {
scrollRow = Math.min(maxScroll, scrollRow + 1);
}
}
}
}
@@ -46,7 +46,9 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
public Map<String, List<String>> languages = new HashMap();
protected int scriptLimit = 1;
public List<String> hookList = new ArrayList<String>();
protected boolean loaded = false;
protected volatile boolean loaded = false;
protected boolean serverDataReceived = false;
protected String scriptSessionToken = null;
protected Map<Integer, GuiScriptTextArea> textAreas = new HashMap<>();
protected GuiScreen parent;
@@ -321,9 +323,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove"));
// Language toggle button (only if handler supports Janino and there is more than one option)
if (handler.supportsJanino() && getLanguageOptions().size() > 1 && container != null) {
this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20, container.getLanguage()));
// Per-tab language button — cycles through all available languages
List<String> langOptions = getLanguageOptions();
if (langOptions.size() > 1 && container != null) {
int langIdx = getContainerLanguageIndex(langOptions, container);
this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20,
langOptions.toArray(new String[0]), langIdx));
}
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
@@ -352,16 +357,20 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
int var9 = this.guiLeft + this.xSize - 150;
this.addButton(new GuiNpcButton(100, var9, this.guiTop + 125, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(102, var9, this.guiTop + 146, 60, 20, "gui.clear"));
this.addLabel(new GuiNpcLabel(1, "script.language", var9, this.guiTop + 15));
this.addLabel(new GuiNpcLabel(1, "script.default", var9, this.guiTop + 15));
List<String> languageOptions = getLanguageOptions();
this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20,
languageOptions.toArray(new String[0]),
this.getLanguageIndex(languageOptions)));
this.getButton(103).enabled = languageOptions.size() > 0;
this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36));
this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20,
new String[]{"gui.no", "gui.yes"}, this.handler.getEnabled() ? 1 : 0));
// Disable language/enabled controls until server data actually arrives
// (serverDataReceived is only set in loadLanguagesData, not by getLanguageOptions injecting Java)
this.getButton(103).enabled = serverDataReceived && languageOptions.size() > 0;
this.getButton(104).enabled = serverDataReceived;
if (this.player.worldObj.isRemote) {
this.addButton(new GuiNpcButton(106, var9, this.guiTop + 55, 150, 20, "script.openfolder"));
}
@@ -478,6 +487,26 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return 0;
}
/**
* Finds the index of a container's language within the available options.
* Used for the per-tab language button (113).
*
* @param languageOptions The list of available languages.
* @param container The script unit whose language to find.
* @return The 0-based index, or 0 if not found.
*/
protected int getContainerLanguageIndex(List<String> languageOptions, IScriptUnit container) {
if (languageOptions == null || languageOptions.isEmpty() || container == null)
return 0;
String current = container.getLanguage();
for (int i = 0; i < languageOptions.size(); i++) {
if (current != null && languageOptions.get(i).equalsIgnoreCase(current))
return i;
}
return 0;
}
/**
* Retrieves the list of available scripting languages for this handler.
* <p>
@@ -602,13 +631,13 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
if (guibutton.id == scriptLimit) {
if (handler.isSingleContainer()) {
if (handler.getSingleScript() == null) {
handler.addScriptUnit(new ScriptContainer(handler));
handler.addScriptUnit(createDefaultScriptUnit());
} else {
this.setScript();
}
this.activeTab = 1;
} else {
handler.addScriptUnit(new ScriptContainer(this.handler));
handler.addScriptUnit(createDefaultScriptUnit());
this.activeTab = this.handler.getScripts().size();
}
this.initGui();
@@ -666,43 +695,47 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
if (guibutton.id == 107) {
IScriptUnit container = getCurrentContainer();
if (container == null) {
container = new ScriptContainer(this.handler);
container = createDefaultScriptUnit();
handler.addScriptUnit(container);
}
String language = container != null ? container.getLanguage() : this.handler.getLanguage();
String language = container.getLanguage();
this.setSubGui(new EventGuiScriptList((List) this.languages.get(language), container));
}
// Language toggle button - switch between ECMAScript and Java
// Per-tab language cycling button
if (guibutton.id == 113) {
String selectedLanguage = ((GuiNpcButton) guibutton).displayString;
int idx = getActiveScriptIndex();
if (idx >= 0 && idx < handler.getScripts().size()) {
IScriptUnit currentUnit = handler.getScripts().get(idx);
IScriptUnit newUnit;
boolean currentIsJanino = currentUnit.isJanino();
boolean targetIsJanino = "Java".equals(selectedLanguage);
if (currentUnit.isJanino()) {
// Switch from Java to ECMAScript
newUnit = new ScriptContainer(handler);
if (currentIsJanino && !targetIsJanino) {
// Switch from Java to a non-Java language
IScriptUnit newUnit = new ScriptContainer(handler);
newUnit.setScript(currentUnit.getScript());
newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts()));
} else {
// Switch from ECMAScript to Java
newUnit = handler.createJaninoScriptUnit();
handler.replaceScriptUnit(idx, newUnit);
textAreas.remove(idx);
initGui();
} else if (!currentIsJanino && targetIsJanino) {
// Switch from non-Java to Java
IScriptUnit newUnit = handler.createJaninoScriptUnit();
if (newUnit != null) {
newUnit.setScript(currentUnit.getScript());
newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts()));
} else {
return; // Handler doesn't support Janino
handler.replaceScriptUnit(idx, newUnit);
textAreas.remove(idx);
initGui();
}
} else if (!currentIsJanino) {
// Switch between non-Java languages (e.g., ECMAScript to Lua)
currentUnit.setLanguage(selectedLanguage);
GuiScriptTextArea area = getActiveScriptArea();
if (area != null) area.setLanguage(selectedLanguage);
}
handler.replaceScriptUnit(idx, newUnit);
// Clear the cached text area so it recreates with new language
textAreas.remove(idx);
// Reinitialize the GUI
initGui();
}
}
}
@@ -712,7 +745,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
IScriptUnit container = getCurrentContainer();
if (container == null) {
container = new ScriptContainer(this.handler);
container = createDefaultScriptUnit();
handler.addScriptUnit(container);
}
@@ -734,6 +767,8 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return;
}
if (result.kind == IScriptHandlerPacket.GuiDataKind.METADATA) {
if (compound.hasKey("ScriptSessionToken"))
scriptSessionToken = compound.getString("ScriptSessionToken");
loadLanguagesData(compound);
return;
}
@@ -744,6 +779,8 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return;
}
if (compound.hasKey("ScriptSessionToken"))
scriptSessionToken = compound.getString("ScriptSessionToken");
loadLanguagesData(compound);
}
@@ -782,6 +819,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
this.languages = languages;
this.serverDataReceived = true;
this.initGui();
}
@@ -792,9 +830,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.setScript();
if (handler instanceof IScriptHandlerPacket)
((IScriptHandlerPacket) handler).sync();
((IScriptHandlerPacket) handler).sync(scriptSessionToken);
}
public void textUpdate(String text) {
@@ -831,6 +867,22 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
super.close();
}
/**
* Create a new script unit using the handler's default language.
* If default is Java, creates a JaninoScript; otherwise a ScriptContainer
* with its language set to the handler's default.
*/
protected IScriptUnit createDefaultScriptUnit() {
String defaultLang = handler.getLanguage();
if ("Java".equals(defaultLang)) {
IScriptUnit unit = handler.createJaninoScriptUnit();
if (unit != null) return unit;
}
ScriptContainer sc = new ScriptContainer(handler);
sc.setLanguage(defaultLang);
return sc;
}
// ==================== FULLSCREEN METHODS ====================
/**
@@ -155,9 +155,21 @@ public enum EnumScriptType {
public String function;
private static final java.util.Map<String, EnumScriptType> BY_FUNCTION = new java.util.HashMap<>();
static {
for (EnumScriptType type : values()) {
BY_FUNCTION.put(type.function, type);
}
}
public static EnumScriptType valueOfIgnoreCase(String channelName) {
channelName = channelName.toUpperCase();
return valueOf(channelName);
// First try by function name (e.g. "abilityStart")
EnumScriptType type = BY_FUNCTION.get(channelName);
if (type != null) {
return type;
}
// Fallback to enum constant name (e.g. "ABILITY_START")
return valueOf(channelName.toUpperCase());
}
private EnumScriptType(String function) {
@@ -11,12 +11,14 @@ import noppes.npcs.api.event.IEnergyProjectileEvent;
import noppes.npcs.api.event.IFactionEvent;
import noppes.npcs.api.event.IForgeEvent;
import noppes.npcs.api.event.IItemEvent;
import noppes.npcs.api.event.ILinkedItemEvent;
import noppes.npcs.api.event.INpcEvent;
import noppes.npcs.api.event.IPartyEvent;
import noppes.npcs.api.event.IChainEvent;
import noppes.npcs.api.event.IPlayerEvent;
import noppes.npcs.api.event.IProjectileEvent;
import noppes.npcs.api.event.IQuestEvent;
import noppes.npcs.api.event.IRecipeEvent;
import java.util.ArrayList;
import java.util.Arrays;
@@ -93,23 +95,24 @@ public class ScriptContext {
);
public static final ScriptContext LINKED_ITEM = register("LINKED_ITEM", "linked_item",
ILinkedItemEvent.class,
IItemEvent.class
);
public static final ScriptContext RECIPE = register("RECIPE", "recipe",
"Recipe"
IRecipeEvent.class
);
public static final ScriptContext EFFECT = register("EFFECT", "effect",
"Effect"
IPlayerEvent.class
);
public static final ScriptContext ABILITY = register("ABILITY", "ability",
"Ability"
IAbilityEvent.class
);
public static final ScriptContext CHAINED_ABILITY = register("CHAINED_ABILITY", "chained_ability",
"ChainedAbility"
IChainEvent.class
);
public static final ScriptContext GLOBAL = register("GLOBAL", "",
@@ -11,6 +11,7 @@ import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.scripted.NpcAPI;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
@@ -46,10 +47,45 @@ public class ScriptContainer implements IScriptUnit {
private CompiledScript compScript = null;
private final HashMap<String, ScriptObjectMirror> cachedFunctions = new HashMap<>();
/**
* Persisted per-container language. Null means inherit from handler default.
* Separate from currentScriptLanguage which is the engine cache.
*/
private String language = null;
/**
* Per-instance bindings for variable isolation. When non-null, this container
* is an instance scope sharing a template's engine. All eval/lookup uses these
* bindings instead of the engine's default ENGINE_SCOPE.
*/
private Bindings instanceBindings = null;
public ScriptContainer(IScriptHandler handler) {
this.handler = handler;
}
/**
* Create a lightweight instance scope that shares this container's engine
* but has its own isolated Bindings for variable state.
* The template's engine is initialized if needed.
*
* @param instanceHandler the script handler for the instance
*/
public ScriptContainer createInstanceScope(IScriptHandler instanceHandler) {
if (this.engine == null) {
this.setEngine(this.getLanguage());
}
ScriptContainer instance = new ScriptContainer(instanceHandler);
instance.script = this.script;
instance.scripts = new ArrayList<>(this.scripts);
instance.console = this.console;
instance.language = this.language;
instance.engine = this.engine;
instance.currentScriptLanguage = this.currentScriptLanguage;
instance.instanceBindings = this.engine.createBindings();
return instance;
}
public void readFromNBT(NBTTagCompound compound) {
String prevScript = this.script;
this.script = compound.getString("Script");
@@ -68,6 +104,12 @@ public class ScriptContainer implements IScriptUnit {
this.console = NBTTags.GetLongStringMap(compound.getTagList("Console", 10));
this.scripts = NBTTags.getStringList(compound.getTagList("ScriptList", 10));
this.lastCreated = 0L;
// Read per-container language (empty string or missing = inherit from handler)
if (compound.hasKey("ContainerLanguage")) {
String lang = compound.getString("ContainerLanguage");
this.language = lang.isEmpty() ? null : lang;
}
}
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
@@ -98,6 +140,11 @@ public class ScriptContainer implements IScriptUnit {
//compound.setString("Type", this.type);
compound.setTag("Console", NBTTags.NBTLongStringMap(this.console));
compound.setTag("ScriptList", NBTTags.nbtStringList(this.scripts));
// Persist per-container language if explicitly set
if (this.language != null) {
compound.setString("ContainerLanguage", this.language);
}
return compound;
}
@@ -169,7 +216,7 @@ public class ScriptContainer implements IScriptUnit {
if (!CustomNpcs.proxy.isScriptingEnabled() || errored || !hasCode() || unknownFunctions.contains(type))
return;
this.setEngine(handler.getLanguage());
this.setEngine(this.getLanguage());
if (engine == null)
return;
@@ -188,20 +235,33 @@ public class ScriptContainer implements IScriptUnit {
engine.getContext().setWriter(pw);
engine.getContext().setErrorWriter(pw);
engine.put("API", NpcAPI.Instance());
HashMap<String, Object> engineEntries = new HashMap<>(NpcAPI.engineObjects);
for (Map.Entry<String, Object> objectEntry : engineEntries.entrySet()) {
engine.put(objectEntry.getKey(), objectEntry.getValue());
// Populate bindings with API objects
if (instanceBindings != null) {
instanceBindings.put("API", NpcAPI.Instance());
HashMap<String, Object> engineEntries = new HashMap<>(NpcAPI.engineObjects);
for (Map.Entry<String, Object> objectEntry : engineEntries.entrySet()) {
instanceBindings.put(objectEntry.getKey(), objectEntry.getValue());
}
} else {
engine.put("API", NpcAPI.Instance());
HashMap<String, Object> engineEntries = new HashMap<>(NpcAPI.engineObjects);
for (Map.Entry<String, Object> objectEntry : engineEntries.entrySet()) {
engine.put(objectEntry.getKey(), objectEntry.getValue());
}
}
try {
if (!evaluated) {
this.cachedFunctions.clear();
engine.eval(getFullCode());
if (instanceBindings != null) {
engine.eval(getFullCode(), instanceBindings);
} else {
engine.eval(getFullCode());
}
evaluated = true;
}
if (engine.getFactory().getLanguageName().equals("lua")) {
Object ob = engine.get(type);
Object ob = instanceBindings != null ? instanceBindings.get(type) : engine.get(type);
if (ob != null) {
if (luaCoerce == null) {
luaCoerce = Class.forName("org.luaj.vm2.lib.jse.CoerceJavaToLua").getMethod("coerce", Object.class);
@@ -213,8 +273,14 @@ public class ScriptContainer implements IScriptUnit {
}
} else {
if (!this.cachedFunctions.containsKey(type)) {
ScriptObjectMirror global = (ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE);
ScriptObjectMirror func = (ScriptObjectMirror) global.get(type);
ScriptObjectMirror func;
if (instanceBindings != null) {
Object val = instanceBindings.get(type);
func = val instanceof ScriptObjectMirror ? (ScriptObjectMirror) val : null;
} else {
ScriptObjectMirror global = (ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE);
func = (ScriptObjectMirror) global.get(type);
}
this.cachedFunctions.put(type, func);
}
ScriptObjectMirror func = this.cachedFunctions.get(type);
@@ -263,6 +329,8 @@ public class ScriptContainer implements IScriptUnit {
public void setEngine(String scriptLanguage) {
if (!Objects.equals(scriptLanguage, this.currentScriptLanguage)) {
// Instance scopes share the template's engine — never create a new one
if (instanceBindings != null) return;
this.currentScriptLanguage = scriptLanguage;
if (ConfigScript.ScriptingECMA6 && scriptLanguage.equals("ECMAScript")) {
System.setProperty("nashorn.args", "--language=es6");
@@ -308,18 +376,15 @@ public class ScriptContainer implements IScriptUnit {
@Override
public String getLanguage() {
// If a specific language is set for this container, use it
// Otherwise fall back to the handler's language
if (currentScriptLanguage != null) {
return currentScriptLanguage;
}
return handler != null ? handler.getLanguage() : "ECMAScript";
// Return persisted per-container language, defaulting to ECMAScript.
// This is separate from currentScriptLanguage which is the engine cache.
return this.language != null ? this.language : "ECMAScript";
}
@Override
public void setLanguage(String language) {
if (!Objects.equals(this.currentScriptLanguage, language)) {
this.currentScriptLanguage = language;
if (!Objects.equals(this.language, language)) {
this.language = language;
this.evaluated = false;
}
}
@@ -18,6 +18,7 @@ import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.janino.EventJaninoScript;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
@@ -161,6 +162,11 @@ public class ForgeDataScript extends MultiScriptHandler {
ForgeScriptPacket.Save(index, totalCount, nbt);
}
@Override
public IScriptUnit createJaninoScriptUnit() {
return new EventJaninoScript(ScriptContext.FORGE);
}
@Override
public boolean isClient() {
return false;
@@ -8,6 +8,7 @@ import noppes.npcs.api.entity.ICustomNpc;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.janino.EventJaninoScript;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.util.ScriptToStringHelper;
@@ -47,6 +48,11 @@ public class GlobalNPCDataScript extends MultiScriptHandler {
lastNpcUpdate = ScriptController.Instance.lastGlobalNpcUpdate;
}
@Override
public IScriptUnit createJaninoScriptUnit() {
return new EventJaninoScript(ScriptContext.NPC);
}
@Override
public void requestData() {
GlobalNPCScriptPacket.Get();
@@ -71,16 +71,29 @@ public interface IScriptHandlerPacket extends IScriptHandler {
* GuiScriptInterface is responsible for updating the active {@link IScriptUnit} with current editor text first.
*/
default void sync() {
sync(null);
}
/**
* Emit save packets with a session token for server-side verification.
* The token prevents saving unloaded default data due to race conditions.
*/
default void sync(String sessionToken) {
List<IScriptUnit> containers = getScripts();
for (int i = 0; i < containers.size(); i++) {
IScriptUnit container = containers.get(i);
sendSavePacket(i, containers.size(), container.writeToNBT(new NBTTagCompound()));
NBTTagCompound nbt = container.writeToNBT(new NBTTagCompound());
if (sessionToken != null && !sessionToken.isEmpty())
nbt.setString("ScriptSessionToken", sessionToken);
sendSavePacket(i, containers.size(), nbt);
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", getLanguage());
scriptData.setBoolean("ScriptEnabled", getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(getConsoleText()));
if (sessionToken != null && !sessionToken.isEmpty())
scriptData.setString("ScriptSessionToken", sessionToken);
sendSavePacket(-1, containers.size(), scriptData);
}
}
@@ -76,4 +76,15 @@ public class MagicData implements IMagicData {
MagicEntry entry = magics.get(id);
return entry == null ? 0 : entry.split;
}
public MagicData copy() {
MagicData copy = new MagicData();
for (java.util.Map.Entry<Integer, MagicEntry> e : magics.entrySet()) {
MagicEntry entryCopy = new MagicEntry();
entryCopy.damage = e.getValue().damage;
entryCopy.split = e.getValue().split;
copy.magics.put(e.getKey(), entryCopy);
}
return copy;
}
}
@@ -696,6 +696,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
// Clear chain and concurrent state
if (currentChain != null) currentChain.clearInstanceScript();
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -778,6 +779,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
// Clear chain and concurrent state
if (currentChain != null) currentChain.clearInstanceScript();
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
@@ -167,6 +167,12 @@ public class PlayerDataScript extends MultiScriptHandler {
return ScriptController.Instance.playerScripts.scriptLanguage;
}
@Override
public void setLanguage(String lang) {
ScriptController.Instance.playerScripts.scriptLanguage = lang;
this.scriptLanguage = lang;
}
@Override
public String noticeString() {
if (this.player == null) {
@@ -2,7 +2,9 @@ package noppes.npcs.controllers.data;
import cpw.mods.fml.common.eventhandler.Event;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants;
import noppes.npcs.CustomNpcs;
@@ -117,9 +119,16 @@ public abstract class SingleScriptHandler extends ScriptHandler {
* - tab == 0: Script content NBT follows
* - tab != 0 (typically -1): Script metadata (language, enabled) follows
*/
public void saveScript(ByteBuf buffer) throws IOException {
public boolean saveScript(ByteBuf buffer, EntityPlayer player) throws IOException {
int tab = buffer.readInt();
int totalScripts = buffer.readInt();
NBTTagCompound compound = ByteBufUtils.readNBT(buffer);
// Verify session token
String token = compound.getString("ScriptSessionToken");
if (!PacketUtil.verifyScriptSession(player, token)) {
return false;
}
if (totalScripts == 0) {
this.container = null;
@@ -127,15 +136,14 @@ public abstract class SingleScriptHandler extends ScriptHandler {
if (tab == 0) {
// Script content
NBTTagCompound tabCompound = ByteBufUtils.readNBT(buffer);
this.container = IScriptUnit.createFromNBT(tabCompound, this);
this.container = IScriptUnit.createFromNBT(compound, this);
} else {
// Metadata (language, enabled)
NBTTagCompound compound = ByteBufUtils.readNBT(buffer);
this.setLanguage(compound.getString("ScriptLanguage"));
normalizeLanguage();
this.setEnabled(compound.getBoolean("ScriptEnabled"));
}
return true;
}
/**
@@ -5,15 +5,18 @@ import cpw.mods.fml.common.eventhandler.EventBus;
import foxz.command.ScriptedCommand;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.EnergyController;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.TelegraphController;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityEnergyPanel;
import kamkeel.npcs.entity.EntityEnergySweeper;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.block.Block;
@@ -60,6 +63,7 @@ import noppes.npcs.api.IBlock;
import noppes.npcs.api.ICommand;
import noppes.npcs.api.IContainer;
import noppes.npcs.api.IDamageSource;
import noppes.npcs.api.IEnergyController;
import noppes.npcs.api.INbt;
import noppes.npcs.api.IParticle;
import noppes.npcs.api.IPos;
@@ -99,12 +103,14 @@ 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.ScriptEnergyExplosion;
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.ScriptEnergyZone;
import noppes.npcs.scripted.entity.ScriptEntity;
import noppes.npcs.scripted.entity.ScriptEntityItem;
import noppes.npcs.scripted.entity.ScriptFishHook;
@@ -462,6 +468,10 @@ public class NpcAPI extends AbstractNpcAPI {
data = new ScriptEntityData(new ScriptEnergyPanel<>((EntityEnergyPanel) entity));
else if (entity instanceof EntityEnergySweeper)
data = new ScriptEntityData(new ScriptEnergySweeper<>((EntityEnergySweeper) entity));
else if (entity instanceof EntityEnergyExplosion)
data = new ScriptEntityData(new ScriptEnergyExplosion<>((EntityEnergyExplosion) entity));
else if (entity instanceof EntityAbilityZone)
data = new ScriptEntityData(new ScriptEnergyZone<>((EntityAbilityZone) entity));
else
data = new ScriptEntityData(new ScriptEntity<>(entity));
entity.registerExtendedProperties("ScriptedObject", data);
@@ -612,6 +622,11 @@ public class NpcAPI extends AbstractNpcAPI {
return instance;
}
@Override
public IEnergyController getEnergyController() {
return EnergyController.Instance;
}
public EventBus events() {
return EVENT_BUS;
}
@@ -23,4 +23,5 @@ public class EntityType {
public static final int ENERGY_BARRIER = 19;
public static final int ENERGY_DOME = 20;
public static final int ENERGY_PANEL = 21;
public static final int ENERGY_EXPLOSION = 22;
}
@@ -2,8 +2,12 @@ package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityEnergyAbility;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.INbt;
import noppes.npcs.api.entity.IEnergyAbility;
import noppes.npcs.api.entity.IEntity;
import noppes.npcs.api.handler.data.IMagicData;
import noppes.npcs.controllers.data.MagicData;
import noppes.npcs.scripted.NpcAPI;
/**
@@ -128,4 +132,35 @@ public abstract class ScriptEnergyAbility<T extends EntityEnergyAbility> extends
public void setIgnoreIFrames(boolean ignore) {
entity.setIgnoreIFrames(ignore);
}
// ==================== CUSTOM DAMAGE DATA ====================
public INbt getDamageData() {
NBTTagCompound data = entity.getCustomDamageData();
if (data == null) {
data = new NBTTagCompound();
entity.setCustomDamageData(data);
}
return NpcAPI.Instance().getINbt(data);
}
public void setDamageData(INbt data) {
if (data == null) {
entity.setCustomDamageData(null);
} else {
entity.setCustomDamageData((NBTTagCompound) data.getMCNBT());
}
}
// ==================== MAGIC DATA ====================
public IMagicData getMagicData() {
return entity.getMagicData();
}
public void setMagicData(IMagicData data) {
if (data instanceof MagicData) {
entity.setMagicData((MagicData) data);
}
}
}
@@ -60,7 +60,7 @@ public class ScriptEnergyBeam<T extends EntityAbilityBeam> extends ScriptEnergyP
// ==================== FIRE ====================
@Override
public void fire(IEntity target) {
public void fireAt(IEntity target) {
ensureSpawned();
EntityLivingBase mcTarget = null;
if (target != null && target.getMCEntity() instanceof EntityLivingBase) {
@@ -70,7 +70,7 @@ public class ScriptEnergyBeam<T extends EntityAbilityBeam> extends ScriptEnergyP
}
@Override
public void fire(double x, double y, double z) {
public void fireAt(double x, double y, double z) {
ensureSpawned();
double dx = x - entity.posX;
double dy = y - entity.posY;
@@ -76,7 +76,7 @@ public class ScriptEnergyDisc<T extends EntityAbilityDisc> extends ScriptEnergyP
// ==================== FIRE ====================
@Override
public void fire(IEntity target) {
public void fireAt(IEntity target) {
ensureSpawned();
EntityLivingBase mcTarget = null;
if (target != null && target.getMCEntity() instanceof EntityLivingBase) {
@@ -86,7 +86,7 @@ public class ScriptEnergyDisc<T extends EntityAbilityDisc> extends ScriptEnergyP
}
@Override
public void fire(double x, double y, double z) {
public void fireAt(double x, double y, double z) {
ensureSpawned();
double dx = x - entity.posX;
double dy = y - entity.posY;
@@ -0,0 +1,109 @@
package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.data.energyexplosion.EnergyExplosionSpawnPacket;
import noppes.npcs.api.entity.IEnergyExplosion;
import noppes.npcs.scripted.constants.EntityType;
import java.util.UUID;
/**
* Script wrapper for standalone energy explosion entities.
*/
public class ScriptEnergyExplosion<T extends EntityEnergyExplosion> extends ScriptEnergyAbility<T> implements IEnergyExplosion {
public ScriptEnergyExplosion(T entity) {
super(entity);
}
// ==================== TYPE ====================
@Override
public int getType() {
return EntityType.ENERGY_EXPLOSION;
}
@Override
public boolean typeOf(int type) {
return type == EntityType.ENERGY_EXPLOSION || super.typeOf(type);
}
// ==================== RADIUS & DURATION ====================
@Override
public float getRadius() {
return entity.getExplosionRadius();
}
@Override
public void setRadius(float radius) {
entity.setExplosionRadius(radius);
}
@Override
public int getDuration() {
return entity.getDurationTicks();
}
// ==================== DAMAGE ====================
@Override
public float getDamage() {
return entity.getDamage();
}
@Override
public void setDamage(float damage) {
entity.setDamage(damage);
}
@Override
public float getKnockback() {
return entity.getKnockback();
}
@Override
public void setKnockback(float knockback) {
entity.setKnockback(knockback);
}
@Override
public float getKnockbackUp() {
return entity.getKnockbackUp();
}
@Override
public void setKnockbackUp(float knockbackUp) {
entity.setKnockbackUp(knockbackUp);
}
@Override
public float getDamageFalloff() {
return entity.getDamageFalloff();
}
@Override
public void setDamageFalloff(float falloff) {
entity.setDamageFalloff(falloff);
}
// ==================== SPAWNING ====================
@Override
public void spawn() {
if (entity.addedToChunk || entity.worldObj == null) return;
if (!entity.worldObj.isRemote) {
// Send visual to clients via packet (explosion is packet-driven, not a tracked entity)
String instanceId = "energy_explosion_" + UUID.randomUUID();
PacketHandler.Instance.sendToAll(new EnergyExplosionSpawnPacket(
instanceId, entity.exportSpawnNBT()));
// Spawn server-side for damage logic (if damage enabled)
if (entity.isDamageEnabled()) {
entity.worldObj.spawnEntityInWorld(entity);
}
}
}
}
@@ -92,7 +92,7 @@ public class ScriptEnergyLaser<T extends EntityAbilityLaser> extends ScriptEnerg
// ==================== FIRE ====================
@Override
public void fire(IEntity target) {
public void fireAt(IEntity target) {
ensureSpawned();
EntityLivingBase mcTarget = null;
if (target != null && target.getMCEntity() instanceof EntityLivingBase) {
@@ -102,7 +102,7 @@ public class ScriptEnergyLaser<T extends EntityAbilityLaser> extends ScriptEnerg
}
@Override
public void fire(double x, double y, double z) {
public void fireAt(double x, double y, double z) {
ensureSpawned();
double dx = x - entity.posX;
double dy = y - entity.posY;
@@ -28,7 +28,7 @@ public class ScriptEnergyOrb<T extends EntityAbilityOrb> extends ScriptEnergyPro
}
@Override
public void fire(IEntity target) {
public void fireAt(IEntity target) {
ensureSpawned();
EntityLivingBase mcTarget = null;
if (target != null && target.getMCEntity() instanceof EntityLivingBase) {
@@ -38,7 +38,7 @@ public class ScriptEnergyOrb<T extends EntityAbilityOrb> extends ScriptEnergyPro
}
@Override
public void fire(double x, double y, double z) {
public void fireAt(double x, double y, double z) {
ensureSpawned();
double dx = x - entity.posX;
double dy = y - entity.posY;
@@ -54,4 +54,23 @@ public class ScriptEnergyPanel<T extends EntityEnergyPanel> extends ScriptEnergy
public boolean isLaunched() {
return entity.getMode() == EntityEnergyPanel.PanelMode.LAUNCHED;
}
public void setPanelYaw(float yaw) {
entity.setPanelYaw(yaw);
}
public void setPanelMode(int mode) {
EntityEnergyPanel.PanelMode[] values = EntityEnergyPanel.PanelMode.values();
if (mode >= 0 && mode < values.length) {
entity.setMode(values[mode]);
}
}
// ==================== SPAWNING ====================
public void spawn() {
if (!entity.addedToChunk && entity.worldObj != null) {
entity.worldObj.spawnEntityInWorld(entity);
}
}
}
@@ -259,7 +259,7 @@ public class ScriptEnergyProjectile<T extends EntityEnergyProjectile> extends Sc
// ==================== FIRE ====================
public void fire(IEntity target) {
public void fireAt(IEntity target) {
if (target != null) {
Entity mcTarget = target.getMCEntity();
setMotionToward(mcTarget.posX, mcTarget.posY + mcTarget.getEyeHeight(), mcTarget.posZ);
@@ -267,12 +267,12 @@ public class ScriptEnergyProjectile<T extends EntityEnergyProjectile> extends Sc
ensureSpawned();
}
public void fire(double x, double y, double z) {
public void fireAt(double x, double y, double z) {
setMotionToward(x, y, z);
ensureSpawned();
}
public void fire(float yaw, float pitch) {
public void fireDirection(float yaw, float pitch) {
float yawRad = (float) Math.toRadians(yaw);
float pitchRad = (float) Math.toRadians(pitch);
entity.motionX = -Math.sin(yawRad) * Math.cos(pitchRad) * entity.getSpeed();
@@ -281,16 +281,16 @@ public class ScriptEnergyProjectile<T extends EntityEnergyProjectile> extends Sc
ensureSpawned();
}
public void fire(IEntityLivingBase caster) {
public void fireFrom(IEntityLivingBase caster) {
if (caster == null) return;
initFromCaster(caster);
fire(caster.getRotation(), caster.getPitch());
fireDirection(caster.getRotation(), caster.getPitch());
}
public void fire(IEntityLivingBase caster, IEntity target) {
public void fireFrom(IEntityLivingBase caster, IEntity target) {
if (caster == null) return;
initFromCaster(caster);
fire(target);
fireAt(target);
}
/**
@@ -48,7 +48,7 @@ public class ScriptEnergySlicer<T extends EntityEnergySlicer> extends ScriptEner
// ==================== FIRE ====================
@Override
public void fire(IEntity target) {
public void fireAt(IEntity target) {
ensureSpawned();
EntityLivingBase mcTarget = null;
if (target != null && target.getMCEntity() instanceof EntityLivingBase) {
@@ -58,7 +58,7 @@ public class ScriptEnergySlicer<T extends EntityEnergySlicer> extends ScriptEner
}
@Override
public void fire(double x, double y, double z) {
public void fireAt(double x, double y, double z) {
ensureSpawned();
double dx = x - entity.posX;
double dy = y - entity.posY;
@@ -1,9 +1,116 @@
package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityEnergySweeper;
import noppes.npcs.api.entity.IEnergySweeper;
public class ScriptEnergySweeper<T extends EntityEnergySweeper> extends ScriptEnergyAbility<T> implements IEnergySweeper {
public class ScriptEnergySweeper<T extends EntityEnergySweeper> extends ScriptEnergyAbility<T> {
public ScriptEnergySweeper(T entity) {
super(entity);
}
// ==================== BEAM DIMENSIONS ====================
@Override
public float getBeamLength() {
return entity.getBeamLength();
}
@Override
public void setBeamLength(float length) {
entity.setBeamLength(length);
}
@Override
public float getBeamWidth() {
return entity.getBeamWidth();
}
@Override
public void setBeamWidth(float width) {
entity.setBeamWidth(width);
}
@Override
public float getBeamHeight() {
return entity.getBeamHeight();
}
@Override
public void setBeamHeight(float height) {
entity.setBeamHeight(height);
}
// ==================== ROTATION ====================
@Override
public float getSweepSpeed() {
return entity.getSweepSpeed();
}
@Override
public void setSweepSpeed(float degreesPerTick) {
entity.setSweepSpeed(degreesPerTick);
}
@Override
public int getNumberOfRotations() {
return entity.getNumberOfRotations();
}
@Override
public void setNumberOfRotations(int rotations) {
entity.setNumberOfRotations(rotations);
}
@Override
public boolean isLockOnTarget() {
return entity.isLockOnTarget();
}
@Override
public void setLockOnTarget(boolean lock) {
entity.setLockOnTarget(lock);
}
// ==================== DAMAGE ====================
@Override
public float getDamage() {
return entity.getDamage();
}
@Override
public void setDamage(float damage) {
entity.setDamage(damage);
}
@Override
public int getDamageInterval() {
return entity.getDamageInterval();
}
@Override
public void setDamageInterval(int ticks) {
entity.setDamageInterval(ticks);
}
@Override
public boolean isPiercing() {
return entity.isPiercing();
}
@Override
public void setPiercing(boolean piercing) {
entity.setPiercing(piercing);
}
// ==================== SPAWNING ====================
@Override
public void spawn() {
if (!entity.addedToChunk && entity.worldObj != null) {
entity.worldObj.spawnEntityInWorld(entity);
}
}
}
@@ -0,0 +1,277 @@
package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityAbilityZone;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.INbt;
import noppes.npcs.api.entity.IEnergyZone;
import noppes.npcs.scripted.NpcAPI;
/**
* Script wrapper for EntityAbilityZone (Hazard and Trap zones).
*/
public class ScriptEnergyZone<T extends EntityAbilityZone> extends ScriptEntity<T> implements IEnergyZone {
public ScriptEnergyZone(T entity) {
super(entity);
}
// ==================== ZONE TYPE ====================
@Override
public int getZoneType() {
return entity.getZoneType().ordinal();
}
// ==================== COMMON ZONE PROPERTIES ====================
@Override
public int getZoneShape() {
return entity.getShape().ordinal();
}
@Override
public void setZoneShape(int shape) {
EntityAbilityZone.ZoneShape[] values = EntityAbilityZone.ZoneShape.values();
if (shape >= 0 && shape < values.length) {
entity.setShape(values[shape]);
}
}
@Override
public float getRadius() {
return entity.getRadius();
}
@Override
public void setRadius(float radius) {
entity.setRadius(radius);
}
@Override
public float getZoneHeight() {
return entity.getZoneHeight();
}
@Override
public void setZoneHeight(float height) {
entity.setZoneHeight(height);
}
@Override
public int getDuration() {
return entity.getDurationTicks();
}
@Override
public void setDuration(int ticks) {
entity.setDurationTicks(ticks);
}
// ==================== COLORS ====================
@Override
public int getInnerColor() {
return entity.getInnerColor();
}
@Override
public void setInnerColor(int color) {
entity.setInnerColor(color);
}
@Override
public int getOuterColor() {
return entity.getOuterColor();
}
@Override
public void setOuterColor(int color) {
entity.setOuterColor(color);
}
@Override
public boolean isOuterColorEnabled() {
return entity.isOuterColorEnabled();
}
@Override
public void setOuterColorEnabled(boolean enabled) {
entity.setOuterColorEnabled(enabled);
}
// ==================== VISUALS ====================
@Override
public float getParticleDensity() {
return entity.getParticleDensity();
}
@Override
public void setParticleDensity(float density) {
entity.setParticleDensity(density);
}
@Override
public float getParticleScale() {
return entity.getParticleScale();
}
@Override
public void setParticleScale(float scale) {
entity.setParticleScale(scale);
}
@Override
public float getAnimSpeed() {
return entity.getAnimSpeed();
}
@Override
public void setAnimSpeed(float speed) {
entity.setAnimSpeed(speed);
}
@Override
public boolean isIgnoreIFrames() {
return entity.isIgnoreIFrames();
}
@Override
public void setIgnoreIFrames(boolean ignore) {
entity.setIgnoreIFrames(ignore);
}
// ==================== HAZARD-SPECIFIC ====================
@Override
public float getDamagePerSecond() {
return entity.getDamagePerSecond();
}
@Override
public void setDamagePerSecond(float dps) {
entity.setDamagePerSecond(dps);
}
@Override
public int getDamageInterval() {
return entity.getDamageInterval();
}
@Override
public void setDamageInterval(int ticks) {
entity.setDamageInterval(ticks);
}
@Override
public boolean isAffectsCaster() {
return entity.isAffectsCaster();
}
@Override
public void setAffectsCaster(boolean affects) {
entity.setAffectsCaster(affects);
}
// ==================== TRAP-SPECIFIC ====================
@Override
public float getTriggerRadius() {
return entity.getTriggerRadius();
}
@Override
public void setTriggerRadius(float radius) {
entity.setTriggerRadius(radius);
}
@Override
public int getArmTime() {
return entity.getArmTime();
}
@Override
public void setArmTime(int ticks) {
entity.setArmTime(ticks);
}
@Override
public int getMaxTriggers() {
return entity.getMaxTriggers();
}
@Override
public void setMaxTriggers(int max) {
entity.setMaxTriggers(max);
}
@Override
public int getTriggerCooldown() {
return entity.getTriggerCooldown();
}
@Override
public void setTriggerCooldown(int ticks) {
entity.setTriggerCooldown(ticks);
}
@Override
public float getDamage() {
return entity.getDamage();
}
@Override
public void setDamage(float damage) {
entity.setDamage(damage);
}
@Override
public float getKnockback() {
return entity.getKnockback();
}
@Override
public void setKnockback(float knockback) {
entity.setKnockback(knockback);
}
@Override
public boolean isVisible() {
return entity.isVisible();
}
@Override
public void setVisible(boolean visible) {
entity.setVisible(visible);
}
// ==================== CUSTOM DAMAGE DATA ====================
@Override
public INbt getDamageData() {
NBTTagCompound data = entity.getCustomDamageData();
if (data == null) {
data = new NBTTagCompound();
entity.setCustomDamageData(data);
}
return NpcAPI.Instance().getINbt(data);
}
@Override
public void setDamageData(INbt data) {
if (data == null) {
entity.setCustomDamageData(null);
} else {
entity.setCustomDamageData((NBTTagCompound) data.getMCNBT());
}
}
// ==================== SPAWNING ====================
@Override
public void spawn() {
if (!entity.addedToChunk && entity.worldObj != null) {
entity.worldObj.spawnEntityInWorld(entity);
}
}
}
@@ -99,8 +99,11 @@ public class ScriptCustomItem extends ScriptCustomizableItem implements IItemCus
}
@Override
public void sync() {
sendSavePacket(-1, getScripts().size(), getMCNbt());
public void sync(String sessionToken) {
NBTTagCompound compound = getMCNbt();
if (sessionToken != null && !sessionToken.isEmpty())
compound.setString("ScriptSessionToken", sessionToken);
sendSavePacket(-1, getScripts().size(), compound);
}
public int getType() {
@@ -87,6 +87,11 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin
return this.durabilityValue;
}
public void setDurabilityValue(float value) {
this.durabilityValue = (double) value;
saveItemData();
}
@Override
public int getMaxItemUseDuration() {
return this.linkedItem.maxItemUseDuration;
@@ -217,6 +222,7 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin
this.itemDisplay.writeToNBT(compound);
compound.setTag(LinkedItem.LINKED_DATA_NBT_TAG, this.linkedItem.writeToNBT(false));
compound.setInteger(LinkedItem.LINKED_VERSION_VERSION_TAG, this.linkedVersion);
compound.setDouble("DurabilityValue", this.durabilityValue);
return compound;
}
@@ -224,5 +230,7 @@ public class ScriptLinkedItem extends ScriptCustomizableItem implements IItemLin
this.itemDisplay.readFromNBT(compound);
this.linkedItem.readFromNBT(compound.getCompoundTag(LinkedItem.LINKED_DATA_NBT_TAG));
this.linkedVersion = compound.getInteger(LinkedItem.LINKED_VERSION_VERSION_TAG);
if (compound.hasKey("DurabilityValue"))
this.durabilityValue = compound.getDouble("DurabilityValue");
}
}