Merge branch 'dev' into kam-cant-make-plugin-integrations-part-2

# Conflicts:
#	dependencies.gradle
This commit is contained in:
somehussar committed 2026-02-03 01:10:40 +01:00
commit 650a13edb1
391 files changed
+52664 -9801

No files matched your search

@@ -14,6 +14,11 @@ import net.minecraftforge.common.util.FakePlayer;
import noppes.npcs.api.IWorld;
import noppes.npcs.blocks.tiles.TileNpcContainer;
import noppes.npcs.constants.EnumGuiType;
import noppes.npcs.containers.ContainerAuction;
import noppes.npcs.containers.ContainerAuctionBidding;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerAnvilRepair;
import noppes.npcs.containers.ContainerCarpentryBench;
import noppes.npcs.containers.ContainerCrate;
@@ -92,6 +97,18 @@ public class CommonProxy implements IGuiHandler {
if (gui == EnumGuiType.PlayerTrader)
return new ContainerNPCTrader(npc, player);
if (gui == EnumGuiType.PlayerAuction)
return new ContainerAuctionListing(npc, player);
if (gui == EnumGuiType.PlayerAuctionSell)
return new ContainerAuctionSell(npc, player);
if (gui == EnumGuiType.PlayerAuctionTrades)
return new ContainerAuctionTrades(npc, player);
if (gui == EnumGuiType.PlayerAuctionBidding)
return new ContainerAuctionBidding(npc, player);
if (gui == EnumGuiType.PlayerCarpentryBench)
return new ContainerCarpentryBench(player.inventory, player.worldObj, x, y, z);
@@ -200,4 +217,7 @@ public class CommonProxy implements IGuiHandler {
public boolean isGUIOpen() {
return false;
}
public void buildPackageIndex() {
}
}
+87 -3
View File
@@ -5,6 +5,7 @@ import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
@@ -13,13 +14,18 @@ import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import foxz.command.CommandNoppes;
import io.github.somehussar.janinoloader.api.IDynamicCompiler;
import io.github.somehussar.janinoloader.api.IDynamicCompilerBuilder;
import kamkeel.npcs.addon.AddonManager;
import kamkeel.npcs.command.CommandKamkeel;
import kamkeel.npcs.command.profile.CommandProfile;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.TelegraphController;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.profile.CNPCData;
import kamkeel.npcs.developer.Developer;
import kamkeel.npcs.network.PacketHandler;
@@ -50,6 +56,7 @@ import noppes.npcs.config.ConfigMain;
import noppes.npcs.config.LoadConfiguration;
import noppes.npcs.config.legacy.LegacyConfig;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.AuctionController;
import noppes.npcs.controllers.BankController;
import noppes.npcs.controllers.ChunkController;
import noppes.npcs.controllers.CustomEffectController;
@@ -70,7 +77,6 @@ import noppes.npcs.controllers.SpawnController;
import noppes.npcs.controllers.TagController;
import noppes.npcs.controllers.TransportController;
import noppes.npcs.enchants.EnchantInterface;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import noppes.npcs.entity.EntityChairMount;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityMagicProjectile;
@@ -80,6 +86,11 @@ import noppes.npcs.entity.EntityNpcDragon;
import noppes.npcs.entity.EntityNpcPony;
import noppes.npcs.entity.EntityNpcSlime;
import noppes.npcs.entity.EntityProjectile;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import noppes.npcs.entity.old.EntityNPCDwarfFemale;
import noppes.npcs.entity.old.EntityNPCDwarfMale;
import noppes.npcs.entity.old.EntityNPCElfFemale;
@@ -99,11 +110,14 @@ import noppes.npcs.entity.old.EntityNpcNagaFemale;
import noppes.npcs.entity.old.EntityNpcNagaMale;
import noppes.npcs.entity.old.EntityNpcSkeleton;
import noppes.npcs.scripted.NpcAPI;
import somehussar.janino.AdvancedClassFilter;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.10.3")
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta1")
public class CustomNpcs {
@SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")
@@ -140,10 +154,56 @@ public class CustomNpcs {
public static MinecraftServer Server;
private static IDynamicCompiler globalJaninoCompiler;
@SideOnly(Side.CLIENT)
private static IDynamicCompiler clientJaninoCompiler;
@SideOnly(Side.CLIENT)
private static Set<Consumer<AdvancedClassFilter>> clientClassFilterConsumer;
static {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
clientClassFilterConsumer = new HashSet<>();
}
}
@SideOnly(Side.CLIENT)
public static void addClassesToClientClassFilter(Consumer<AdvancedClassFilter> consumer) {
clientClassFilterConsumer.add(consumer);
}
public CustomNpcs() {
instance = this;
}
public static IDynamicCompiler getDynamicCompiler() {
if (globalJaninoCompiler == null) {
globalJaninoCompiler = IDynamicCompilerBuilder.createBuilder().getCompiler();
}
return globalJaninoCompiler;
}
@SideOnly(Side.CLIENT)
public static IDynamicCompiler getClientCompiler() {
if (clientJaninoCompiler == null) {
AdvancedClassFilter filter = new AdvancedClassFilter()
.addRegexes("noppes\\.npcs\\.api\\..*")
.banRegexes(".*ClassLoader.*",
".*File*.",
"java\\.lang\\.reflect\\..*");
for (Consumer<AdvancedClassFilter> consumer : clientClassFilterConsumer) {
consumer.accept(filter);
}
clientJaninoCompiler = IDynamicCompilerBuilder.createBuilder().setClassFilter(filter).getCompiler();
}
return clientJaninoCompiler;
}
@EventHandler
public void load(FMLPreInitializationEvent ev) {
PacketHandler.Instance = new PacketHandler();
@@ -227,6 +287,11 @@ 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(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true);
new RecipeController();
@@ -259,8 +324,17 @@ public class CustomNpcs {
PacketHandler.Instance.registerChannels();
}
@EventHandler
public void loadComplete(FMLLoadCompleteEvent ev) {
proxy.buildPackageIndex();
}
@EventHandler
public void setAboutToStart(FMLServerAboutToStartEvent event) {
globalJaninoCompiler = null;
if (FMLCommonHandler.instance().getSide().isClient())
clientJaninoCompiler = null;
Server = event.getServer();
ChunkController.Instance.clear();
FactionController.getInstance().load();
@@ -272,8 +346,8 @@ public class CustomNpcs {
new SpawnController();
new LinkedNpcController();
new AnimationController();
new AbilityController();
AbilityController.Instance.load();
TelegraphController.init();
LinkedItemController.getInstance().load();
@@ -312,6 +386,7 @@ public class CustomNpcs {
public void started(FMLServerStartedEvent event) {
RecipeController.Instance.load();
new BankController();
new AuctionController();
DialogController.Instance.load();
QuestController.Instance.load();
ScriptController.HasStart = true;
@@ -332,6 +407,15 @@ public class CustomNpcs {
ScriptController.Instance.saveForgeScripts();
ScriptController.Instance.savePlayerScripts();
ScriptController.Instance.saveGlobalNpcScripts();
// Save auction data synchronously on shutdown
if (AuctionController.Instance != null) {
AuctionController.Instance.save();
}
if (FMLCommonHandler.instance().getSide().isClient())
clientJaninoCompiler = null;
globalJaninoCompiler = null;
}
@EventHandler
@@ -67,6 +67,7 @@ public class CustomNpcsPermissions {
public static final Permission GLOBAL_NATURALSPAWN = new Permission("customnpcs.global.naturalspawn");
public static final Permission GLOBAL_TAG = new Permission("customnpcs.global.tag");
public static final Permission GLOBAL_ANIMATION = new Permission("customnpcs.global.animation");
public static final Permission GLOBAL_ABILITY = new Permission("customnpcs.global.ability");
public static final Permission GLOBAL_MAGIC = new Permission("customnpcs.global.magic");
public static final Permission GLOBAL_EFFECT = new Permission("customnpcs.global.effect");
@@ -111,6 +112,9 @@ public class CustomNpcsPermissions {
public static final Permission PROFILE_REGION_BYPASS = new Permission("customnpcs.profile.region-bypass");
public static final Permission PROFILE_MAX = new Permission("customnpcs.profile.max.*");
// Auction
public static final Permission AUCTION_TRADES_MAX = new Permission("customnpcs.auction.trades.*");
public static CustomNpcsPermissions Instance;
private static boolean isEnabled;
+403 -141
View File
@@ -1,11 +1,13 @@
package noppes.npcs;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.ability.TelegraphRemovePacket;
import kamkeel.npcs.network.packets.data.ability.TelegraphSpawnPacket;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.AbilitySlot;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
@@ -17,9 +19,7 @@ import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.AbilityEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
@@ -35,34 +35,60 @@ public class DataAbilities {
// CONFIGURATION (saved to NBT)
// ═══════════════════════════════════════════════════════════════════
/** List of abilities this NPC can use */
private List<Ability> abilities = new ArrayList<>();
/**
* List of ability slots this NPC can use (inline or reference).
*/
private List<AbilitySlot> abilitySlots = new ArrayList<>();
/** Whether the ability system is enabled for this NPC */
/**
* Whether the ability system is enabled for this NPC
*/
public boolean enabled = false;
/** Minimum ticks between ability selections (global cooldown) */
public int globalCooldown = 20;
/**
* Minimum cooldown ticks between abilities (global minimum)
*/
public int minCooldown = 80;
/**
* Maximum cooldown ticks between abilities (global maximum)
*/
public int maxCooldown = 200;
// ═══════════════════════════════════════════════════════════════════
// RUNTIME STATE (not saved)
// ═══════════════════════════════════════════════════════════════════
/** Currently executing ability (null if none) */
/**
* Currently executing ability (null if none)
*/
private transient Ability currentAbility;
/** Per-ability cooldown timers (ability ID -> world time when cooldown ends) */
private transient Map<String, Long> cooldowns = new HashMap<>();
/**
* World time when NPC cooldown ends (can select next ability)
*/
private transient long cooldownEndTime = 0;
/** Ticks until next ability can be selected (global cooldown timer) */
private transient int globalCooldownTimer = 0;
/** Last target used for ability execution */
/**
* Last target used for ability execution
*/
private transient EntityLivingBase lastTarget;
/** Recent hit timestamps for hit count condition */
/**
* Recent hit timestamps for hit count condition
*/
private transient List<Long> recentHitTimes = new ArrayList<>();
/**
* Locked rotation values for ACTIVE phase when movement is locked.
* Stored when entering ACTIVE phase, applied every tick to prevent rotation changes.
*/
private transient boolean rotationLocked = false;
private transient float lockedYaw = 0;
private transient float lockedYawHead = 0;
private transient float lockedRenderYawOffset = 0;
private transient float lockedPitch = 0;
// ═══════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════════════
@@ -84,11 +110,6 @@ public class DataAbilities {
return;
}
// Tick global cooldown
if (globalCooldownTimer > 0) {
globalCooldownTimer--;
}
// Tick current ability if executing
if (currentAbility != null && currentAbility.isExecuting()) {
tickCurrentAbility();
@@ -126,9 +147,15 @@ public class DataAbilities {
// Remove telegraph - it has served its purpose
removeTelegraph(currentAbility);
// Lock rotation if movement is locked during ACTIVE phase
// Capture current rotation values to force them every tick
if (currentAbility.isMovementLockedDuringActive()) {
captureLockedRotation();
}
// Play active sound and animation
playAbilitySound(currentAbility.getActiveSound());
playAbilityAnimation(currentAbility.getActiveAnimationId());
playAbilityAnimation(currentAbility.getActiveAnimation());
// Fire execute event (cancelable)
AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent(
@@ -140,59 +167,103 @@ public class DataAbilities {
// Call onExecute
currentAbility.onExecute(npc, target, npc.worldObj);
// Check if ability completed during onExecute (signalCompletion was called)
if (currentAbility.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(target);
return;
}
}
currentAbility.onActiveTick(npc, target, npc.worldObj, currentAbility.getCurrentTick());
// Check if ability completed during onActiveTick (signalCompletion was called)
if (currentAbility.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(target);
return;
}
break;
case RECOVERY:
// Recovery phase - just wait
case DAZED:
// Dazed phase - NPC cannot attack, just wait for daze to end
break;
case IDLE:
// Ability completed
currentAbility.onComplete(npc, target);
// Fire complete event
AbilityEvent.CompleteEvent completeEvent = new AbilityEvent.CompleteEvent(
npc.wrappedNPC, currentAbility, target);
NpcAPI.EVENT_BUS.post(completeEvent);
onAbilityComplete();
// Ability completed (reached via tick() phase transition from DAZED)
handleAbilityCompletion(target);
break;
}
// Clear AI pathfinding if ability is controlling movement
// But DON'T zero motion - let the ability set it if needed
// Apply movement control if ability is still executing
if (currentAbility != null && currentAbility.isExecuting()) {
if (isAbilityControllingMovement()) {
// Clear navigator so AI doesn't fight with ability movement
npc.getNavigator().clearPathEntity();
applyMovementControl();
}
}
// Only zero motion if lockMovement is true AND ability doesn't have its own movement
// This allows stationary abilities to freeze the NPC, while movement abilities can set their own motion
if (currentAbility.isLockMovement() && !currentAbility.hasAbilityMovement()) {
npc.motionX = 0;
npc.motionZ = 0;
}
/**
* Apply movement control based on lock movement settings.
* Called every tick during ability execution.
*/
private void applyMovementControl() {
if (currentAbility == null) return;
// Check if movement should be locked for the current phase
if (currentAbility.isMovementLockedForCurrentPhase()) {
// Clear navigator to prevent AI pathfinding
npc.getNavigator().clearPathEntity();
// Zero motion if ability doesn't have its own movement
// This allows abilities like Charge/Slam to control their own motion
if (!currentAbility.hasAbilityMovement()) {
npc.motionX = 0;
npc.motionZ = 0;
}
}
}
/**
* Handle ability completion - called when ability phase becomes IDLE.
* This can happen from:
* - signalCompletion() called in onExecute() or onActiveTick()
* - tick() transitioning from DAZED to IDLE
*/
private void handleAbilityCompletion(EntityLivingBase target) {
if (currentAbility == null) return;
// Call onComplete callback
currentAbility.onComplete(npc, target);
// Fire complete event
AbilityEvent.CompleteEvent completeEvent = new AbilityEvent.CompleteEvent(
npc.wrappedNPC, currentAbility, target);
NpcAPI.EVENT_BUS.post(completeEvent);
// Release rotation lock before cleanup
releaseLockedRotation();
// Clean up and roll cooldown (this sets currentAbility to null)
onAbilityComplete();
}
/**
* Called when an ability completes.
* Calculates cooldown as: random(minCooldown, maxCooldown) + ability's cooldown offset
*/
private void onAbilityComplete() {
if (currentAbility != null) {
// Stop any ability animation
stopAbilityAnimation();
// Start per-ability cooldown
startCooldown(currentAbility);
// Release rotation lock
releaseLockedRotation();
// Calculate cooldown: random(min, max) + ability offset
int abilityCooldownOffset = currentAbility.getCooldownTicks();
rollCooldown();
// Add ability-specific cooldown offset
cooldownEndTime += abilityCooldownOffset;
currentAbility = null;
lastTarget = null;
// Start global cooldown
globalCooldownTimer = globalCooldown;
}
}
@@ -224,13 +295,14 @@ public class DataAbilities {
* Check if an ability can be selected right now.
*/
public boolean canSelectAbility() {
if (!enabled || abilities.isEmpty()) {
if (!enabled || abilitySlots.isEmpty()) {
return false;
}
if (currentAbility != null && currentAbility.isExecuting()) {
return false;
}
if (globalCooldownTimer > 0) {
// Check if still on cooldown
if (npc.worldObj.getTotalWorldTime() < cooldownEndTime) {
return false;
}
return true;
@@ -243,7 +315,7 @@ public class DataAbilities {
List<Ability> eligible = new ArrayList<>();
int totalWeight = 0;
for (Ability ability : abilities) {
for (Ability ability : getAbilities()) {
if (isAbilityEligible(ability, target)) {
eligible.add(ability);
totalWeight += ability.getWeight();
@@ -276,11 +348,6 @@ public class DataAbilities {
return false;
}
// Check cooldown
if (isOnCooldown(ability)) {
return false;
}
// Check if already executing
if (ability.isExecuting()) {
return false;
@@ -325,7 +392,7 @@ public class DataAbilities {
playAbilitySound(ability.getWindUpSound());
// Play wind up animation if configured
playAbilityAnimation(ability.getWindUpAnimationId());
playAbilityAnimation(ability.getWindUpAnimation());
return true;
}
@@ -341,17 +408,25 @@ public class DataAbilities {
/**
* Play an animation on the NPC by ID.
* Public so abilities can trigger animations directly if needed.
*
* @param animation The animation to play, or null if none
*/
private void playAbilityAnimation(int animationId) {
if (animationId < 0) return;
public void playAbilityAnimation(Animation animation) {
if (animation == null) return;
if (AnimationController.Instance == null) return;
Animation animation = AnimationController.Instance.animations.get(animationId);
if (animation != null) {
npc.display.animationData.setEnabled(true);
npc.display.animationData.setAnimation(animation);
npc.display.animationData.updateClient();
}
npc.display.animationData.setEnabled(true);
npc.display.animationData.setAnimation(animation);
npc.display.animationData.updateClient();
}
public void playAbilityAnimation(int animation) {
if (animation < 0) return;
if (AnimationController.Instance == null) return;
if (AnimationController.Instance.get(animation) == null) return;
playAbilityAnimation((Animation) AnimationController.Instance.get(animation));
}
/**
@@ -390,37 +465,25 @@ public class DataAbilities {
// ═══════════════════════════════════════════════════════════════════
/**
* Check if an ability is on cooldown.
* Check if NPC is on cooldown (cannot use any ability).
*/
public boolean isOnCooldown(Ability ability) {
Long endTime = cooldowns.get(ability.getId());
if (endTime == null) {
return false;
}
return npc.worldObj.getTotalWorldTime() < endTime;
public boolean isOnCooldown() {
return npc.worldObj.getTotalWorldTime() < cooldownEndTime;
}
/**
* Start cooldown for an ability.
* Get remaining cooldown ticks.
*/
private void startCooldown(Ability ability) {
long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks();
cooldowns.put(ability.getId(), endTime);
public long getRemainingCooldown() {
long remaining = cooldownEndTime - npc.worldObj.getTotalWorldTime();
return remaining > 0 ? remaining : 0;
}
/**
* Reset cooldown for a specific ability.
* Reset cooldown (allow immediate ability use).
*/
public void resetCooldown(String abilityId) {
cooldowns.remove(abilityId);
}
/**
* Reset all cooldowns.
*/
public void resetAllCooldowns() {
cooldowns.clear();
globalCooldownTimer = 0;
public void resetCooldown() {
cooldownEndTime = 0;
}
// ═══════════════════════════════════════════════════════════════════
@@ -428,7 +491,7 @@ public class DataAbilities {
// ═══════════════════════════════════════════════════════════════════
/**
* Handle damage taken - may interrupt current ability.
* Handle damage taken - may interrupt current ability or trigger guard counter.
*
* @param source The damage source
* @param amount The damage amount
@@ -438,6 +501,14 @@ public class DataAbilities {
// Track hit for hit count condition
recordHit();
// Check if currently executing a Guard ability and notify it of damage taken
if (currentAbility instanceof AbilityGuard) {
AbilityGuard guard = (AbilityGuard) currentAbility;
if (guard.isGuarding() && source.getEntity() instanceof EntityLivingBase) {
guard.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount);
}
}
if (currentAbility == null || !currentAbility.isExecuting()) {
return false;
}
@@ -450,11 +521,32 @@ public class DataAbilities {
return false;
}
/**
* Get the damage reduction factor if a Guard ability is currently active.
*
* @return The damage reduction factor (0.0 = no reduction, 1.0 = full immunity), or 0 if not guarding
*/
public float getGuardDamageReduction() {
if (currentAbility instanceof AbilityGuard) {
return ((AbilityGuard) currentAbility).getDamageReductionFactor();
}
return 0.0f;
}
/**
* Record a hit for the hit count condition.
* Includes periodic cleanup to prevent memory leak.
*/
private void recordHit() {
recentHitTimes.add(npc.worldObj.getTotalWorldTime());
long currentTime = npc.worldObj.getTotalWorldTime();
recentHitTimes.add(currentTime);
// Cleanup old entries periodically to prevent unbounded growth
// Keep only hits from last 5 minutes (6000 ticks) max
if (recentHitTimes.size() > 50) {
long cutoff = currentTime - 6000;
recentHitTimes.removeIf(time -> time < cutoff);
}
}
/**
@@ -480,6 +572,8 @@ public class DataAbilities {
/**
* Interrupt the currently executing ability.
* If interrupted during WINDUP, the ability will transition to DAZED phase.
* When DAZED completes, the ability will move to IDLE and onAbilityComplete() is called.
*/
public void interruptCurrentAbility(DamageSource source, float damage) {
if (currentAbility != null) {
@@ -489,15 +583,19 @@ public class DataAbilities {
// Stop any ability animation
stopAbilityAnimation();
// Release rotation lock
releaseLockedRotation();
// Fire interrupt event
AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent(
npc.wrappedNPC, currentAbility, lastTarget, source, damage);
NpcAPI.EVENT_BUS.post(interruptEvent);
currentAbility.onInterrupt(npc, source, damage);
currentAbility.interrupt();
currentAbility = null;
lastTarget = null;
currentAbility.interrupt(); // Transitions to DAZED if interrupted during WINDUP
// Don't clear currentAbility - let it tick through DAZED phase
// When DAZED ends and phase becomes IDLE, onAbilityComplete() will be called
}
}
@@ -508,12 +606,57 @@ public class DataAbilities {
if (currentAbility != null) {
removeTelegraph(currentAbility);
stopAbilityAnimation();
releaseLockedRotation();
currentAbility.interrupt();
currentAbility = null;
lastTarget = null;
}
}
/**
* Force start a specific ability, bypassing normal selection and cooldown.
* If an ability is currently executing, it will be cancelled.
*
* @param ability The ability to start
* @param target The target entity (can be null for self-targeted abilities)
* @return true if the ability was started successfully
*/
public boolean forceStartAbility(Ability ability, EntityLivingBase target) {
if (ability == null || npc.worldObj.isRemote) {
return false;
}
// Stop any currently executing ability
stopCurrentAbility();
// Reset the ability state
ability.reset();
// Start the ability directly
return startAbility(ability, target);
}
/**
* Execute an ability on this NPC by key (built-in name or custom UUID).
* The NPC does NOT need to have this ability assigned.
*
* @param key The ability key (built-in name or custom UUID)
* @param target The target entity (can be null for self-targeted abilities)
* @return true if the ability was started successfully
*/
public boolean executeAbility(String key, EntityLivingBase target) {
if (key == null || key.isEmpty() || npc.worldObj.isRemote) {
return false;
}
Ability resolved = AbilityController.Instance.resolveAbility(key);
if (resolved == null) {
return false;
}
return forceStartAbility(resolved, target);
}
// ═══════════════════════════════════════════════════════════════════
// SCRIPT EVENTS
// ═══════════════════════════════════════════════════════════════════
@@ -532,12 +675,12 @@ public class DataAbilities {
* Fire an ability hit event. Called by abilities when they hit an entity.
* Returns null if the event was cancelled, otherwise returns the (possibly modified) event.
*
* @param ability The ability doing the hit
* @param target The original target of the ability
* @param hitEntity The entity being hit
* @param damage The damage amount
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback (deprecated, ignored)
* @param ability The ability doing the hit
* @param target The original target of the ability
* @param hitEntity The entity being hit
* @param damage The damage amount
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback
* @return The event (with possibly modified values), or null if cancelled
*/
public AbilityEvent.HitEvent fireHitEvent(Ability ability, EntityLivingBase target,
@@ -565,54 +708,109 @@ public class DataAbilities {
/**
* Reset all runtime state (cooldowns, current ability).
* Called when NPC respawns or combat ends.
* Rolls cooldown so NPC doesn't immediately use an ability.
*/
public void reset() {
stopCurrentAbility();
resetAllCooldowns();
// Reset execution state on all abilities
for (Ability ability : abilities) {
// Roll cooldown so NPC doesn't immediately attack after reset
rollCooldown();
// Reset execution state on all resolved abilities
for (Ability ability : getAbilities()) {
ability.reset();
}
}
/**
* Roll a new cooldown using the min/max range.
* Called after ability completes and on reset.
*/
private void rollCooldown() {
int baseCooldown = minCooldown;
if (maxCooldown > minCooldown) {
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
}
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown;
}
// ═══════════════════════════════════════════════════════════════════
// ABILITY LIST MANAGEMENT
// ═══════════════════════════════════════════════════════════════════
/**
* Get resolved abilities from all slots, filtering out broken references.
*/
public List<Ability> getAbilities() {
return abilities;
List<Ability> resolved = new ArrayList<>();
for (AbilitySlot slot : abilitySlots) {
Ability a = slot.getAbility();
if (a != null) {
resolved.add(a);
}
}
return resolved;
}
/** Get the raw slot list (for GUI access). */
public List<AbilitySlot> getAbilitySlots() {
return abilitySlots;
}
/** Add an inline ability. */
public void addAbility(Ability ability) {
abilities.add(ability);
abilitySlots.add(AbilitySlot.inline(ability));
}
/** Add a reference ability by key (built-in name or custom UUID). */
public void addAbilityReference(String key) {
abilitySlots.add(AbilitySlot.reference(key));
}
public void removeAbility(int index) {
if (index >= 0 && index < abilities.size()) {
abilities.remove(index);
if (index >= 0 && index < abilitySlots.size()) {
abilitySlots.remove(index);
}
}
public void removeAbility(String id) {
abilities.removeIf(a -> a.getId().equals(id));
abilitySlots.removeIf(slot -> {
if (slot.isReference()) {
return slot.getReferenceId().equals(id);
}
Ability a = slot.getAbility();
return a != null && a.getId().equals(id);
});
}
public Ability getAbility(String id) {
for (Ability ability : abilities) {
if (ability.getId().equals(id)) {
return ability;
for (AbilitySlot slot : abilitySlots) {
Ability a = slot.getAbility();
if (a != null && a.getId().equals(id)) {
return a;
}
}
return null;
}
/** Check if a slot at a given index is a reference. */
public boolean isSlotReference(int index) {
if (index < 0 || index >= abilitySlots.size()) return false;
return abilitySlots.get(index).isReference();
}
/** Convert a reference slot to inline. Returns false if resolution fails. */
public boolean convertToInline(int index) {
if (index < 0 || index >= abilitySlots.size()) return false;
return abilitySlots.get(index).convertToInline();
}
public void clearAbilities() {
abilities.clear();
abilitySlots.clear();
}
public boolean isEmpty() {
return abilities.isEmpty();
return abilitySlots.isEmpty();
}
// ═══════════════════════════════════════════════════════════════════
@@ -636,11 +834,11 @@ public class DataAbilities {
/**
* Check if ability is controlling NPC movement (AI pathfinding should be blocked).
* Called by AI tasks to determine if they should try to path.
*
* <p>
* Rules:
* - WINDUP phase: Block AI if lockMovement is true
* - ACTIVE phase: Block AI if lockMovement OR hasAbilityMovement is true
* - RECOVERY phase: Block AI if lockMovement is true
* - WINDUP phase: Block AI if movement is locked during windup
* - ACTIVE phase: Block AI if movement is locked during active OR hasAbilityMovement is true
* - DAZED phase: Always block AI (NPC is stunned)
*/
public boolean isAbilityControllingMovement() {
if (currentAbility == null || !currentAbility.isExecuting()) {
@@ -651,19 +849,19 @@ public class DataAbilities {
switch (phase) {
case WINDUP:
// During windup, only block if lockMovement is set
// This allows NPC to keep chasing while winding up if lockMovement=false
return currentAbility.isLockMovement();
// During windup, only block if movement is locked during windup
// This allows NPC to keep chasing while winding up if not locked
return currentAbility.isMovementLockedDuringWindup();
case ACTIVE:
// During active phase, block if either:
// - lockMovement is true (stationary ability)
// - movement is locked during active (stationary ability)
// - hasAbilityMovement is true (ability is moving the NPC itself)
return currentAbility.isLockMovement() || currentAbility.hasAbilityMovement();
return currentAbility.isMovementLockedDuringActive() || currentAbility.hasAbilityMovement();
case RECOVERY:
// During recovery, block if lockMovement is set
return currentAbility.isLockMovement();
case DAZED:
// During dazed phase, always block - NPC is stunned from interrupt
return true;
default:
return false;
@@ -671,12 +869,21 @@ public class DataAbilities {
}
/**
* Check if NPC movement should be blocked due to ability execution.
* @deprecated Use isAbilityControllingMovement() instead
* Check if NPC's look direction should be locked to target.
* Only locks during ACTIVE phase when movement is locked during active.
* This allows the NPC to freely track target during WINDUP and DAZED.
*/
@Deprecated
public boolean isMovementBlocked() {
return isAbilityControllingMovement();
public boolean shouldLockLookDirection() {
if (currentAbility == null || !currentAbility.isExecuting()) {
return false;
}
// Only lock look direction during ACTIVE phase
if (currentAbility.getPhase() != AbilityPhase.ACTIVE) {
return false;
}
return currentAbility.isMovementLockedDuringActive();
}
/**
@@ -690,17 +897,72 @@ public class DataAbilities {
return phase == AbilityPhase.WINDUP || phase == AbilityPhase.ACTIVE;
}
// ═══════════════════════════════════════════════════════════════════
// ROTATION LOCKING
// ═══════════════════════════════════════════════════════════════════
/**
* Capture current rotation values to lock NPC's look direction.
* Called when entering ACTIVE phase with movement locked during active.
*/
private void captureLockedRotation() {
lockedYaw = npc.rotationYaw;
lockedYawHead = npc.rotationYawHead;
lockedRenderYawOffset = npc.renderYawOffset;
lockedPitch = npc.rotationPitch;
rotationLocked = true;
}
/**
* Release the rotation lock.
* Called when leaving ACTIVE phase or ability completes.
*/
private void releaseLockedRotation() {
rotationLocked = false;
}
/**
* Apply locked rotation values to the NPC.
* Called AFTER super.onLivingUpdate() in EntityNPCInterface to override
* any rotation changes made by the look helper or AI tasks.
*/
public void applyLockedRotation() {
if (!rotationLocked) {
return;
}
// Force rotation back to locked values
npc.rotationYaw = lockedYaw;
npc.rotationYawHead = lockedYawHead;
npc.renderYawOffset = lockedRenderYawOffset;
npc.rotationPitch = lockedPitch;
// Also set prev values to prevent interpolation jitter
npc.prevRotationYaw = lockedYaw;
npc.prevRotationYawHead = lockedYawHead;
npc.prevRenderYawOffset = lockedRenderYawOffset;
npc.prevRotationPitch = lockedPitch;
}
/**
* Check if rotation is currently locked.
*/
public boolean isRotationLocked() {
return rotationLocked;
}
// ═══════════════════════════════════════════════════════════════════
// NBT SERIALIZATION
// ═══════════════════════════════════════════════════════════════════
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setBoolean("AbilitiesEnabled", enabled);
compound.setInteger("AbilityGlobalCooldown", globalCooldown);
compound.setInteger("AbilityMinCooldown", minCooldown);
compound.setInteger("AbilityMaxCooldown", maxCooldown);
NBTTagList abilityList = new NBTTagList();
for (Ability ability : abilities) {
abilityList.appendTag(ability.writeNBT());
for (AbilitySlot slot : abilitySlots) {
abilityList.appendTag(slot.writeNBT());
}
compound.setTag("Abilities", abilityList);
@@ -709,16 +971,16 @@ public class DataAbilities {
public void readFromNBT(NBTTagCompound compound) {
enabled = compound.getBoolean("AbilitiesEnabled");
globalCooldown = compound.hasKey("AbilityGlobalCooldown") ?
compound.getInteger("AbilityGlobalCooldown") : 20;
minCooldown = compound.getInteger("AbilityMinCooldown");
maxCooldown = compound.getInteger("AbilityMaxCooldown");
abilities.clear();
abilitySlots.clear();
NBTTagList abilityList = compound.getTagList("Abilities", 10);
for (int i = 0; i < abilityList.tagCount(); i++) {
NBTTagCompound abilityNBT = abilityList.getCompoundTagAt(i);
Ability ability = AbilityController.Instance.fromNBT(abilityNBT);
if (ability != null) {
abilities.add(ability);
AbilitySlot slot = AbilitySlot.fromNBT(abilityNBT);
if (slot != null) {
abilitySlots.add(slot);
}
}
}
@@ -18,6 +18,7 @@ import noppes.npcs.roles.JobGuard;
import noppes.npcs.roles.JobHealer;
import noppes.npcs.roles.JobItemGiver;
import noppes.npcs.roles.JobSpawner;
import noppes.npcs.roles.RoleAuctioneer;
import noppes.npcs.roles.RoleBank;
import noppes.npcs.roles.RoleCompanion;
import noppes.npcs.roles.RoleFollower;
@@ -218,6 +219,8 @@ public class DataAdvanced {
npc.roleInterface = new RoleCompanion(npc);
else if (role == EnumRoleType.Mount && !(npc.roleInterface instanceof RoleMount))
npc.roleInterface = new RoleMount(npc);
else if (role == EnumRoleType.Auctioneer && !(npc.roleInterface instanceof RoleAuctioneer))
npc.roleInterface = new RoleAuctioneer(npc);
}
public void setJob(int i) {
+31 -24
View File
@@ -38,9 +38,7 @@ import noppes.npcs.controllers.CustomGuiController;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.EffectScript;
import noppes.npcs.controllers.data.ForgeDataScript;
import noppes.npcs.controllers.data.INpcScriptHandler;
import noppes.npcs.controllers.data.IScriptBlockHandler;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.Party;
@@ -64,6 +62,7 @@ import noppes.npcs.scripted.event.RecipeScriptEvent;
import noppes.npcs.scripted.event.player.CustomGuiEvent;
import noppes.npcs.scripted.event.player.DialogEvent;
import noppes.npcs.scripted.event.player.FactionEvent;
import noppes.npcs.scripted.event.player.PlayerAbilityEvent;
import noppes.npcs.scripted.event.player.PlayerEvent;
import noppes.npcs.scripted.event.player.PlayerEvent.ChatEvent;
import noppes.npcs.scripted.event.player.PlayerEvent.ContainerOpen;
@@ -85,7 +84,7 @@ public class EventHooks {
}
public static void onScriptItemInit(IItemCustomizable item) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
if (handler != null && !handler.isClient()) {
ItemEvent.InitEvent event = new ItemEvent.InitEvent(item);
handler.callScript(EnumScriptType.INIT, event);
@@ -94,7 +93,7 @@ public class EventHooks {
}
public static void onScriptItemUpdate(IItemCustomizable item, EntityLivingBase player) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
if (handler != null && !handler.isClient()) {
ItemEvent.UpdateEvent event = new ItemEvent.UpdateEvent(item, NpcAPI.Instance().getIEntity(player));
handler.callScript(EnumScriptType.TICK, event);
@@ -103,7 +102,7 @@ public class EventHooks {
}
public static boolean onScriptItemTossed(IItemCustomizable item, EntityPlayer player, EntityItem entity) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.TossedEvent event = new ItemEvent.TossedEvent(item, (IPlayer) NpcAPI.Instance().getIEntity(player), NpcAPI.Instance().getIEntity(entity));
if (handler != null) {
handler.callScript(EnumScriptType.TOSSED, event);
@@ -112,7 +111,7 @@ public class EventHooks {
}
public static boolean onScriptItemPickedUp(IItemCustomizable item, EntityPlayer player) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.PickedUpEvent event = new ItemEvent.PickedUpEvent(item, (IPlayer) NpcAPI.Instance().getIEntity(player));
if (handler != null) {
handler.callScript(EnumScriptType.PICKEDUP, event);
@@ -121,7 +120,7 @@ public class EventHooks {
}
public static boolean onScriptItemSpawn(IItemCustomizable item, EntityItem entity) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.SpawnEvent event = new ItemEvent.SpawnEvent(item, NpcAPI.Instance().getIEntity(entity));
if (handler != null) {
handler.callScript(EnumScriptType.SPAWN, event);
@@ -130,7 +129,7 @@ public class EventHooks {
}
public static boolean onScriptItemInteract(IItemCustomizable item, noppes.npcs.scripted.event.ItemEvent.InteractEvent event) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
if (handler != null) {
handler.callScript(EnumScriptType.INTERACT, event);
}
@@ -138,7 +137,7 @@ public class EventHooks {
}
public static boolean onScriptItemRightClick(IItemCustomizable item, noppes.npcs.scripted.event.ItemEvent.RightClickEvent event) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
if (handler != null) {
handler.callScript(EnumScriptType.RIGHT_CLICK, event);
}
@@ -146,7 +145,7 @@ public class EventHooks {
}
public static boolean onScriptItemAttack(IItemCustomizable item, noppes.npcs.scripted.event.ItemEvent.AttackEvent event) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
if (handler != null) {
handler.callScript(EnumScriptType.ATTACK, event);
}
@@ -154,7 +153,7 @@ public class EventHooks {
}
public static boolean onStartUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.StartUsingItem event = new ItemEvent.StartUsingItem(item, player, duration);
if (handler != null) {
handler.callScript(EnumScriptType.START_USING_ITEM, event);
@@ -163,7 +162,7 @@ public class EventHooks {
}
public static boolean onUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.UsingItem event = new ItemEvent.UsingItem(item, player, duration);
if (handler != null) {
handler.callScript(EnumScriptType.USING_ITEM, event);
@@ -172,7 +171,7 @@ public class EventHooks {
}
public static boolean onStopUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.StopUsingItem event = new ItemEvent.StopUsingItem(item, player, duration);
if (handler != null) {
handler.callScript(EnumScriptType.STOP_USING_ITEM, event);
@@ -181,7 +180,7 @@ public class EventHooks {
}
public static boolean onFinishUsingCustomItem(IItemCustomizable item, IPlayer player, int duration) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.FinishUsingItem event = new ItemEvent.FinishUsingItem(item, player, duration);
if (handler != null) {
handler.callScript(EnumScriptType.FINISH_USING_ITEM, event);
@@ -190,7 +189,7 @@ public class EventHooks {
}
public static void onRepairCustomItem(IItemCustomizable item, IPlayer player, IItemStack left, IItemStack right, float anvilBreakChance) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.RepairItem event = new ItemEvent.RepairItem(item, player, left, right, anvilBreakChance);
if (handler != null) {
handler.callScript(EnumScriptType.REPAIR_ITEM, event);
@@ -199,7 +198,7 @@ public class EventHooks {
}
public static void onBreakCustomItem(IItemCustomizable item, IPlayer player) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
ItemEvent.BreakItem event = new ItemEvent.BreakItem(item, player);
if (handler != null) {
handler.callScript(EnumScriptType.BREAK_ITEM, event);
@@ -242,7 +241,7 @@ public class EventHooks {
public static void onLinkedItemVersionChange(IItemLinked item, int version, int prevVersion) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
LinkedItemEvent.VersionChangeEvent event = new LinkedItemEvent.VersionChangeEvent(item, version, prevVersion);
if (handler != null) {
handler.callScript(EnumScriptType.LINKED_ITEM_VERSION, event);
@@ -251,7 +250,7 @@ public class EventHooks {
}
public static void onLinkedItemBuild(IItemLinked item) {
INpcScriptHandler handler = (INpcScriptHandler) item.getScriptHandler();
IScriptHandler handler = (IScriptHandler) item.getScriptHandler();
LinkedItemEvent.BuildEvent event = new LinkedItemEvent.BuildEvent(item);
if (handler != null) {
handler.callScript(EnumScriptType.LINKED_ITEM_BUILD, event);
@@ -298,7 +297,6 @@ public class EventHooks {
NpcEvent.DialogClosedEvent event = new NpcEvent.DialogClosedEvent(npc.wrappedNPC, player, dialogId, optionId, dialog);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.DIALOG_CLOSE, event);
npc.script.callScript(EnumScriptType.DIALOG_CLOSE, event, "player", event.getPlayer(), "dialog", event.getDialogId(), "option", event.getOptionId(), "dialogObj", event.getDialog());
NpcAPI.EVENT_BUS.post(event);
}
@@ -421,7 +419,9 @@ public class EventHooks {
EntityLivingBase thrower = projectile.getThrower();
if (thrower != null) {
if (thrower instanceof EntityNPCInterface) {
((EntityNPCInterface) thrower).script.callScript(EnumScriptType.PROJECTILE_TICK, event);
EntityNPCInterface npc = (EntityNPCInterface) thrower;
npc.script.callScript(EnumScriptType.PROJECTILE_TICK, event);
}
}
@@ -439,7 +439,9 @@ public class EventHooks {
EntityLivingBase thrower = projectile.getThrower();
if (thrower != null) {
if (thrower instanceof EntityNPCInterface) {
((EntityNPCInterface) thrower).script.callScript(EnumScriptType.PROJECTILE_IMPACT, event);
EntityNPCInterface npc = (EntityNPCInterface) thrower;
npc.script.callScript(EnumScriptType.PROJECTILE_IMPACT, event);
}
}
@@ -489,21 +491,21 @@ public class EventHooks {
public static boolean onEffectAdded(IPlayer player, IPlayerEffect effect) {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
PlayerEvent.EffectEvent.Added event = new PlayerEvent.EffectEvent.Added(player, effect);
handler.callScript(EffectScript.ScriptType.OnEffectAdd.function, event);
handler.callScript(EnumScriptType.ON_EFFECT_ADD.function, event);
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onEffectTick(IPlayer player, IPlayerEffect effect) {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
PlayerEvent.EffectEvent.Ticked event = new PlayerEvent.EffectEvent.Ticked(player, effect);
handler.callScript(EffectScript.ScriptType.OnEffectTick.function, event);
handler.callScript(EnumScriptType.ON_EFFECT_TICK.function, event);
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onEffectRemove(IPlayer player, IPlayerEffect effect, EffectEvent.ExpirationType type) {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
PlayerEvent.EffectEvent.Removed event = new PlayerEvent.EffectEvent.Removed(player, effect, type);
handler.callScript(EffectScript.ScriptType.OnEffectRemove.function, event);
handler.callScript(EnumScriptType.ON_EFFECT_REMOVE.function, event);
return NpcAPI.EVENT_BUS.post(event);
}
@@ -691,6 +693,11 @@ public class EventHooks {
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onPlayerAbilityHit(PlayerDataScript handler, PlayerAbilityEvent.HitEvent event) {
handler.callScript(EnumScriptType.ABILITY_HIT, event);
return NpcAPI.EVENT_BUS.post(event);
}
public static void onPlayerChangeDim(PlayerDataScript handler, IPlayer player, int fromDim, int toDim) {
PlayerEvent.ChangedDimension event = new PlayerEvent.ChangedDimension(player, fromDim, toDim);
handler.callScript(EnumScriptType.CHANGED_DIM, event);
+9 -14
View File
@@ -6,8 +6,8 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptUnit;
import java.util.ArrayList;
import java.util.HashMap;
@@ -540,38 +540,33 @@ public class NBTTags {
}
}
public static List<ScriptContainer> GetScriptOld(NBTTagList list, IScriptHandler handler) {
ArrayList scripts = new ArrayList();
public static List<IScriptUnit> GetScriptOld(NBTTagList list, IScriptHandler handler) {
ArrayList<IScriptUnit> scripts = new ArrayList<>();
for (int i = 0; i < list.tagCount(); ++i) {
NBTTagCompound compoundd = list.getCompoundTagAt(i);
ScriptContainer script = new ScriptContainer(handler);
script.readFromNBT(compoundd);
IScriptUnit script = IScriptUnit.createFromNBT(compoundd, handler);
scripts.add(script);
}
return scripts;
}
public static List<ScriptContainer> GetScript(NBTTagCompound compound, IScriptHandler handler) {
ArrayList<ScriptContainer> scripts = new ArrayList<>();
public static List<IScriptUnit> GetScript(NBTTagCompound compound, IScriptHandler handler) {
ArrayList<IScriptUnit> scripts = new ArrayList<>();
for (int i = 0; i < compound.getInteger("TotalScripts"); ++i) {
NBTTagCompound containerCompound = compound.getCompoundTag("Tab" + i);
ScriptContainer script = new ScriptContainer(handler);
script.readFromNBT(containerCompound);
IScriptUnit script = IScriptUnit.createFromNBT(containerCompound, handler);
scripts.add(script);
}
return scripts;
}
public static NBTTagList NBTScript(List<ScriptContainer> scripts) {
public static NBTTagList NBTScript(List<IScriptUnit> scripts) {
NBTTagList list = new NBTTagList();
Iterator var2 = scripts.iterator();
while (var2.hasNext()) {
ScriptContainer script = (ScriptContainer) var2.next();
for (IScriptUnit script : scripts) {
NBTTagCompound compound = new NBTTagCompound();
script.writeToNBT(compound);
list.appendTag(compound);
@@ -4,7 +4,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.StatCollector;
import noppes.npcs.entity.EntityNPCInterface;
import java.awt.*;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
@@ -306,18 +306,18 @@ public class NoppesUtilPlayer {
if (dialog == null)
return;
DialogOption option = dialog.options.get(optionId);
if (EventHooks.onDialogOption(player, new DialogEvent.DialogOption((IPlayer) NpcAPI.Instance().getIEntity(player), dialog)))
if (EventHooks.onDialogOption(player, new DialogEvent.DialogOption((IPlayer) NpcAPI.Instance().getIEntity(player), dialogId, optionId, dialog)))
return;
if (!npc.isRemote()) {
EventHooks.onNPCDialogClosed(npc, player, dialogId, optionId + 1, dialog);
if (!dialog.hasDialogs(player) && !dialog.hasOtherOptions()) {
EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialog));
EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialogId, optionId, dialog));
return;
}
if (option == null || option.optionType == EnumOptionType.DialogOption && (!option.isAvailable(player) || !option.hasDialog()) || option.optionType == EnumOptionType.Disabled || option.optionType == EnumOptionType.QuitOption) {
EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialog));
EventHooks.onDialogClosed(player, new DialogEvent.DialogClosed((IPlayer) NpcAPI.Instance().getIEntity(player), dialogId, optionId, dialog));
return;
}
}
@@ -163,7 +163,16 @@ public class NoppesUtilServer {
for (Animation animation : AnimationController.getInstance().animations.values()) {
map.put(animation.name, animation.id);
}
sendScrollData(player, map, EnumScrollData.OPTIONAL);
sendScrollData(player, map, EnumScrollData.ANIMATIONS);
}
public static void sendBuiltInAnimationData(EntityPlayerMP player) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (String name : AnimationController.getInstance().builtInAnimations.keySet()) {
// Use -1 as a marker for built-in animations (they have no ID)
map.put(AnimationController.getInstance().builtInAnimations.get(name).getName(), -1);
}
sendScrollData(player, map, EnumScrollData.BUILTIN_ANIMATIONS);
}
public static void sendTagDataAll(EntityPlayerMP player) {
@@ -241,7 +250,7 @@ public class NoppesUtilServer {
if (EventHooks.onNPCDialog(npc, player, dialog.id, optionId, dialog)) {
return;
}
if (EventHooks.onDialogOpen(player, new DialogEvent.DialogOpen((IPlayer) NpcAPI.Instance().getIEntity(player), dialog))) {
if (EventHooks.onDialogOpen(player, new DialogEvent.DialogOpen((IPlayer) NpcAPI.Instance().getIEntity(player), dialog.id, optionId, dialog))) {
return;
}
}
@@ -776,6 +785,20 @@ public class NoppesUtilServer {
sendScrollData(player, map, EnumScrollData.ABILITY_TYPES);
}
public static void sendCustomAbilitiesData(EntityPlayerMP player) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
kamkeel.npcs.controllers.data.ability.AbilityController controller = kamkeel.npcs.controllers.data.ability.AbilityController.Instance;
if (controller != null) {
int index = 0;
for (String uuid : controller.getCustomAbilityIds()) {
String name = controller.getCustomAbilityName(uuid);
if (name == null || name.isEmpty()) name = uuid;
map.put(name + "\t" + uuid, index++);
}
}
sendScrollData(player, map, EnumScrollData.CUSTOM_ABILITIES);
}
public static DialogOption setNpcDialog(int slot, int dialogId, EntityPlayer player) throws IOException {
return setNpcDialog(slot, dialogId, getEditingNpc(player));
}
@@ -36,6 +36,10 @@ public class ScriptForgeEventHandler {
@SubscribeEvent
public void forgeEntity(Event event) {
if (CustomNpcs.getServer() != null && ScriptController.Instance.forgeScripts.isEnabled()) {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
return;
}
if (event instanceof TickEvent && !(((TickEvent) event).side == Side.SERVER && ((TickEvent) event).phase == TickEvent.Phase.START)) {
return;
}
@@ -62,7 +62,6 @@ import noppes.npcs.items.ItemNpcTool;
import noppes.npcs.quests.QuestItem;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.item.ScriptCustomizableItem;
import noppes.npcs.scripted.item.ScriptItemStack;
import static noppes.npcs.config.ConfigMain.TrackedQuestUpdateFrequency;
@@ -98,6 +97,13 @@ public class ScriptPlayerEventHandler {
if (PlayerDataController.Instance != null) {
PlayerData playerData = PlayerData.get(player);
playerData.actionManager.tick();
playerData.abilityData.tick(player);
// Lock player movement during ability phases that require it
if (playerData.abilityData.isMovementLocked()) {
player.motionX = 0;
player.motionZ = 0;
}
if (playerData.updateClient) {
SyncController.syncPlayerData((EntityPlayerMP) player, true);
@@ -549,7 +555,7 @@ public class ScriptPlayerEventHandler {
if (event.source.getEntity() instanceof EntityPlayerMP) {
EntityPlayerMP playerMP = (EntityPlayerMP) event.source.getEntity();
if(playerMP.getHeldItem() != null) {
if (playerMP.getHeldItem() != null) {
IItemStack itemStack = NpcAPI.Instance().getIItemStack(playerMP.getHeldItem());
if (itemStack instanceof ScriptCustomizableItem) {
ScriptCustomizableItem sci = (ScriptCustomizableItem) itemStack;
@@ -51,7 +51,6 @@ import noppes.npcs.controllers.ServerCloneController;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.Line;
import noppes.npcs.controllers.data.LinkedItem;
import noppes.npcs.controllers.data.MarkData;
import noppes.npcs.controllers.data.Party;
import noppes.npcs.controllers.data.PlayerData;
@@ -60,7 +59,6 @@ import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestData;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.items.ItemExcalibur;
import noppes.npcs.items.ItemLinked;
import noppes.npcs.items.ItemShield;
import noppes.npcs.items.ItemSoulstoneEmpty;
import noppes.npcs.quests.QuestKill;
@@ -6,16 +6,13 @@ import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import noppes.npcs.controllers.AuctionController;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import noppes.npcs.client.AnalyticsTracking;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.controllers.data.action.ActionManager;
import java.net.InetAddress;
import java.net.UnknownHostException;
import noppes.npcs.entity.EntityNPCInterface;
public class ServerTickHandler {
@@ -23,6 +20,11 @@ public class ServerTickHandler {
public void onServerTick(TickEvent.ServerTickEvent event) {
if (event.phase == Phase.END) {
ActionManager.GLOBAL.tick();
// Process auction system tick
if (AuctionController.Instance != null) {
AuctionController.Instance.onServerTick();
}
}
}
@@ -38,25 +40,6 @@ public class ServerTickHandler {
@SubscribeEvent
public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) {
EntityPlayerMP player = (EntityPlayerMP) event.player;
// Temporary Disabled
// if (serverName == null) {
// String e = "local";
// MinecraftServer server = MinecraftServer.getServer();
// if (server.isDedicatedServer()) {
// try {
// e = InetAddress.getByName(server.getServerHostname()).getCanonicalHostName();
// } catch (UnknownHostException e1) {
// e = MinecraftServer.getServer().getServerHostname();
// }
// if (server.getPort() != 25565)
// e += ":" + server.getPort();
// }
// if (e == null || e.startsWith("192.168") || e.contains("127.0.0.1") || e.startsWith("localhost"))
// e = "local";
// serverName = e;
// }
// AnalyticsTracking.sendData(event.player, "join", serverName);
PlayerData playerData = PlayerData.get(event.player);
if (playerData != null) {
playerData.onLogin();
@@ -65,6 +48,12 @@ public class ServerTickHandler {
ProfileController.Instance.login(player);
SyncController.beginLogin(player);
SyncController.syncEffects(player);
ScriptController.Instance.syncClientScripts(player);
// Send auction notifications on login
if (AuctionController.Instance != null) {
AuctionController.Instance.onPlayerLogin(player);
}
}
@SubscribeEvent
@@ -79,6 +68,11 @@ public class ServerTickHandler {
playerData.onLogout();
}
// Clear auction permission cache on logout
if (AuctionController.Instance != null) {
AuctionController.Instance.onPlayerLogout(event.player.getUniqueID());
}
// Save and unload the player's profile data on logout
ProfileController.Instance.logout(event.player);
}
@@ -179,10 +179,10 @@ public class CombatHandler {
}
/**
* Check if NPC movement should be blocked due to ability execution.
* Check if ability is controlling NPC movement (AI pathfinding should be blocked).
*/
public boolean isMovementBlocked() {
return npc.abilities.isMovementBlocked();
public boolean isAbilityControllingMovement() {
return npc.abilities.isAbilityControllingMovement();
}
/**
@@ -41,8 +41,14 @@ public class BlockWaypoint extends BlockContainer {
@Override
public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityliving, ItemStack item) {
if (entityliving instanceof EntityPlayer && world.isRemote) {
CustomNpcs.proxy.openGui(i, j, k, EnumGuiType.Waypoint, (EntityPlayer) entityliving);
if (entityliving instanceof EntityPlayer) {
if (!world.isRemote) {
// Server-side: sync TileEntity data to client and open GUI (same as onBlockActivated)
TileEntity tile = world.getTileEntity(i, j, k);
NBTTagCompound compound = new NBTTagCompound();
tile.writeToNBT(compound);
PacketHandler.Instance.sendToPlayer(new GuiWaypointPacket(compound), (EntityPlayerMP) entityliving);
}
}
}
@@ -3,6 +3,7 @@ package noppes.npcs.blocks.tiles;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.network.packets.request.script.BlockScriptPacket;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.ITickable;
import net.minecraft.item.Item;
@@ -25,9 +26,11 @@ import noppes.npcs.api.IBlock;
import noppes.npcs.api.block.ITextPlane;
import noppes.npcs.client.renderer.blocks.BlockScriptedRenderer;
import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.IScriptBlockHandler;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.entity.data.DataTimers;
import noppes.npcs.scripted.BlockScriptedWrapper;
import noppes.npcs.util.ValueUtil;
@@ -36,11 +39,9 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class TileScripted extends TileEntity implements IScriptBlockHandler {
public List<ScriptContainer> scripts = new ArrayList<>();
public class TileScripted extends TileEntity implements IScriptBlockHandler, IScriptHandlerPacket {
public List<IScriptUnit> scripts = new ArrayList<>();
public Map<String, Object> tempData = new HashMap<>();
@@ -161,6 +162,36 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler {
text6.setNBT(compound.getCompoundTag("Text6"));
}
@Override
public ScriptContext getContext() {
return ScriptContext.BLOCK;
}
@Override
public void requestData() {
BlockScriptPacket.Get(this.xCoord, this.yCoord, this.zCoord);
}
@Override
public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) {
BlockScriptPacket.Save(this.xCoord, this.yCoord, this.zCoord, nbt);
}
@Override
public GuiDataResult setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
return new GuiDataResult(GuiDataKind.LOAD_COMPLETE, -1);
}
setNBT(compound);
return new GuiDataResult(GuiDataKind.METADATA, -1);
}
@Override
public void sync() {
sendSavePacket(-1, getScripts().size(), getNBT(new NBTTagCompound()));
}
@Override
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
@@ -367,7 +398,7 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler {
EventHooks.onScriptBlockInit(this);
}
for (ScriptContainer script : scripts) {
for (IScriptUnit script : scripts) {
script.run(type, event);
}
}
@@ -408,34 +439,15 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler {
}
@Override
public void setScripts(List<ScriptContainer> list) {
public void setScripts(List<IScriptUnit> list) {
scripts = list;
}
@Override
public List<ScriptContainer> getScripts() {
public List<IScriptUnit> getScripts() {
return scripts;
}
@Override
public Map<Long, String> getConsoleText() {
Map<Long, String> map = new TreeMap<>();
int tab = 0;
for (ScriptContainer script : getScripts()) {
tab++;
for (Entry<Long, String> entry : script.console.entrySet()) {
map.put(entry.getKey(), " tab " + tab + ":\n" + entry.getValue());
}
}
return map;
}
@Override
public void clearConsole() {
for (ScriptContainer script : getScripts()) {
script.console.clear();
}
}
@SideOnly(Side.CLIENT)
@Override
@@ -1,53 +0,0 @@
package noppes.npcs.client;
import net.minecraft.entity.player.EntityPlayer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
public class AnalyticsTracking {
public static void sendData(final EntityPlayer player, final String event, final String data) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UUID uuid = player.getUniqueID();
String analyticsPostData = "v=1" +
"&tid=UA-29079943-5" +
"&cid=" + uuid.toString() +
"&t=event" +
"&ec=customnpcs_1.7d" +
"&ea=" + event +
"&el=" + data +
"&ev=300";
URL url = new URL("http://www.google-analytics.com/collect");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(analyticsPostData.getBytes().length));
OutputStream dataOutput = connection.getOutputStream();
dataOutput.write(analyticsPostData.getBytes());
dataOutput.close();
connection.getInputStream().close();
} catch (IOException e) {
}
}
};
Thread t = new Thread(r);
t.start();
}
}
@@ -0,0 +1,66 @@
package noppes.npcs.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.nbt.NBTTagCompound;
/**
* Client-side cache for auction configuration synced from server.
* Prevents client from using local ConfigMarket which may differ from server settings.
*
* IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in
* AuctionConfigSync to avoid @SideOnly crashes on dedicated servers.
*/
@SideOnly(Side.CLIENT)
public class AuctionClientConfig {
// Cached values from server
private static long listingFee = 0;
private static String currencyName = "Coins";
private static int auctionDurationHours = 24;
private static double minBidIncrement = 0.05;
private static int maxActiveListings = 8;
private static int claimExpirationDays = 20;
private static boolean auctionEnabled = false;
/**
* Update cached config from server NBT data.
* Called when receiving login packet.
*/
public static void readFromNBT(NBTTagCompound compound) {
if (compound == null) return;
auctionEnabled = compound.getBoolean("AuctionEnabled");
listingFee = compound.getLong("ListingFee");
currencyName = compound.getString("CurrencyName");
auctionDurationHours = compound.getInteger("AuctionDurationHours");
minBidIncrement = compound.getDouble("MinBidIncrement");
maxActiveListings = compound.getInteger("MaxActiveListings");
claimExpirationDays = compound.getInteger("ClaimExpirationDays");
if (currencyName.isEmpty()) {
currencyName = "Gold";
}
}
/**
* Reset to defaults (called on disconnect).
*/
public static void reset() {
listingFee = 0;
currencyName = "Coins";
auctionDurationHours = 24;
minBidIncrement = 0.05;
maxActiveListings = 8;
claimExpirationDays = 20;
auctionEnabled = false;
}
// Getters
public static boolean isAuctionEnabled() { return auctionEnabled; }
public static long getListingFee() { return listingFee; }
public static String getCurrencyName() { return currencyName; }
public static int getAuctionDurationHours() { return auctionDurationHours; }
public static double getMinBidIncrement() { return minBidIncrement; }
public static int getMaxActiveListings() { return maxActiveListings; }
public static int getClaimExpirationDays() { return claimExpirationDays; }
}
@@ -1,5 +1,6 @@
package noppes.npcs.client;
import kamkeel.npcs.network.enums.EnumSyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.controllers.MusicController;
@@ -15,7 +16,6 @@ import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.Party;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.SkinOverlay;
import kamkeel.npcs.network.enums.EnumSyncType;
import noppes.npcs.util.CacheHashMap;
import java.util.EnumMap;
@@ -6,6 +6,8 @@ import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import kamkeel.npcs.addon.client.DBCClient;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.model.ModelBiped;
@@ -21,7 +23,9 @@ import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Achievement;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ReportedException;
import net.minecraft.util.ResourceLocation;
@@ -83,6 +87,7 @@ import noppes.npcs.client.gui.global.GuiNPCManageAnimations;
import noppes.npcs.client.gui.global.GuiNPCManageBanks;
import noppes.npcs.client.gui.global.GuiNPCManageDialogs;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import noppes.npcs.client.gui.global.GuiNpcManageAbilities;
import noppes.npcs.client.gui.global.GuiNPCManageFactions;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.global.GuiNPCManageQuest;
@@ -104,6 +109,10 @@ import noppes.npcs.client.gui.player.GuiCrate;
import noppes.npcs.client.gui.player.GuiMailbox;
import noppes.npcs.client.gui.player.GuiMailmanWrite;
import noppes.npcs.client.gui.player.GuiNPCBankChest;
import noppes.npcs.client.gui.player.GuiAuctionBidding;
import noppes.npcs.client.gui.player.GuiAuctionTrades;
import noppes.npcs.client.gui.player.GuiAuctionListing;
import noppes.npcs.client.gui.player.GuiAuctionSell;
import noppes.npcs.client.gui.player.GuiNPCTrader;
import noppes.npcs.client.gui.player.GuiNpcAnvil;
import noppes.npcs.client.gui.player.GuiNpcCarpentryBench;
@@ -120,9 +129,9 @@ import noppes.npcs.client.gui.roles.GuiNpcFollowerSetup;
import noppes.npcs.client.gui.roles.GuiNpcItemGiver;
import noppes.npcs.client.gui.roles.GuiNpcTraderSetup;
import noppes.npcs.client.gui.roles.GuiNpcTransporter;
import noppes.npcs.client.gui.script.GuiScriptBlock;
import noppes.npcs.client.gui.script.GuiScriptGlobal;
import noppes.npcs.client.gui.script.GuiScriptItem;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.script.PackageFinder;
import noppes.npcs.client.model.ModelNPCGolem;
import noppes.npcs.client.model.ModelNpcCrystal;
import noppes.npcs.client.model.ModelNpcDragon;
@@ -136,8 +145,17 @@ import noppes.npcs.client.renderer.RenderNpcCrystal;
import noppes.npcs.client.renderer.RenderNpcDragon;
import noppes.npcs.client.renderer.RenderNpcSlime;
import noppes.npcs.client.renderer.RenderProjectile;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphManager;
import kamkeel.npcs.client.renderer.RenderAbilityOrb;
import kamkeel.npcs.client.renderer.RenderAbilityDisc;
import kamkeel.npcs.client.renderer.RenderAbilityLaser;
import kamkeel.npcs.client.renderer.RenderAbilityBeam;
import kamkeel.npcs.client.renderer.RenderAbilitySweeper;
import kamkeel.npcs.client.renderer.lightning.LightningHandler;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import noppes.npcs.client.renderer.blocks.BlockBannerRenderer;
import noppes.npcs.client.renderer.blocks.BlockBarrelRenderer;
import noppes.npcs.client.renderer.blocks.BlockBeamRenderer;
@@ -191,6 +209,11 @@ import noppes.npcs.containers.ContainerNPCFollower;
import noppes.npcs.containers.ContainerNPCFollowerHire;
import noppes.npcs.containers.ContainerNPCFollowerSetup;
import noppes.npcs.containers.ContainerNPCInv;
import noppes.npcs.containers.ContainerAuction;
import noppes.npcs.containers.ContainerAuctionBidding;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerNPCTrader;
import noppes.npcs.containers.ContainerNPCTraderSetup;
import noppes.npcs.containers.ContainerNpcItemGiver;
@@ -211,6 +234,7 @@ import noppes.npcs.entity.data.ModelPartData;
import noppes.npcs.items.ItemLinked;
import noppes.npcs.items.ItemNpcTool;
import noppes.npcs.items.ItemScripted;
import noppes.npcs.scripted.item.ScriptCustomItem;
import org.lwjgl.input.Keyboard;
import tconstruct.client.tabs.InventoryTabCustomNpc;
import tconstruct.client.tabs.InventoryTabVanilla;
@@ -239,6 +263,11 @@ public class ClientProxy extends CommonProxy {
RenderingRegistry.registerEntityRenderingHandler(EntityNpcDragon.class, new RenderNpcDragon(new ModelNpcDragon(0.0F), 0.5F));
RenderingRegistry.registerEntityRenderingHandler(EntityNpcSlime.class, new RenderNpcSlime(new ModelNpcSlime(16), new ModelNpcSlime(0), 0.25F));
RenderingRegistry.registerEntityRenderingHandler(EntityProjectile.class, new RenderProjectile());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityOrb.class, new RenderAbilityOrb());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityDisc.class, new RenderAbilityDisc());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam());
RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper());
RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc());
@@ -291,7 +320,7 @@ public class ClientProxy extends CommonProxy {
Minecraft mc = Minecraft.getMinecraft();
NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc");
SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_C, "key.categories.customnpc");
SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_B, "key.categories.customnpc");
ClientRegistry.registerKeyBinding(NPCButton);
ClientRegistry.registerKeyBinding(SpecialKey);
@@ -312,6 +341,9 @@ public class ClientProxy extends CommonProxy {
TelegraphManager.initClient();
MinecraftForge.EVENT_BUS.register(new TelegraphRenderer());
// Lightning effect rendering system
MinecraftForge.EVENT_BUS.register(new LightningHandler());
if (ConfigClient.InventoryGuiEnabled) {
MinecraftForge.EVENT_BUS.register(new TabRegistry());
if (TabRegistry.getTabList().isEmpty()) {
@@ -466,6 +498,20 @@ public class ClientProxy extends CommonProxy {
else if (gui == EnumGuiType.ManageEffects)
return new GuiNPCManageEffects(npc);
else if (gui == EnumGuiType.ManageAbilities) {
EntityCustomNpc abilityNpc;
if (npc != null) {
abilityNpc = new EntityCustomNpc(npc.worldObj);
abilityNpc.copyDataFrom(npc, true);
abilityNpc.display.showName = 1;
abilityNpc.display.showBossBar = 0;
} else {
abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld);
abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png";
}
return new GuiNpcManageAbilities(abilityNpc);
}
else if (gui == EnumGuiType.MainMenuGlobal)
return new GuiNPCGlobalMainMenu(npc);
@@ -481,6 +527,18 @@ public class ClientProxy extends CommonProxy {
else if (gui == EnumGuiType.PlayerTrader)
return new GuiNPCTrader(npc, (ContainerNPCTrader) container);
else if (gui == EnumGuiType.PlayerAuction)
return new GuiAuctionListing(npc, (ContainerAuctionListing) container);
else if (gui == EnumGuiType.PlayerAuctionSell)
return new GuiAuctionSell(npc, (ContainerAuctionSell) container);
else if (gui == EnumGuiType.PlayerAuctionTrades)
return new GuiAuctionTrades(npc, (ContainerAuctionTrades) container);
else if (gui == EnumGuiType.PlayerAuctionBidding)
return new GuiAuctionBidding(npc, (ContainerAuctionBidding) container);
else if (gui == EnumGuiType.PlayerBankSmall || gui == EnumGuiType.PlayerBankUnlock || gui == EnumGuiType.PlayerBankUprade || gui == EnumGuiType.PlayerBankLarge)
return new GuiNPCBankChest(npc, (ContainerNPCBankInterface) container);
@@ -491,7 +549,7 @@ public class ClientProxy extends CommonProxy {
return new GuiScript(npc);
else if (gui == EnumGuiType.ScriptItem)
return new GuiScriptItem();
return GuiScriptInterface.create(null, new ScriptCustomItem(new ItemStack(CustomItems.scripted_item)));
else if (gui == EnumGuiType.PlayerCarpentryBench)
return new GuiNpcCarpentryBench((ContainerCarpentryBench) container);
@@ -566,7 +624,7 @@ public class ClientProxy extends CommonProxy {
return new GuiCustom((ContainerCustomGui) container);
else if (gui == EnumGuiType.ScriptBlock)
return new GuiScriptBlock(x, y, z);
return getScriptBlockGui(x, y, z);
else if (gui == EnumGuiType.Paintbrush)
return new GuiNpcPaintbrush();
@@ -618,9 +676,22 @@ public class ClientProxy extends CommonProxy {
if (guiscreen != null) {
minecraft.displayGuiScreen((GuiScreen) guiscreen);
}
}
private GuiScreen getScriptBlockGui(int x, int y, int z) {
World world = Minecraft.getMinecraft().theWorld;
if (world == null)
return null;
TileEntity tile = world.getTileEntity(x, y, z);
if (!(tile instanceof TileScripted))
return null;
return GuiScriptInterface.create(null, (TileScripted) tile);
}
@Override
public void spawnParticle(EntityLivingBase player, String string, Object... ob) {
if (string.equals("Spell")) {
@@ -744,6 +815,13 @@ public class ClientProxy extends CommonProxy {
return Minecraft.getMinecraft().currentScreen != null;
}
public void buildPackageIndex() {
try {
PackageFinder.init(Thread.currentThread().getContextClassLoader());
} catch (IOException e) {
}
}
public static class FontContainer {
public StringCache textFont = null;
public boolean useCustomFont = true;
@@ -5,11 +5,13 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import kamkeel.npcs.client.renderer.lightning.LightningBolt;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.player.CheckPlayerValue;
import kamkeel.npcs.network.packets.player.InputDevicePacket;
import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket;
import kamkeel.npcs.network.packets.player.ScreenSizePacket;
import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
@@ -18,7 +20,6 @@ import net.minecraft.world.World;
import noppes.npcs.CustomNpcs;
import noppes.npcs.client.controllers.MusicController;
import noppes.npcs.client.controllers.ScriptSoundController;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphManager;
import noppes.npcs.client.gui.hud.ClientHudManager;
import noppes.npcs.client.gui.hud.CompassHudComponent;
import noppes.npcs.client.gui.hud.EnumHudComponent;
@@ -115,6 +116,9 @@ public class ClientTickHandler {
if (TelegraphManager.ClientInstance != null) {
TelegraphManager.ClientInstance.tick(mc.theWorld);
}
// Update lightning bolts for ability effects
LightningBolt.updateAll();
if (Minecraft.getMinecraft().thePlayer != null && (prevWidth != mc.displayWidth || prevHeight != mc.displayHeight)) {
prevWidth = mc.displayWidth;
prevHeight = mc.displayHeight;
@@ -11,7 +11,7 @@ import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
@@ -199,6 +199,7 @@ public class MusicController {
/**
* Stops a specific sound by its resource key.
* This is used to stop dialog sounds without affecting Bard music.
*
* @param soundKey The sound resource key to stop
*/
public void stopSound(String soundKey) {
@@ -4,25 +4,19 @@ import kamkeel.npcs.network.packets.request.script.NPCScriptPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.script.GuiNPCEventScripts;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.DataScript;
@@ -30,81 +24,162 @@ import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCallback, ICustomScrollListener, IJTextAreaListener, ITextChangeListener {
/**
* NPC Script GUI - extends GuiScriptInterface but with unique behavior:
* - Uses scroll-based tab selection instead of top buttons
* - Shows settings/script toggle
* - Uses DataScript with getNPCScript(index) access pattern
* - Has console filtering by hook type
*/
public class GuiScript extends GuiScriptInterface {
public boolean showScript = false;
private int activeTab = 0;
public DataScript script;
public Map<String, List<String>> languages = new HashMap<String, List<String>>();
private static int activeConsole = 0;
boolean loaded = false;
public GuiScript(EntityNPCInterface npc) {
super(npc);
script = npc.script;
drawDefaultBackground = true;
closeOnEsc = true;
xSize = 420;
super();
this.npc = npc;
this.script = npc.script;
this.handler = script;
this.useScrollTabs = true;
this.useSettingsToggle = true;
// Initialize hook list for NPC scripts
hookList.add("script.init");
hookList.add("script.update");
hookList.add("script.interact");
hookList.add("dialog.dialog");
hookList.add("script.damaged");
hookList.add("script.killed");
hookList.add("script.attack");
hookList.add("script.target");
hookList.add("script.collide");
hookList.add("script.kills");
hookList.add("script.dialog_closed");
hookList.add("script.timer");
hookList.add("script.targetLost");
hookList.add("script.projectileTick");
hookList.add("script.projectileImpact");
setBackground("menubg.png");
NPCScriptPacket.Get();
}
@Override
protected ScriptContext getScriptContext() {
return ScriptContext.NPC;
}
@Override
protected int getActiveScriptIndex() {
return this.activeTab;
}
@Override
protected ScriptContainer getCurrentContainer() {
return script.getNPCScript(activeTab);
}
@Override
public void initGui() {
super.initGui();
guiTop += 10;
GuiMenuTopButton top;
addTopButton(top = new GuiMenuTopButton(13, guiLeft + 4, guiTop - 17, "script.scripts"));
addTopButton(new GuiMenuTopButton(16, guiLeft + (xSize - 102), guiTop - 17, "eventscript.eventScripts"));
addTopButton(new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"));
top.active = showScript;
addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings"));
top.active = !showScript;
addTopButton(new GuiMenuTopButton(15, top, "gui.website"));
this.guiTop += 10;
List<String> list = new ArrayList<String>();
list.add("script.init");
list.add("script.update");
list.add("script.interact");
list.add("dialog.dialog");
list.add("script.damaged");
list.add("script.killed");
list.add("script.attack");
list.add("script.target");
list.add("script.collide");
list.add("script.kills");
list.add("script.dialog_closed");
list.add("script.timer");
list.add("script.targetLost");
list.add("script.projectileTick");
list.add("script.projectileImpact");
// ==================== TOP BUTTONS (hidden in fullscreen) ====================
if (!isFullscreen) {
GuiMenuTopButton top;
addTopButton(top = new GuiMenuTopButton(13, guiLeft + 4, guiTop - 17, "script.scripts"));
addTopButton(new GuiMenuTopButton(16, guiLeft + (xSize - 102), guiTop - 17, "eventscript.eventScripts"));
addTopButton(new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"));
top.active = showScript;
addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings"));
top.active = !showScript;
addTopButton(new GuiMenuTopButton(15, top, "gui.website"));
}
if (showScript) {
initScriptView();
} else {
initSettingsView();
}
}
private void initScriptView() {
ScriptContainer container = getCurrentContainer();
// ==================== CALCULATE VIEWPORT BOUNDS ====================
int editorX, editorY, editorWidth, editorHeight;
if (isFullscreen) {
// Fullscreen: viewport fills screen with configured padding
FullscreenConfig.paddingTop = 30;
FullscreenConfig.paddingBottom = 20;
FullscreenConfig.paddingLeft = 20;
FullscreenConfig.paddingRight = 20;
editorX = FullscreenConfig.paddingLeft;
editorY = FullscreenConfig.paddingTop;
editorWidth = this.width - FullscreenConfig.paddingLeft - FullscreenConfig.paddingRight;
editorHeight = this.height - FullscreenConfig.paddingTop - FullscreenConfig.paddingBottom;
} else {
// Normal: fixed layout with hooks on left
editorX = guiLeft + 74;
editorY = guiTop + 4;
editorWidth = 239;
editorHeight = 208;
}
// ==================== HOOKS SCROLL (hidden in fullscreen) ====================
if (!isFullscreen) {
addLabel(new GuiNpcLabel(0, "script.hooks", guiLeft + 4, guiTop + 5));
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.setSize(68, 198);
hooks.guiLeft = guiLeft + 4;
hooks.guiTop = guiTop + 14;
hooks.setUnsortedList(list);
hooks.setUnsortedList(hookList);
hooks.selected = activeTab;
addScroll(hooks);
}
ScriptContainer container = script.getNPCScript(activeTab);
// ==================== SCRIPT TEXT AREA ====================
int idx = getActiveScriptIndex();
GuiScriptTextArea activeArea = getActiveScriptArea();
if (activeArea == null) {
activeArea = new GuiScriptTextArea(this, 2, editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.script);
activeArea.setListener(this);
this.closeOnEsc(activeArea::closeOnEsc);
textAreas.put(idx, activeArea);
} else {
activeArea.init(editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.script);
}
GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, guiLeft + 74, guiTop + 4, 239, 208, container == null ? "" : container.script);
ta.enableCodeHighlighting();
ta.setListener(this);
this.addTextField(ta);
activeArea.setLanguage(script.getLanguage());
activeArea.setScriptContext(getScriptContext());
// Setup fullscreen key binding
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
if (e.isPress()) {
toggleFullscreen();
}
});
activeArea.enableCodeHighlighting();
addTextField(activeArea);
// Initialize fullscreen button
int scrollbarOffset = activeArea.hasVerticalScrollbar() ? -8 : -2;
fullscreenButton.initGui(editorX + editorWidth, editorY, scrollbarOffset);
// ==================== RIGHT PANEL (hidden in fullscreen) ====================
if (!isFullscreen) {
addButton(new GuiNpcButton(102, guiLeft + 315, guiTop + 4, 50, 20, "gui.clear"));
addButton(new GuiNpcButton(101, guiLeft + 366, guiTop + 4, 50, 20, "gui.paste"));
addButton(new GuiNpcButton(100, guiLeft + 315, guiTop + 25, 50, 20, "gui.copy"));
addButton(new GuiNpcButton(107, guiLeft + 315, guiTop + 70, 80, 20, "script.loadscript"));
GuiCustomScroll scroll = new GuiCustomScroll(this, 0).setUnselectable();
@@ -114,55 +189,52 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
if (container != null)
scroll.setList(container.scripts);
addScroll(scroll);
} else {
addLabel(new GuiNpcLabel(0, "script.console", guiLeft + 4, guiTop + 16));
}
}
private void initSettingsView() {
addLabel(new GuiNpcLabel(0, "script.console", guiLeft + 4, guiTop + 16));
if (getTopButton(14) != null)
getTopButton(14).active = true;
addTextField(new GuiNpcTextArea(2, this, guiLeft + 4, guiTop + 26, 226, 186, getConsoleText()));
getTextField(2).canEdit = false;
addButton(new GuiNpcButton(100, guiLeft + 232, guiTop + 170, 56, 20, "gui.copy"));
addButton(new GuiNpcButton(102, guiLeft + 232, guiTop + 192, 56, 20, "gui.clear"));
List<String> l = new ArrayList<String>();
l.add("All");
l.addAll(list);
addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20, l.toArray(new String[l.size()]), activeConsole));
GuiNpcTextArea consoleArea = new GuiNpcTextArea(2, this, guiLeft + 4, guiTop + 26, 226, 186, getConsoleText());
consoleArea.canEdit = false;
addTextField(consoleArea);
addLabel(new GuiNpcLabel(1, "script.language", guiLeft + 232, guiTop + 30));
addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20, languages.keySet().toArray(new String[languages.keySet().size()]), getScriptIndex()));
getButton(103).enabled = languages.size() > 0;
addButton(new GuiNpcButton(100, guiLeft + 232, guiTop + 170, 56, 20, "gui.copy"));
addButton(new GuiNpcButton(102, guiLeft + 232, guiTop + 192, 56, 20, "gui.clear"));
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));
List<String> consoleOptions = new ArrayList<>();
consoleOptions.add("All");
consoleOptions.addAll(hookList);
addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20,
consoleOptions.toArray(new String[0]), activeConsole));
if (MinecraftServer.getServer() != null)
addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder"));
}
addLabel(new GuiNpcLabel(1, "script.language", 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));
if (MinecraftServer.getServer() != null)
addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder"));
}
private int getScriptIndex() {
int i = 0;
for (String language : languages.keySet()) {
if (language.equalsIgnoreCase(script.scriptLanguage))
return i;
i++;
}
return 0;
}
private String getConsoleText() {
@Override
protected String getConsoleText() {
Map<Long, String> map = this.script.getOldConsoleText();
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet().iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n");
for (Map.Entry<Long, String> entry : map.entrySet()) {
builder.insert(0, new Date(entry.getKey()) + entry.getValue() + "\n");
}
return builder.toString();
}
@Override
public void confirmClicked(boolean result, int id) {
NoppesUtil.openGUI(player, this);
@@ -187,8 +259,6 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
}
}
}
displayGuiScreen(this);
}
@@ -204,12 +274,11 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
initGui();
}
if (guibutton.id == 15) {
GuiConfirmOpenLink guiyesno = new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true);
mc.displayGuiScreen(guiyesno);
displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
}
if (guibutton.id == 16) {
close();
mc.displayGuiScreen(new GuiNPCEventScripts(npc));
GuiScriptInterface.open(this, this.script);
}
if (guibutton.id == 17) {
close();
@@ -218,12 +287,12 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
NoppesStringUtils.setClipboardContents(getTextField(2).getText());
}
if (guibutton.id == 101) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
displayGuiScreen(guiyesno);
displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"),
StatCollector.translateToLocal("gui.sure"), 101));
}
if (guibutton.id == 102) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
displayGuiScreen(guiyesno);
displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"),
StatCollector.translateToLocal("gui.sure"), 102));
}
if (guibutton.id == 103) {
script.scriptLanguage = ((GuiNpcButton) guibutton).displayString;
@@ -236,21 +305,20 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
initGui();
}
if (guibutton.id == 106) {
// TODO: Uses ScriptController.Instance.dir (shared script repository); this GUI is gated behind the scripter tool
// and CustomNpcsPermissions.TOOL_SCRIPTER so only authorized editors touch the controller-backed scripts.
NoppesUtil.openFolder(ScriptController.Instance.dir);
}
if (guibutton.id == 107) {
ScriptContainer container = script.getNPCScript(activeTab);
ScriptContainer container = getCurrentContainer();
if (container == null)
script.setNPCScript(activeTab, container = new ScriptContainer(this.script));
setSubGui(new GuiScriptList(languages.get(script.scriptLanguage), container));
}
}
private void setScript() {
@Override
protected void setScript() {
if (showScript) {
ScriptContainer container = script.getNPCScript(activeTab);
ScriptContainer container = getCurrentContainer();
if (container == null)
script.setNPCScript(activeTab, container = new ScriptContainer(this.script));
String text = getTextField(2).getText();
@@ -263,19 +331,7 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
@Override
public void setGuiData(NBTTagCompound compound) {
script.readFromNBT(compound);
NBTTagList data = compound.getTagList("Languages", 10);
Map<String, List<String>> languages = new HashMap<String, List<String>>();
for (int i = 0; i < data.tagCount(); i++) {
NBTTagCompound comp = data.getCompoundTagAt(i);
List<String> scripts = new ArrayList<String>();
NBTTagList list = comp.getTagList("Scripts", 8);
for (int j = 0; j < list.tagCount(); j++) {
scripts.add(list.getStringTagAt(j));
}
languages.put(comp.getString("Language"), scripts);
}
this.languages = languages;
initGui();
loadLanguagesData(compound);
loaded = true;
}
@@ -296,19 +352,23 @@ public class GuiScript extends GuiNPCInterface implements IGuiData, GuiYesNoCall
}
}
public void textUpdate(String text) {
ScriptContainer container = script.getNPCScript(activeTab);
if (container != null)
container.script = text;
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
// Draw fullscreen button when in script view (GuiScript uses 0-based activeTab)
if (showScript) {
fullscreenButton.draw(mouseX, mouseY);
}
}
@Override
public void saveText(String text) {
ScriptContainer container = script.getNPCScript(activeTab);
if (container != null)
container.script = text;
initGui();
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
// Check fullscreen button first when in script view
if (showScript && fullscreenButton.mouseClicked(mouseX, mouseY, mouseButton)) {
return;
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
}
@@ -6,6 +6,7 @@ import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.data.IScriptUnit;
import java.util.ArrayList;
import java.util.List;
@@ -13,16 +14,20 @@ import java.util.List;
public class GuiScriptList extends SubGuiInterface {
private GuiCustomScroll scroll1;
private GuiCustomScroll scroll2;
private ScriptContainer container;
private IScriptUnit scriptUnit;
private List<String> scripts;
public GuiScriptList(List<String> scripts, ScriptContainer container) {
this.container = container;
this(scripts, (IScriptUnit) container);
}
public GuiScriptList(List<String> scripts, IScriptUnit scriptUnit) {
this.scriptUnit = scriptUnit;
setBackground("menubg.png");
xSize = 346;
ySize = 216;
if (scripts == null)
scripts = new ArrayList<String>();
scripts = new ArrayList<>();
this.scripts = scripts;
}
@@ -46,10 +51,10 @@ public class GuiScriptList extends SubGuiInterface {
scroll2.guiTop = guiTop + 14;
this.addScroll(scroll2);
addLabel(new GuiNpcLabel(2, "script.loadedScripts", guiLeft + 200, guiTop + 4));
List<String> temp = new ArrayList<String>(scripts);
temp.removeAll(container.scripts);
List<String> temp = new ArrayList<>(scripts);
temp.removeAll(scriptUnit.getExternalScripts());
scroll1.setList(temp);
scroll2.setList(container.scripts);
scroll2.setList(scriptUnit.getExternalScripts());
addButton(new GuiNpcButton(1, guiLeft + 145, guiTop + 40, 55, 20, ">"));
addButton(new GuiNpcButton(2, guiLeft + 145, guiTop + 62, 55, 20, "<"));
@@ -64,7 +69,7 @@ public class GuiScriptList extends SubGuiInterface {
GuiNpcButton button = (GuiNpcButton) guibutton;
if (button.id == 1) {
if (scroll1.hasSelected()) {
container.scripts.add(scroll1.getSelected());
scriptUnit.getExternalScripts().add(scroll1.getSelected());
scroll1.selected = -1;
scroll2.selected = -1;
initGui();
@@ -72,22 +77,22 @@ public class GuiScriptList extends SubGuiInterface {
}
if (button.id == 2) {
if (scroll2.hasSelected()) {
container.scripts.remove(scroll2.getSelected());
scriptUnit.getExternalScripts().remove(scroll2.getSelected());
scroll2.selected = -1;
initGui();
}
}
if (button.id == 3) {
container.scripts.clear();
scriptUnit.getExternalScripts().clear();
for (String script : scripts) {
container.scripts.add(script);
scriptUnit.getExternalScripts().add(script);
}
scroll1.selected = -1;
scroll2.selected = -1;
initGui();
}
if (button.id == 4) {
container.scripts.clear();
scriptUnit.getExternalScripts().clear();
scroll1.selected = -1;
scroll2.selected = -1;
initGui();
@@ -25,10 +25,10 @@ public class SubGuiColorSelector extends SubGuiInterface implements ITextfieldLi
public int color;
public SubGuiColorSelector(int color) {
xSize = 176;
xSize = 182;
ySize = 222;
this.color = color;
setBackground("smallbg.png");
setBackground("menubg.png");
}
@Override
@@ -40,7 +40,7 @@ public class SubGuiColorSelector extends SubGuiInterface implements ITextfieldLi
this.addTextField(textfield = new GuiNpcTextField(0, this, guiLeft + 53, guiTop + 20, 70, 20, getColor()));
textfield.setTextColor(color);
addButton(new GuiNpcButton(66, guiLeft + 112, guiTop + 198, 60, 20, "gui.done"));
addButton(new GuiNpcButton(66, guiLeft + 112, guiTop + 175, 60, 20, "gui.done"));
}
public String getColor() {
@@ -7,7 +7,7 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import noppes.npcs.client.gui.script.GuiScriptEffect;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -17,6 +17,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.EffectScript;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
@@ -202,10 +203,7 @@ public class SubGuiEffectGeneral extends SubGuiInterface implements ITextfieldLi
}
if (id == -2) {
PacketClient.sendClient(new EffectSavePacket(effect.writeToNBT(false), originalName));
GuiScriptEffect scriptGUI = new GuiScriptEffect(parent, effect);
scriptGUI.setWorldAndResolution(mc, width, height);
scriptGUI.initGui();
mc.currentScreen = scriptGUI;
GuiScriptInterface.open(parent, new EffectScript(effect.id));
}
if (id == 10) {
GuiNpcButtonYesNo button = (GuiNpcButtonYesNo) guibutton;
@@ -98,7 +98,7 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
getTextField(18).setVisible(dialog.renderGradual);
getLabel(18).enabled = dialog.renderGradual;
addTextField(new GuiNpcTextField(19, this, guiLeft + 125, y += 22, 40, 20, String.valueOf(dialog.textPitch)));
addTextField(new GuiNpcTextField(19, this, guiLeft + 125, y += 22, 40, 20, "" + dialog.textPitch));
addLabel(new GuiNpcLabel(19, "dialog.textPitch", guiLeft + 4, y + 5));
getTextField(19).floatsOnly = true;
getTextField(19).setVisible(dialog.renderGradual);
@@ -110,48 +110,48 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
addButton(new GuiNpcButton(24, guiLeft + 192, y, 50, 20, new String[]{"display.bottom", "display.top"}, dialog.alignment));
addLabel(new GuiNpcLabel(27, "display.alignment", guiLeft + 126, y + 5));
addTextField(new GuiNpcTextField(11, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.textWidth)));
addTextField(new GuiNpcTextField(12, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.textHeight)));
addTextField(new GuiNpcTextField(11, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.textWidth));
addTextField(new GuiNpcTextField(12, this, guiLeft + 165, y, 40, 20, "" + dialog.textHeight));
addLabel(new GuiNpcLabel(12, "gui.widthHeight", guiLeft + 4, y + 5));
getTextField(11).integersOnly = true;
getTextField(11).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(12).integersOnly = true;
getTextField(12).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
addTextField(new GuiNpcTextField(13, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.textOffsetX)));
addTextField(new GuiNpcTextField(14, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.textOffsetY)));
addTextField(new GuiNpcTextField(13, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.textOffsetX));
addTextField(new GuiNpcTextField(14, this, guiLeft + 165, y, 40, 20, "" + dialog.textOffsetY));
addLabel(new GuiNpcLabel(15, "dialog.textOffset", guiLeft + 4, y + 5));
getTextField(13).integersOnly = true;
getTextField(13).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(14).integersOnly = true;
getTextField(14).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.titleOffsetX)));
addTextField(new GuiNpcTextField(16, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.titleOffsetY)));
addTextField(new GuiNpcTextField(15, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.titleOffsetX));
addTextField(new GuiNpcTextField(16, this, guiLeft + 165, y, 40, 20, "" + dialog.titleOffsetY));
addLabel(new GuiNpcLabel(18, "dialog.titleOffset", guiLeft + 4, y + 5));
getTextField(15).integersOnly = true;
getTextField(15).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(16).integersOnly = true;
getTextField(16).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
addTextField(new GuiNpcTextField(17, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.optionOffsetX)));
addTextField(new GuiNpcTextField(18, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.optionOffsetY)));
addTextField(new GuiNpcTextField(17, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.optionOffsetX));
addTextField(new GuiNpcTextField(18, this, guiLeft + 165, y, 40, 20, "" + dialog.optionOffsetY));
addLabel(new GuiNpcLabel(21, "dialog.optionOffset", guiLeft + 4, y + 5));
getTextField(17).integersOnly = true;
getTextField(17).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(18).integersOnly = true;
getTextField(18).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
addTextField(new GuiNpcTextField(19, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.optionSpaceX)));
addTextField(new GuiNpcTextField(20, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.optionSpaceY)));
addTextField(new GuiNpcTextField(19, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.optionSpaceX));
addTextField(new GuiNpcTextField(20, this, guiLeft + 165, y, 40, 20, "" + dialog.optionSpaceY));
addLabel(new GuiNpcLabel(24, "dialog.optionSpacing", guiLeft + 4, y + 5));
getTextField(19).integersOnly = true;
getTextField(19).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(20).integersOnly = true;
getTextField(20).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
addTextField(new GuiNpcTextField(21, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.npcOffsetX)));
addTextField(new GuiNpcTextField(22, this, guiLeft + 165, y, 40, 20, String.valueOf(dialog.npcOffsetY)));
addTextField(new GuiNpcTextField(21, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.npcOffsetX));
addTextField(new GuiNpcTextField(22, this, guiLeft + 165, y, 40, 20, "" + dialog.npcOffsetY));
addLabel(new GuiNpcLabel(25, "dialog.npcOffset", guiLeft + 4, y + 5));
getTextField(21).integersOnly = true;
getTextField(21).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
@@ -161,7 +161,7 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
getTextField(22).setVisible(!dialog.hideNPC);
getLabel(25).enabled = !dialog.hideNPC;
addTextField(new GuiNpcTextField(23, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialog.npcScale)));
addTextField(new GuiNpcTextField(23, this, guiLeft + 120, y += 25, 40, 20, "" + dialog.npcScale));
addLabel(new GuiNpcLabel(26, "dialog.npcScale", guiLeft + 4, y + 5));
getTextField(23).floatsOnly = true;
getTextField(23).setMinMaxDefaultFloat(-Float.MAX_VALUE, Float.MAX_VALUE, 0);
@@ -182,30 +182,30 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
DialogImage dialogImage = getSelectedImage();
addButton(new GuiNpcButton(2, guiLeft + xSize + 24, guiTop + 5, 20, 20, "-"));
addTextField(new GuiNpcTextField(10, this, guiLeft + 17, y += 25, 30, 20, String.valueOf(dialogImage.id)));
addTextField(new GuiNpcTextField(10, this, guiLeft + 17, y += 25, 30, 20, "" + dialogImage.id));
addTextField(new GuiNpcTextField(11, this, guiLeft + 92, y, 150, 20, dialogImage.texture));
addLabel(new GuiNpcLabel(10, "gui.id", guiLeft + 4, y + 5));
addLabel(new GuiNpcLabel(11, "display.texture", guiLeft + 50, y + 5));
getTextField(10).integersOnly = true;
addTextField(new GuiNpcTextField(12, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialogImage.x)));
addTextField(new GuiNpcTextField(13, this, guiLeft + 165, y, 40, 20, String.valueOf(dialogImage.y)));
addTextField(new GuiNpcTextField(12, this, guiLeft + 120, y += 25, 40, 20, "" + dialogImage.x));
addTextField(new GuiNpcTextField(13, this, guiLeft + 165, y, 40, 20, "" + dialogImage.y));
addLabel(new GuiNpcLabel(12, "gui.position", guiLeft + 4, y + 5));
getTextField(12).integersOnly = true;
getTextField(12).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
getTextField(13).integersOnly = true;
getTextField(13).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialogImage.width)));
addTextField(new GuiNpcTextField(15, this, guiLeft + 165, y, 40, 20, String.valueOf(dialogImage.height)));
addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 25, 40, 20, "" + dialogImage.width));
addTextField(new GuiNpcTextField(15, this, guiLeft + 165, y, 40, 20, "" + dialogImage.height));
addLabel(new GuiNpcLabel(13, "gui.widthHeight", 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);
addTextField(new GuiNpcTextField(16, this, guiLeft + 120, y += 25, 40, 20, String.valueOf(dialogImage.textureX)));
addTextField(new GuiNpcTextField(17, this, guiLeft + 165, y, 40, 20, String.valueOf(dialogImage.textureY)));
addTextField(new GuiNpcTextField(16, this, guiLeft + 120, y += 25, 40, 20, "" + dialogImage.textureX));
addTextField(new GuiNpcTextField(17, this, guiLeft + 165, y, 40, 20, "" + dialogImage.textureY));
addLabel(new GuiNpcLabel(14, "dialog.textureOffset", guiLeft + 4, y + 5));
getTextField(16).integersOnly = true;
getTextField(16).setMinMaxDefault(-Integer.MAX_VALUE, Integer.MAX_VALUE, 0);
@@ -229,9 +229,9 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
getButton(19).setVisible(dialogImage.imageType == 2);
getLabel(16).enabled = dialogImage.imageType == 2;
addTextField(new GuiNpcTextField(20, this, guiLeft + 33, y += 25, 30, 20, String.valueOf(dialogImage.scale)));
addTextField(new GuiNpcTextField(21, this, guiLeft + 102, y, 30, 20, String.valueOf(dialogImage.alpha)));
addTextField(new GuiNpcTextField(22, this, guiLeft + 183, y, 45, 20, String.valueOf(dialogImage.rotation)));
addTextField(new GuiNpcTextField(20, this, guiLeft + 33, y += 25, 30, 20, "" + dialogImage.scale));
addTextField(new GuiNpcTextField(21, this, guiLeft + 102, y, 30, 20, "" + dialogImage.alpha));
addTextField(new GuiNpcTextField(22, this, guiLeft + 183, y, 45, 20, "" + dialogImage.rotation));
addLabel(new GuiNpcLabel(17, "model.scale", guiLeft + 4, y + 5));
addLabel(new GuiNpcLabel(18, "display.alpha", guiLeft + 72, y + 5));
addLabel(new GuiNpcLabel(19, "movement.rotation", guiLeft + 140, y + 5));
@@ -306,13 +306,13 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
Collections.sort(ids);
ArrayList<String> strings = new ArrayList<>();
for (int i : ids) {
strings.add(String.valueOf(i));
strings.add("" + i);
}
imageScroll.setUnsortedList(strings);
if (changedId != -1) {
selected = imageScroll.getList().indexOf(String.valueOf(changedId));
imageScroll.setSelected(String.valueOf(changedId));
selected = imageScroll.getList().indexOf("" + changedId);
imageScroll.setSelected("" + changedId);
changedId = -1;
}
@@ -402,7 +402,7 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
dialog.dialogImages.put(addId, new DialogImage(addId));
updateScrollData();
selected = imageScroll.getList().indexOf(String.valueOf(addId));
selected = imageScroll.getList().indexOf("" + addId);
}
if (button.id == 2) {
if (imageScroll.getSelected() != null) {
@@ -598,8 +598,8 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis
}
if (textfield.id == 10) {
if (imageScroll.getList().contains(String.valueOf(textfield.getInteger()))) {
textfield.setText(String.valueOf(dialogImage.id));
if (imageScroll.getList().contains("" + textfield.getInteger())) {
textfield.setText("" + dialogImage.id);
return;
}
@@ -71,7 +71,7 @@ public class SubGuiNpcPartyOptions extends SubGuiInterface implements ITextfield
y += 23;
//min party size - number field
GuiNpcTextField minField = new GuiNpcTextField(21, this, guiLeft + 60, guiTop + 10 + y,
30, 20, String.valueOf(options.minPartySize));
30, 20, "" + options.minPartySize);
minField.integersOnly = true;
minField.setMinMaxDefault(1, Integer.MAX_VALUE, 1);
addTextField(minField);
@@ -79,7 +79,7 @@ public class SubGuiNpcPartyOptions extends SubGuiInterface implements ITextfield
//max party size - number field
GuiNpcTextField maxField = new GuiNpcTextField(20, this, guiLeft + 160, guiTop + 10 + y,
30, 20, String.valueOf(options.maxPartySize));
30, 20, "" + options.maxPartySize);
maxField.integersOnly = true;
maxField.setMinMaxDefault(1, Integer.MAX_VALUE, 4);
addTextField(maxField);
@@ -36,7 +36,7 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Fields
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
// Current tab (10=Quest, 11=Dialog, 12=Transport, 13=Bank, 14=Faction, 15=Magic)
private int currentTab = 10;
@@ -99,7 +99,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
public SubGuiPlayerData(String playerName) {
this.playerName = playerName;
xSize = 420;
@@ -112,7 +113,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Layout Helpers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
private int getPaddedLeft() {
return guiLeft + leftPadding;
}
@@ -135,7 +137,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Component Setup Helpers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
private void setupTopButtons() {
// Show General Display Information
GuiMenuTopButton playerTab = new GuiMenuTopButton(-10, guiLeft + 4, guiTop - 10, playerName);
@@ -192,7 +195,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// initGui() & Tab Initialization
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void initGui() {
super.initGui();
@@ -489,7 +493,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Drawing Helpers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
@@ -525,7 +530,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Mouse & Resizing Handlers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
int hitMargin = 3;
@@ -672,7 +678,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Key & Search Field Handling
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
@@ -894,7 +901,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Action Handling
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void actionPerformed(GuiButton button) {
if (button.id == -5) {
@@ -1043,7 +1051,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Data Setting Methods (IPlayerDataInfo)
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void setQuestData(Map<String, Integer> questCategories, Map<String, Integer> questActive, Map<String, Integer> questFinished) {
this.questCatData = new HashMap<>(questCategories);
@@ -36,9 +36,9 @@ public class SubGuiSpawningOptions extends SubGuiInterface implements ITextfield
addButton(new GuiNpcButtonYesNo(13, guiLeft + 120, y += 22, data.airSpawning));
addLabel(new GuiNpcLabel(13, "spawning.airSpawning", guiLeft + 4, y + 5));
addTextField(new GuiNpcTextField(14, this, guiLeft + 120, y += 22, 40, 20, String.valueOf(data.spawnHeightMin)));
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, String.valueOf(data.spawnHeightMax)));
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);
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.AbilitySlot;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket;
import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket;
@@ -10,7 +11,18 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNPCInterface2;
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.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IScrollData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.entity.EntityNPCInterface;
@@ -35,12 +47,13 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Display name to typeId mapping for the available types scroll
private final HashMap<String, String> displayNameToTypeId = new HashMap<>();
// NPC's current abilities
private final List<Ability> npcAbilities = new ArrayList<>();
// NPC's current ability slots
private final List<AbilitySlot> npcSlots = new ArrayList<>();
// Settings
private boolean abilitiesEnabled = false;
private int globalCooldown = 20;
private int minCooldown = 20;
private int maxCooldown = 60;
private String search = "";
private int selectedAbilityIndex = -1;
@@ -61,12 +74,18 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
addLabel(new GuiNpcLabel(100, "gui.enabled", guiLeft + 5, y + 5));
addButton(new GuiNpcButton(100, guiLeft + 55, y, 50, 20, new String[]{"gui.no", "gui.yes"}, abilitiesEnabled ? 1 : 0));
// Global cooldown (spaced out since combat only is removed)
addLabel(new GuiNpcLabel(101, "ability.globalCooldown", guiLeft + 140, y + 5));
GuiNpcTextField cooldownField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 230, y, 50, 20, String.valueOf(globalCooldown));
cooldownField.setIntegersOnly();
cooldownField.setMinMaxDefault(0, 10000, 20);
addTextField(cooldownField);
// Cooldown range: Min Cooldown and Max Cooldown (spaced apart more)
addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 115, y + 5));
GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 165, y, 40, 20, "" + minCooldown);
minField.setIntegersOnly();
minField.setMinMaxDefault(0, 10000, 20);
addTextField(minField);
addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 260, y + 5));
GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 310, y, 40, 20, "" + maxCooldown);
maxField.setIntegersOnly();
maxField.setMinMaxDefault(0, 10000, 60);
addTextField(maxField);
y += 28;
@@ -105,6 +124,14 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Load button (under the add/remove arrows)
addButton(new GuiNpcButton(75, centerX, y + 90, 40, 20, "gui.load"));
// On/Off toggle for selected ability (under Load button)
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
Ability selectedAbility = npcSlots.get(selectedAbilityIndex).getAbility();
GuiNpcButton toggleBtn = new GuiNpcButton(77, centerX, y + 112, 40, 20,
new String[]{"gui.off", "gui.on"}, selectedAbility.isEnabled() ? 1 : 0);
addButton(toggleBtn);
}
// Right side buttons: Edit and Up/Down carrots with Save button
addButton(new GuiNpcButton(72, guiLeft + 210, y + 145, 55, 20, "gui.edit"));
getButton(72).setEnabled(selectedAbilityIndex >= 0);
@@ -113,7 +140,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
addButton(new GuiNpcButton(73, guiLeft + 270, y + 145, 20, 20, "<"));
addButton(new GuiNpcButton(74, guiLeft + 292, y + 145, 20, 20, ">"));
getButton(73).setEnabled(selectedAbilityIndex > 0);
getButton(74).setEnabled(selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size() - 1);
getButton(74).setEnabled(selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1);
// Save button (to the right of carrots, only enabled when ability is selected)
addButton(new GuiNpcButton(76, guiLeft + 320, y + 145, 50, 20, "gui.save"));
@@ -140,10 +167,8 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
Ability newAbility = AbilityController.Instance.create(typeId);
if (newAbility != null) {
newAbility.setId(UUID.randomUUID().toString());
// Don't set custom name - let it default to type name
npcAbilities.add(newAbility);
// Auto-select the newly added ability
selectedAbilityIndex = npcAbilities.size() - 1;
npcSlots.add(AbilitySlot.inline(newAbility));
selectedAbilityIndex = npcSlots.size() - 1;
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
initGui();
@@ -156,8 +181,8 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Remove ability
if (id == 71) {
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size()) {
npcAbilities.remove(selectedAbilityIndex);
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
npcSlots.remove(selectedAbilityIndex);
selectedAbilityIndex = -1;
updateNpcAbilitiesList();
initGui();
@@ -168,9 +193,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Edit ability
if (id == 72) {
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size()) {
Ability ability = npcAbilities.get(selectedAbilityIndex);
setSubGui(ability.createConfigGui(this));
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
AbilitySlot slot = npcSlots.get(selectedAbilityIndex);
if (slot.isReference()) {
// Reference slot - ask clone-and-modify vs modify-parent
setSubGui(new SubGuiAbilityEditMode());
} else {
Ability ability = slot.getAbility();
if (ability != null) {
setSubGui(ability.createConfigGui(this));
}
}
}
return;
}
@@ -178,9 +211,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Move up (carrot left = earlier in list)
if (id == 73) {
if (selectedAbilityIndex > 0) {
Ability temp = npcAbilities.get(selectedAbilityIndex);
npcAbilities.set(selectedAbilityIndex, npcAbilities.get(selectedAbilityIndex - 1));
npcAbilities.set(selectedAbilityIndex - 1, temp);
AbilitySlot temp = npcSlots.get(selectedAbilityIndex);
npcSlots.set(selectedAbilityIndex, npcSlots.get(selectedAbilityIndex - 1));
npcSlots.set(selectedAbilityIndex - 1, temp);
selectedAbilityIndex--;
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
@@ -192,10 +225,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
// Move down (carrot right = later in list)
if (id == 74) {
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size() - 1) {
Ability temp = npcAbilities.get(selectedAbilityIndex);
npcAbilities.set(selectedAbilityIndex, npcAbilities.get(selectedAbilityIndex + 1));
npcAbilities.set(selectedAbilityIndex + 1, temp);
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1) {
AbilitySlot temp = npcSlots.get(selectedAbilityIndex);
npcSlots.set(selectedAbilityIndex, npcSlots.get(selectedAbilityIndex + 1));
npcSlots.set(selectedAbilityIndex + 1, temp);
selectedAbilityIndex++;
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
@@ -211,15 +244,31 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
return;
}
// Save selected ability
// Save selected ability as custom preset
if (id == 76) {
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size()) {
Ability abilityToSave = npcAbilities.get(selectedAbilityIndex);
if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) {
// Need a name to save - open edit dialog first
setSubGui(abilityToSave.createConfigGui(this));
} else {
setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave));
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
Ability abilityToSave = npcSlots.get(selectedAbilityIndex).getAbility();
if (abilityToSave != null) {
if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) {
setSubGui(abilityToSave.createConfigGui(this));
} else {
setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave));
}
}
}
return;
}
// Toggle selected ability on/off
if (id == 77) {
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
Ability ability = npcSlots.get(selectedAbilityIndex).getAbility();
if (ability != null) {
ability.setEnabled(((GuiNpcButton) guibutton).getValue() == 1);
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
initGui();
save();
}
}
return;
@@ -242,16 +291,29 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
@Override
public void setGuiData(NBTTagCompound compound) {
abilitiesEnabled = compound.getBoolean("AbilitiesEnabled");
globalCooldown = compound.hasKey("AbilityGlobalCooldown") ? compound.getInteger("AbilityGlobalCooldown") : 20;
// Only process NPC ability data, not saved ability preset data
// SubGuiAbilityLoad also implements IGuiData and may receive responses
// that get forwarded here - ignore those by checking for expected keys
if (!compound.hasKey("Abilities")) {
return;
}
npcAbilities.clear();
abilitiesEnabled = compound.getBoolean("AbilitiesEnabled");
minCooldown = compound.getInteger("AbilityMinCooldown");
maxCooldown = compound.getInteger("AbilityMaxCooldown");
if (minCooldown == 0 && maxCooldown == 0) {
minCooldown = 20;
maxCooldown = 60;
}
npcSlots.clear();
NBTTagList abilityList = compound.getTagList("Abilities", 10);
for (int i = 0; i < abilityList.tagCount(); i++) {
NBTTagCompound abilityNBT = abilityList.getCompoundTagAt(i);
Ability ability = AbilityController.Instance.fromNBT(abilityNBT);
if (ability != null) {
npcAbilities.add(ability);
AbilitySlot slot = AbilitySlot.fromNBT(abilityNBT);
if (slot != null) {
npcSlots.add(slot);
}
}
@@ -294,7 +356,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
private void updateNpcAbilitiesList() {
List<String> list = new ArrayList<>();
for (int i = 0; i < npcAbilities.size(); i++) {
for (int i = 0; i < npcSlots.size(); i++) {
list.add(getAbilityListEntry(i));
}
if (npcAbilitiesScroll != null) {
@@ -303,26 +365,41 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
}
/**
* Creates the display entry for an ability in the list.
* Format: "[●] 1. Custom Name (Type)" or "[●] 1. Type" if no custom name
* Circle is green (§a) for enabled, red (§c) for disabled
* Creates the display entry for an ability slot in the list.
* Inline: "[●] 1. Custom Name (Type)" or "[●] 1. Type"
* Reference: "[●] 1. > Name (Type)" in yellow
* Broken: "[●] 1. > [Missing: id...]" in red
*/
private String getAbilityListEntry(int index) {
Ability ability = npcAbilities.get(index);
AbilitySlot slot = npcSlots.get(index);
Ability ability = slot.getAbility();
if (ability == null) {
// Broken reference
String refId = slot.getReferenceId();
String shortId = refId != null && refId.length() > 8 ? refId.substring(0, 8) + "..." : refId;
return "\u00A7c\u25CF\u00A7r " + (index + 1) + ". \u00A7c> [Missing: " + shortId + "]\u00A7r";
}
String typeName = getDisplayName(ability.getTypeId());
String customName = ability.getName();
// Color prefix: green circle for enabled, red for disabled
String colorPrefix = ability.isEnabled() ? "\u00A7a\u25CF\u00A7r " : "\u00A7c\u25CF\u00A7r ";
String nameDisplay;
if (customName != null && !customName.isEmpty() && !customName.equals(typeName)) {
return colorPrefix + (index + 1) + ". " + customName + " (" + typeName + ")";
nameDisplay = customName + " (" + typeName + ")";
} else {
nameDisplay = typeName;
}
return colorPrefix + (index + 1) + ". " + typeName;
if (slot.isReference()) {
return colorPrefix + (index + 1) + ". \u00A7e> " + nameDisplay + "\u00A7r";
}
return colorPrefix + (index + 1) + ". " + nameDisplay;
}
private void selectAbilityByIndex(int index) {
if (index >= 0 && index < npcAbilities.size()) {
if (index >= 0 && index < npcSlots.size()) {
String entry = getAbilityListEntry(index);
if (npcAbilitiesScroll != null) {
npcAbilitiesScroll.setSelected(entry);
@@ -341,11 +418,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
public void save() {
NBTTagCompound compound = new NBTTagCompound();
compound.setBoolean("AbilitiesEnabled", abilitiesEnabled);
compound.setInteger("AbilityGlobalCooldown", globalCooldown);
compound.setInteger("AbilityMinCooldown", minCooldown);
compound.setInteger("AbilityMaxCooldown", maxCooldown);
NBTTagList abilityList = new NBTTagList();
for (Ability ability : npcAbilities) {
abilityList.appendTag(ability.writeNBT());
for (AbilitySlot slot : npcSlots) {
abilityList.appendTag(slot.writeNBT());
}
compound.setTag("Abilities", abilityList);
@@ -353,15 +431,29 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
}
/**
* Called from SubGuiAbilityLoad when a saved ability is loaded.
* Adds the ability to the NPC's ability list.
* Called from SubGuiAbilityLoad when a cloned ability is loaded.
* Adds as an inline slot.
*/
public void loadAbility(Ability loadedAbility) {
if (loadedAbility != null) {
loadedAbility.setId(UUID.randomUUID().toString());
npcAbilities.add(loadedAbility);
// Auto-select the newly added ability
selectedAbilityIndex = npcAbilities.size() - 1;
npcSlots.add(AbilitySlot.inline(loadedAbility));
selectedAbilityIndex = npcSlots.size() - 1;
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
initGui();
save();
}
}
/**
* Called from SubGuiAbilityLoad when a reference is loaded.
* Adds as a reference slot.
*/
public void loadAbilityReference(String referenceId) {
if (referenceId != null && !referenceId.isEmpty()) {
npcSlots.add(AbilitySlot.reference(referenceId));
selectedAbilityIndex = npcSlots.size() - 1;
updateNpcAbilitiesList();
selectAbilityByIndex(selectedAbilityIndex);
initGui();
@@ -401,24 +493,68 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll == npcAbilitiesScroll && selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size()) {
Ability ability = npcAbilities.get(selectedAbilityIndex);
setSubGui(ability.createConfigGui(this));
if (scroll == npcAbilitiesScroll && selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
AbilitySlot slot = npcSlots.get(selectedAbilityIndex);
if (slot.isReference()) {
setSubGui(new SubGuiAbilityEditMode());
} else {
Ability ability = slot.getAbility();
if (ability != null) {
setSubGui(ability.createConfigGui(this));
}
}
}
}
@Override
public void unFocused(GuiNpcTextField textField) {
if (textField.id == 101) {
globalCooldown = textField.getInteger();
minCooldown = textField.getInteger();
// Ensure min <= max
if (minCooldown > maxCooldown) {
maxCooldown = minCooldown;
initGui();
}
save();
} else if (textField.id == 102) {
maxCooldown = textField.getInteger();
// Ensure min <= max
if (maxCooldown < minCooldown) {
minCooldown = maxCooldown;
initGui();
}
save();
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiAbilityConfig) {
// Ability was saved in the SubGui, refresh list
if (subgui instanceof SubGuiAbilityEditMode) {
int mode = ((SubGuiAbilityEditMode) subgui).getResult();
if (mode < 0) return; // cancelled
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
AbilitySlot slot = npcSlots.get(selectedAbilityIndex);
if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) {
// Convert reference to inline, then edit
if (slot.convertToInline()) {
Ability ability = slot.getAbility();
if (ability != null) {
ability.setId(UUID.randomUUID().toString());
setSubGui(ability.createConfigGui(this));
}
updateNpcAbilitiesList();
save();
}
} else if (mode == SubGuiAbilityEditMode.MODE_MODIFY_PARENT) {
// Edit the resolved ability directly (changes propagate to controller)
Ability ability = slot.getAbility();
if (ability != null) {
setSubGui(ability.createConfigGui(this));
}
}
}
} else if (subgui instanceof SubGuiAbilityConfig) {
updateNpcAbilitiesList();
save();
}
@@ -428,8 +564,15 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
* Called from SubGuiAbilityConfig when ability is saved.
*/
public void onAbilitySaved(Ability ability) {
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcAbilities.size()) {
npcAbilities.set(selectedAbilityIndex, ability);
if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) {
AbilitySlot slot = npcSlots.get(selectedAbilityIndex);
if (slot.isReference()) {
// For reference slots, save back to controller
// (The resolved copy was edited in-place)
} else {
// For inline slots, replace with the updated ability
npcSlots.set(selectedAbilityIndex, AbilitySlot.inline(ability));
}
updateNpcAbilitiesList();
save();
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -8,15 +9,20 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Confirmation dialog for deleting an ability preset.
* Uses packet-based communication for proper client-server architecture.
*/
public class SubGuiAbilityDeleteConfirm extends SubGuiInterface {
private final String abilityName;
private final SubGuiAbilityLoad loadGui;
private final Runnable onDeleted;
public SubGuiAbilityDeleteConfirm(String abilityName, SubGuiAbilityLoad loadGui) {
public SubGuiAbilityDeleteConfirm(String abilityName) {
this(abilityName, null);
}
public SubGuiAbilityDeleteConfirm(String abilityName, Runnable onDeleted) {
this.abilityName = abilityName;
this.loadGui = loadGui;
this.onDeleted = onDeleted;
setBackground("menubg.png");
xSize = 200;
@@ -44,9 +50,11 @@ public class SubGuiAbilityDeleteConfirm extends SubGuiInterface {
int id = guibutton.id;
if (id == 0) {
// Delete the ability
AbilityController.Instance.deleteAbility(abilityName);
loadGui.onAbilityDeleted(abilityName);
// Delete the ability via packet
PacketClient.sendClient(new CustomAbilityRemovePacket(abilityName));
if (onDeleted != null) {
onDeleted.run();
}
close();
} else if (id == 1) {
close();
@@ -0,0 +1,56 @@
package noppes.npcs.client.gui.advanced;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Dialog asking the user whether to clone-and-modify (convert to inline) or modify the parent ability.
*/
public class SubGuiAbilityEditMode extends SubGuiInterface {
public static final int MODE_CLONE_MODIFY = 0;
public static final int MODE_MODIFY_PARENT = 1;
private int result = -1;
public SubGuiAbilityEditMode() {
setBackground("menubg.png");
xSize = 220;
ySize = 90;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 10;
addLabel(new GuiNpcLabel(0, "ability.edit.mode", guiLeft + 10, y));
y += 25;
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "ability.cloneModify"));
addButton(new GuiNpcButton(1, guiLeft + 115, y, 95, 20, "ability.modifyParent"));
y += 25;
addButton(new GuiNpcButton(2, guiLeft + 65, y, 90, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
result = MODE_CLONE_MODIFY;
close();
} else if (guibutton.id == 1) {
result = MODE_MODIFY_PARENT;
close();
} else if (guibutton.id == 2) {
result = -1;
close();
}
}
public int getResult() {
return result;
}
}
@@ -2,24 +2,45 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.*;
import net.minecraft.nbt.NBTTagCompound;
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.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IScrollData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
/**
* Dialog for loading a saved ability preset.
* Can be opened from SubGuiAbilityConfig (to load into editing ability)
* or from GuiNPCAbilities (to add ability directly to NPC).
* Shows custom abilities from the server, then asks Clone/Reference via SubGuiAbilityLoadMode.
*/
public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollListener {
public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollListener, IScrollData, IGuiData, ISubGuiListener {
private final SubGuiAbilityConfig parentConfig;
private final GuiNPCAbilities parentAbilities;
private String selectedName = null;
private List<String> abilityNames = new ArrayList<>();
private String selectedDisplayName = null;
private String selectedUuid = null;
/** Maps display name -> UUID for custom abilities. */
private final HashMap<String, String> displayToUuid = new HashMap<>();
private HashMap<String, Integer> rawData = new HashMap<>();
private GuiCustomScroll scroll;
private boolean waitingForLoad = false;
private int pendingLoadMode = -1;
public SubGuiAbilityLoad(SubGuiAbilityConfig parentConfig) {
this.parentConfig = parentConfig;
@@ -28,6 +49,8 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
setBackground("menubg.png");
xSize = 220;
ySize = 180;
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
public SubGuiAbilityLoad(GuiNPCAbilities parentAbilities) {
@@ -37,71 +60,90 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
setBackground("menubg.png");
xSize = 220;
ySize = 180;
PacketClient.sendClient(new CustomAbilitiesGetPacket());
}
@Override
public void initGui() {
super.initGui();
// Load ability names
Set<String> names = AbilityController.Instance.getSavedAbilityNames();
abilityNames = new ArrayList<>(names);
int y = guiTop + 5;
addLabel(new GuiNpcLabel(0, "ability.load.select", guiLeft + 10, y));
y += 14;
// Scroll list of saved abilities
GuiCustomScroll scroll = new GuiCustomScroll(this, 0);
scroll.setSize(200, 110);
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(200, 110);
}
scroll.guiLeft = guiLeft + 10;
scroll.guiTop = y;
scroll.setUnsortedList(abilityNames);
if (selectedName != null && abilityNames.contains(selectedName)) {
scroll.setSelected(selectedName);
scroll.setList(getFilteredList());
if (selectedDisplayName != null) {
scroll.setSelected(selectedDisplayName);
}
addScroll(scroll);
y += 115;
// Buttons
addButton(new GuiNpcButton(0, guiLeft + 10, y, 60, 20, "gui.load"));
addButton(new GuiNpcButton(1, guiLeft + 80, y, 60, 20, "gui.delete"));
addButton(new GuiNpcButton(2, guiLeft + 150, y, 60, 20, "gui.cancel"));
addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.load"));
addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel"));
// Disable load/delete if nothing selected
getButton(0).setEnabled(selectedName != null && !selectedName.isEmpty());
getButton(1).setEnabled(selectedName != null && !selectedName.isEmpty());
getButton(0).setEnabled(selectedUuid != null);
}
private List<String> getFilteredList() {
return new ArrayList<>(displayToUuid.keySet());
}
@Override
public void buttonEvent(GuiButton guibutton) {
int id = guibutton.id;
if (id == 0 && selectedName != null) {
// Load the selected ability
Ability loaded = AbilityController.Instance.getSavedAbility(selectedName);
if (loaded != null) {
if (parentConfig != null) {
parentConfig.loadAbility(loaded);
} else if (parentAbilities != null) {
parentAbilities.loadAbility(loaded);
}
if (id == 0 && selectedUuid != null) {
if (parentAbilities != null) {
// From NPC abilities GUI - ask clone/reference
setSubGui(new SubGuiAbilityLoadMode());
} else {
// From config GUI - always clone
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
}
close();
} else if (id == 1 && selectedName != null) {
// Delete confirmation
setSubGui(new SubGuiAbilityDeleteConfirm(selectedName, this));
} else if (id == 2) {
close();
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiAbilityLoadMode) {
int mode = ((SubGuiAbilityLoadMode) subgui).getResult();
if (mode < 0) return; // cancelled
if (mode == SubGuiAbilityLoadMode.MODE_REFERENCE) {
// Reference mode - just pass the reference ID
if (parentAbilities != null && selectedUuid != null) {
parentAbilities.loadAbilityReference(selectedUuid);
}
close();
} else {
// Clone mode - request full data
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
}
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0) {
selectedName = scroll.getSelected();
selectedDisplayName = scroll.getSelected();
if (selectedDisplayName != null) {
selectedUuid = displayToUuid.get(selectedDisplayName);
}
initGui();
}
}
@@ -109,9 +151,57 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll.id == 0 && selection != null && !selection.isEmpty()) {
// Double-click to load immediately
Ability loaded = AbilityController.Instance.getSavedAbility(selection);
selectedDisplayName = selection;
selectedUuid = displayToUuid.get(selectedDisplayName);
if (selectedUuid != null) {
if (parentAbilities != null) {
setSubGui(new SubGuiAbilityLoadMode());
} else {
waitingForLoad = true;
pendingLoadMode = SubGuiAbilityLoadMode.MODE_CLONE;
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
}
}
}
}
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
if (type == EnumScrollData.CUSTOM_ABILITIES) {
displayToUuid.clear();
rawData = data;
for (String key : data.keySet()) {
// key format: "displayName\tUUID"
int tabIndex = key.indexOf('\t');
if (tabIndex > 0) {
String displayName = key.substring(0, tabIndex);
String uuid = key.substring(tabIndex + 1);
displayToUuid.put(displayName, uuid);
} else {
displayToUuid.put(key, key);
}
}
if (scroll != null) {
scroll.setList(getFilteredList());
if (selectedDisplayName != null && displayToUuid.containsKey(selectedDisplayName)) {
scroll.setSelected(selectedDisplayName);
}
}
initGui();
}
}
@Override
public void setGuiData(NBTTagCompound compound) {
if (waitingForLoad) {
waitingForLoad = false;
Ability loaded = AbilityController.Instance.fromNBT(compound);
if (loaded != null) {
if (pendingLoadMode == SubGuiAbilityLoadMode.MODE_CLONE) {
// Give it a new UUID so it's a unique inline copy
loaded.setId(UUID.randomUUID().toString());
}
if (parentConfig != null) {
parentConfig.loadAbility(loaded);
} else if (parentAbilities != null) {
@@ -122,13 +212,11 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
}
}
/**
* Called after an ability is deleted to refresh the list.
*/
public void onAbilityDeleted(String name) {
if (name.equals(selectedName)) {
selectedName = null;
@Override
public void setSelected(String selected) {
this.selectedDisplayName = selected;
if (scroll != null) {
scroll.setSelected(selected);
}
initGui();
}
}
@@ -0,0 +1,56 @@
package noppes.npcs.client.gui.advanced;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Dialog asking the user whether to Clone (inline copy) or Reference the loaded ability.
*/
public class SubGuiAbilityLoadMode extends SubGuiInterface {
public static final int MODE_CLONE = 0;
public static final int MODE_REFERENCE = 1;
private int result = -1;
public SubGuiAbilityLoadMode() {
setBackground("menubg.png");
xSize = 200;
ySize = 90;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 10;
addLabel(new GuiNpcLabel(0, "ability.load.mode", guiLeft + 10, y));
y += 25;
addButton(new GuiNpcButton(0, guiLeft + 15, y, 80, 20, "ability.clone"));
addButton(new GuiNpcButton(1, guiLeft + 105, y, 80, 20, "ability.reference"));
y += 25;
addButton(new GuiNpcButton(2, guiLeft + 55, y, 90, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton guibutton) {
if (guibutton.id == 0) {
result = MODE_CLONE;
close();
} else if (guibutton.id == 1) {
result = MODE_REFERENCE;
close();
} else if (guibutton.id == 2) {
result = -1;
close();
}
}
public int getResult() {
return result;
}
}
@@ -1,23 +1,30 @@
package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Confirmation dialog for saving an ability preset.
* Uses packet-based communication for proper client-server architecture.
*/
public class SubGuiAbilitySaveConfirm extends SubGuiInterface {
private final Ability ability;
private final boolean exists;
private final IAbilityConfigCallback callback;
public SubGuiAbilitySaveConfirm(Ability ability) {
this(ability, null);
}
public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback) {
this.ability = ability;
this.exists = AbilityController.Instance.hasSavedAbility(ability.getName());
this.callback = callback;
setBackground("menubg.png");
xSize = 200;
@@ -30,15 +37,9 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface {
int y = guiTop + 10;
if (exists) {
addLabel(new GuiNpcLabel(0, "ability.save.overwrite", guiLeft + 10, y));
y += 12;
addLabel(new GuiNpcLabel(1, "'" + ability.getName() + "'?", guiLeft + 10, y));
} else {
addLabel(new GuiNpcLabel(0, "ability.save.confirm", guiLeft + 10, y));
y += 12;
addLabel(new GuiNpcLabel(1, "'" + ability.getName() + "'?", guiLeft + 10, y));
}
addLabel(new GuiNpcLabel(0, "ability.save.confirm", guiLeft + 10, y));
y += 12;
addLabel(new GuiNpcLabel(1, "'" + ability.getName() + "'?", guiLeft + 10, y));
y += 30;
@@ -51,8 +52,11 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface {
int id = guibutton.id;
if (id == 0) {
// Save the ability
AbilityController.Instance.saveAbility(ability);
// Save the ability via packet
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
if (callback != null) {
callback.onAbilitySaved(ability);
}
close();
} else if (id == 1) {
close();
@@ -2,7 +2,11 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Condition;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.*;
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.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* SubGui for editing a single ability condition.
@@ -84,7 +88,9 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi
// Condition Type selector
addLabel(new GuiNpcLabel(1, "gui.type", labelX, y + 5));
addButton(new GuiNpcButton(1, fieldX, y, 115, 20, CONDITION_TYPES, selectedTypeIndex));
GuiNpcButton typeBtn = new GuiNpcButton(1, fieldX, y, 115, 20, CONDITION_TYPES, selectedTypeIndex);
typeBtn.setHoverText("condition.hover.type");
addButton(typeBtn);
y += 26;
// Type-specific fields
@@ -92,24 +98,27 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi
if (typeId.equals("hit_count")) {
// Hit count fields
addLabel(new GuiNpcLabel(2, "condition.hits", labelX, y + 5));
GuiNpcTextField hitsField = new GuiNpcTextField(2, this, fontRendererObj, fieldX, y, 40, 20, String.valueOf(requiredHits));
GuiNpcTextField hitsField = new GuiNpcTextField(2, this, fontRendererObj, fieldX, y, 40, 20, "" + requiredHits);
hitsField.setIntegersOnly();
hitsField.setMinMaxDefault(1, 100, 3);
hitsField.setHoverText("condition.hover.hits");
addTextField(hitsField);
y += 24;
addLabel(new GuiNpcLabel(3, "condition.within", labelX, y + 5));
GuiNpcTextField ticksField = new GuiNpcTextField(3, this, fontRendererObj, fieldX, y, 40, 20, String.valueOf(withinTicks));
GuiNpcTextField ticksField = new GuiNpcTextField(3, this, fontRendererObj, fieldX, y, 40, 20, "" + withinTicks);
ticksField.setIntegersOnly();
ticksField.setMinMaxDefault(1, 1200, 60);
ticksField.setHoverText("condition.hover.within");
addTextField(ticksField);
} else {
// HP threshold field (as percentage)
addLabel(new GuiNpcLabel(2, "condition.percent", labelX, y + 5));
int percent = (int)(threshold * 100);
GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, String.valueOf(percent));
int percent = (int) (threshold * 100);
GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, "" + percent);
thresholdField.setIntegersOnly();
thresholdField.setMinMaxDefault(1, 99, 50);
thresholdField.setHoverText("condition.hover.threshold");
addTextField(thresholdField);
addLabel(new GuiNpcLabel(4, "%", fieldX + 45, y + 5));
}
@@ -1,92 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityBeam;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Beam ability type-specific settings.
*/
public class SubGuiAbilityBeam extends SubGuiAbilityConfig {
private final AbilityBeam beam;
public SubGuiAbilityBeam(AbilityBeam ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.beam = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Damage Interval
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, beam.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.dmgInterval", col2LabelX, y + 5));
addTextField(createIntField(101, col2FieldX, y, 50, beam.getDamageInterval()));
y += 24;
// Row 2: Beam Length + Beam Width
addLabel(new GuiNpcLabel(102, "ability.beamLength", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, beam.getBeamLength()));
addLabel(new GuiNpcLabel(103, "ability.beamWidth", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, beam.getBeamWidth()));
y += 24;
// Row 3: Sweep Angle + Sweep Speed
addLabel(new GuiNpcLabel(104, "ability.sweepAngle", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, beam.getSweepAngle()));
addLabel(new GuiNpcLabel(105, "ability.sweepSpeed", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, beam.getSweepSpeed()));
y += 24;
// Row 4: Piercing + Lock On Target
addLabel(new GuiNpcLabel(106, "ability.piercing", labelX, y + 5));
addButton(new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isPiercing() ? 1 : 0));
addLabel(new GuiNpcLabel(107, "ability.lockTarget", col2LabelX, y + 5));
addButton(new GuiNpcButton(107, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isLockOnTarget() ? 1 : 0));
y += 24;
// Row 5: Sweep Back & Forth
addLabel(new GuiNpcLabel(108, "ability.sweepBackForth", labelX, y + 5));
addButton(new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isSweepBackAndForth() ? 1 : 0));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 106: beam.setPiercing(value == 1); break;
case 107: beam.setLockOnTarget(value == 1); break;
case 108: beam.setSweepBackAndForth(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: beam.setDamage(parseFloat(field, beam.getDamage())); break;
case 101: beam.setDamageInterval(field.getInteger()); break;
case 102: beam.setBeamLength(parseFloat(field, beam.getBeamLength())); break;
case 103: beam.setBeamWidth(parseFloat(field, beam.getBeamWidth())); break;
case 104: beam.setSweepAngle(parseFloat(field, beam.getSweepAngle())); break;
case 105: beam.setSweepSpeed(parseFloat(field, beam.getSweepSpeed())); break;
}
}
}
@@ -1,59 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCharge;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Charge ability type-specific settings.
*/
public class SubGuiAbilityCharge extends SubGuiAbilityConfig {
private final AbilityCharge charge;
public SubGuiAbilityCharge(AbilityCharge ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.charge = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, charge.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, charge.getChargeSpeed()));
y += 24;
// Row 2: Knockback
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, charge.getKnockback()));
y += 24;
// Row 3: Hit Width
addLabel(new GuiNpcLabel(104, "ability.hitWidth", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, charge.getHitWidth()));
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: charge.setDamage(parseFloat(field, charge.getDamage())); break;
case 101: charge.setChargeSpeed(parseFloat(field, charge.getChargeSpeed())); break;
case 102: charge.setKnockback(parseFloat(field, charge.getKnockback())); break;
case 104: charge.setHitWidth(parseFloat(field, charge.getHitWidth())); break;
}
}
}
@@ -1,104 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCutter;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Cutter ability type-specific settings.
*/
public class SubGuiAbilityCutter extends SubGuiAbilityConfig {
private final AbilityCutter cutter;
public SubGuiAbilityCutter(AbilityCutter ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.cutter = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Range
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, cutter.getDamage()));
addLabel(new GuiNpcLabel(101, "gui.range", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, cutter.getRange()));
y += 24;
// Row 2: Arc Angle + Inner Radius
addLabel(new GuiNpcLabel(102, "ability.arcAngle", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, cutter.getArcAngle()));
addLabel(new GuiNpcLabel(103, "ability.innerRadius", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, cutter.getInnerRadius()));
y += 24;
// Row 3: Knockback + Sweep Speed
addLabel(new GuiNpcLabel(104, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, cutter.getKnockback()));
addLabel(new GuiNpcLabel(105, "ability.sweepSpeed", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, cutter.getSweepSpeed()));
y += 24;
// Row 4: Sweep Mode + Piercing
addLabel(new GuiNpcLabel(106, "ability.sweepMode", labelX, y + 5));
String[] sweepModes = {"Swipe", "Spin"};
addButton(new GuiNpcButton(106, fieldX, y, 70, 20, sweepModes, cutter.getSweepMode().ordinal()));
addLabel(new GuiNpcLabel(107, "ability.piercing", col2LabelX, y + 5));
addButton(new GuiNpcButton(107, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, cutter.isPiercing() ? 1 : 0));
y += 24;
// Row 5: Stun Duration + Poison Time
addLabel(new GuiNpcLabel(108, "ability.stunDuration", labelX, y + 5));
addTextField(createIntField(108, fieldX, y, 50, cutter.getStunDuration()));
addLabel(new GuiNpcLabel(109, "ability.poisonTime", col2LabelX, y + 5));
addTextField(createIntField(109, col2FieldX, y, 50, cutter.getPoisonDurationSeconds()));
y += 24;
// Row 6: Poison Level
addLabel(new GuiNpcLabel(110, "ability.poisonLvl", labelX, y + 5));
addTextField(createIntField(110, fieldX, y, 50, cutter.getPoisonLevel()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 106: cutter.setSweepMode(AbilityCutter.SweepMode.values()[value]); break;
case 107: cutter.setPiercing(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: cutter.setDamage(parseFloat(field, cutter.getDamage())); break;
case 101: cutter.setRange(parseFloat(field, cutter.getRange())); break;
case 102: cutter.setArcAngle(parseFloat(field, cutter.getArcAngle())); break;
case 103: cutter.setInnerRadius(parseFloat(field, cutter.getInnerRadius())); break;
case 104: cutter.setKnockback(parseFloat(field, cutter.getKnockback())); break;
case 105: cutter.setSweepSpeed(parseFloat(field, cutter.getSweepSpeed())); break;
case 108: cutter.setStunDuration(field.getInteger()); break;
case 109: cutter.setPoisonDurationSeconds(field.getInteger()); break;
case 110: cutter.setPoisonLevel(field.getInteger()); break;
}
}
}
@@ -1,59 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityDash;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Dash ability type-specific settings.
*/
public class SubGuiAbilityDash extends SubGuiAbilityConfig {
private final AbilityDash dash;
public SubGuiAbilityDash(AbilityDash ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.dash = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Dash Mode
addLabel(new GuiNpcLabel(100, "ability.mode", labelX, y + 5));
String[] dashModes = {"Aggressive", "Defensive"};
addButton(new GuiNpcButton(100, fieldX, y, 80, 20, dashModes, dash.getDashMode().ordinal()));
y += 24;
// Row 2: Dash Distance + Dash Speed
addLabel(new GuiNpcLabel(101, "ability.dashDist", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, dash.getDashDistance()));
addLabel(new GuiNpcLabel(102, "ability.dashSpeed", col2LabelX, y + 5));
addTextField(createFloatField(102, col2FieldX, y, 50, dash.getDashSpeed()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 100) {
dash.setDashMode(AbilityDash.DashMode.values()[button.getValue()]);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101: dash.setDashDistance(parseFloat(field, dash.getDashDistance())); break;
case 102: dash.setDashSpeed(parseFloat(field, dash.getDashSpeed())); break;
}
}
}
@@ -1,96 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Guard ability type-specific settings.
*/
public class SubGuiAbilityGuard extends SubGuiAbilityConfig {
private final AbilityGuard guard;
public SubGuiAbilityGuard(AbilityGuard ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.guard = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 105;
int col2LabelX = guiLeft + 165;
int col2FieldX = guiLeft + 225;
// Row 1: Damage Reduction
addLabel(new GuiNpcLabel(100, "ability.dmgReduce", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, guard.getDamageReduction()));
y += 24;
// Row 2: Can Counter + Counter Type
addLabel(new GuiNpcLabel(101, "ability.canCounter", labelX, y + 5));
addButton(new GuiNpcButton(101, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, guard.isCanCounter() ? 1 : 0));
addLabel(new GuiNpcLabel(102, "ability.counterType", col2LabelX, y + 5));
String[] types = {"Flat", "Percent"};
GuiNpcButton counterTypeButton = new GuiNpcButton(102, col2FieldX, y, 60, 20, types, guard.getCounterType().ordinal());
counterTypeButton.setEnabled(guard.isCanCounter());
addButton(counterTypeButton);
y += 24;
// Row 3: Counter Value + Counter Chance
addLabel(new GuiNpcLabel(103, "ability.counterValue", labelX, y + 5));
GuiNpcTextField counterValueField = createFloatField(103, fieldX, y, 50, guard.getCounterValue());
counterValueField.setEnabled(guard.isCanCounter());
addTextField(counterValueField);
addLabel(new GuiNpcLabel(104, "ability.counterChance", col2LabelX, y + 5));
GuiNpcTextField counterChanceField = createFloatField(104, col2FieldX, y, 50, guard.getCounterChance());
counterChanceField.setEnabled(guard.isCanCounter());
addTextField(counterChanceField);
y += 24;
// Row 4: Counter Sound + Counter Animation
addLabel(new GuiNpcLabel(105, "ability.counterSound", labelX, y + 5));
GuiNpcTextField counterSoundField = new GuiNpcTextField(105, this, fontRendererObj, fieldX, y, 100, 20, guard.getCounterSound());
counterSoundField.setEnabled(guard.isCanCounter());
addTextField(counterSoundField);
addLabel(new GuiNpcLabel(106, "ability.counterAnim", col2LabelX, y + 5));
GuiNpcTextField counterAnimField = createIntField(106, col2FieldX, y, 50, guard.getCounterAnimationId());
counterAnimField.setEnabled(guard.isCanCounter());
addTextField(counterAnimField);
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
switch (id) {
case 101:
guard.setCanCounter(button.getValue() == 1);
initGui();
break;
case 102:
guard.setCounterType(AbilityGuard.CounterType.values()[button.getValue()]);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: guard.setDamageReduction(parseFloat(field, guard.getDamageReduction())); break;
case 103: guard.setCounterValue(parseFloat(field, guard.getCounterValue())); break;
case 104: guard.setCounterChance(parseFloat(field, guard.getCounterChance())); break;
case 105: guard.setCounterSound(field.getText()); break;
case 106: guard.setCounterAnimationId(field.getInteger()); break;
}
}
}
@@ -1,98 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHazard;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Hazard ability type-specific settings.
*/
public class SubGuiAbilityHazard extends SubGuiAbilityConfig {
private final AbilityHazard hazard;
public SubGuiAbilityHazard(AbilityHazard ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.hazard = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Shape + Placement
addLabel(new GuiNpcLabel(100, "ability.shape", labelX, y + 5));
String[] shapes = {"Circle", "Ring", "Cone"};
addButton(new GuiNpcButton(100, fieldX, y, 55, 20, shapes, hazard.getShape().ordinal()));
addLabel(new GuiNpcLabel(101, "ability.placement", col2LabelX, y + 5));
String[] placements = {"Caster", "Target", "FollowCast", "FollowTgt"};
addButton(new GuiNpcButton(101, col2FieldX, y, 60, 20, placements, hazard.getPlacement().ordinal()));
y += 24;
// Row 2: Radius + Inner Radius
addLabel(new GuiNpcLabel(102, "ability.radius", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, hazard.getRadius()));
addLabel(new GuiNpcLabel(103, "ability.innerRadius", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, hazard.getInnerRadius()));
y += 24;
// Row 3: Damage Per Tick + Damage Interval
addLabel(new GuiNpcLabel(104, "ability.dmgPerTick", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, hazard.getDamagePerTick()));
addLabel(new GuiNpcLabel(105, "ability.dmgInterval", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, hazard.getDamageInterval()));
y += 24;
// Row 4: Slowness Level + Debuff Duration
addLabel(new GuiNpcLabel(106, "ability.slownessLvl", labelX, y + 5));
addTextField(createIntField(106, fieldX, y, 50, hazard.getSlownessLevel()));
addLabel(new GuiNpcLabel(107, "ability.debuffDur", col2LabelX, y + 5));
addTextField(createIntField(107, col2FieldX, y, 50, hazard.getDebuffDuration()));
y += 24;
// Row 5: Poison Level + Affects Caster
addLabel(new GuiNpcLabel(108, "ability.poisonLvl", labelX, y + 5));
addTextField(createIntField(108, fieldX, y, 50, hazard.getPoisonLevel()));
addLabel(new GuiNpcLabel(109, "ability.affectsCaster", col2LabelX, y + 5));
addButton(new GuiNpcButton(109, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, hazard.isAffectsCaster() ? 1 : 0));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 100: hazard.setShape(AbilityHazard.HazardShape.values()[value]); break;
case 101: hazard.setPlacement(AbilityHazard.PlacementMode.values()[value]); break;
case 109: hazard.setAffectsCaster(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 102: hazard.setRadius(parseFloat(field, hazard.getRadius())); break;
case 103: hazard.setInnerRadius(parseFloat(field, hazard.getInnerRadius())); break;
case 104: hazard.setDamagePerTick(parseFloat(field, hazard.getDamagePerTick())); break;
case 105: hazard.setDamageInterval(field.getInteger()); break;
case 106: hazard.setSlownessLevel(field.getInteger()); break;
case 107: hazard.setDebuffDuration(field.getInteger()); break;
case 108: hazard.setPoisonLevel(field.getInteger()); break;
}
}
}
@@ -1,74 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeal;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Heal ability type-specific settings.
*/
public class SubGuiAbilityHeal extends SubGuiAbilityConfig {
private final AbilityHeal heal;
public SubGuiAbilityHeal(AbilityHeal ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.heal = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Heal Amount + Heal Percent
addLabel(new GuiNpcLabel(100, "ability.healAmount", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, heal.getHealAmount()));
addLabel(new GuiNpcLabel(101, "ability.healPercent", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, heal.getHealPercent()));
y += 24;
// Row 2: Heal Radius + Instant Heal
addLabel(new GuiNpcLabel(102, "ability.healRadius", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, heal.getHealRadius()));
addLabel(new GuiNpcLabel(103, "dialog.instant", col2LabelX, y + 5));
addButton(new GuiNpcButton(103, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isInstantHeal() ? 1 : 0));
y += 24;
// Row 3: Heal Self + Heal Allies
addLabel(new GuiNpcLabel(104, "ability.healSelf", labelX, y + 5));
addButton(new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isHealSelf() ? 1 : 0));
addLabel(new GuiNpcLabel(105, "ability.healAllies", col2LabelX, y + 5));
addButton(new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isHealAllies() ? 1 : 0));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 103: heal.setInstantHeal(value == 1); break;
case 104: heal.setHealSelf(value == 1); break;
case 105: heal.setHealAllies(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: heal.setHealAmount(parseFloat(field, heal.getHealAmount())); break;
case 101: heal.setHealPercent(parseFloat(field, heal.getHealPercent())); break;
case 102: heal.setHealRadius(parseFloat(field, heal.getHealRadius())); break;
}
}
}
@@ -1,62 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Heavy Hit ability type-specific settings.
*/
public class SubGuiAbilityHeavyHit extends SubGuiAbilityConfig {
private final AbilityHeavyHit heavyHit;
public SubGuiAbilityHeavyHit(AbilityHeavyHit ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.heavyHit = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Potion Time
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, heavyHit.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.potionTime", col2LabelX, y + 5));
addTextField(createIntField(101, col2FieldX, y, 50, heavyHit.getPotionDurationSeconds()));
y += 24;
// Row 2: Knockback + Slowness Level
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, heavyHit.getKnockback()));
addLabel(new GuiNpcLabel(103, "ability.slownessLvl", col2LabelX, y + 5));
addTextField(createIntField(103, col2FieldX, y, 50, heavyHit.getSlownessLevel()));
y += 24;
// Row 3: Weakness Level
addLabel(new GuiNpcLabel(104, "ability.weaknessLvl", labelX, y + 5));
addTextField(createIntField(104, fieldX, y, 50, heavyHit.getWeaknessLevel()));
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: heavyHit.setDamage(parseFloat(field, heavyHit.getDamage())); break;
case 101: heavyHit.setPotionDurationSeconds(field.getInteger()); break;
case 102: heavyHit.setKnockback(parseFloat(field, heavyHit.getKnockback())); break;
case 103: heavyHit.setSlownessLevel(field.getInteger()); break;
case 104: heavyHit.setWeaknessLevel(field.getInteger()); break;
}
}
}
@@ -1,96 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityOrb;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Orb ability type-specific settings.
*/
public class SubGuiAbilityOrb extends SubGuiAbilityConfig {
private final AbilityOrb orb;
public SubGuiAbilityOrb(AbilityOrb ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.orb = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, orb.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, orb.getOrbSpeed()));
y += 24;
// Row 2: Orb Size + Max Distance
addLabel(new GuiNpcLabel(102, "stats.size", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, orb.getOrbSize()));
addLabel(new GuiNpcLabel(103, "ability.maxDist", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, orb.getMaxDistance()));
y += 24;
// Row 3: Homing + Homing Strength
addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5));
addButton(new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isHoming() ? 1 : 0));
addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, orb.getHomingStrength()));
y += 24;
// Row 4: Explosive + Explosion Radius
addLabel(new GuiNpcLabel(106, "ability.explosive", labelX, y + 5));
addButton(new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isExplosive() ? 1 : 0));
addLabel(new GuiNpcLabel(107, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, orb.getExplosionRadius()));
y += 24;
// Row 5: Knockback + Max Lifetime
addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(108, fieldX, y, 50, orb.getKnockback()));
addLabel(new GuiNpcLabel(109, "ability.lifetime", col2LabelX, y + 5));
addTextField(createIntField(109, col2FieldX, y, 50, orb.getMaxLifetime()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104: orb.setHoming(value == 1); break;
case 106: orb.setExplosive(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: orb.setDamage(parseFloat(field, orb.getDamage())); break;
case 101: orb.setOrbSpeed(parseFloat(field, orb.getOrbSpeed())); break;
case 102: orb.setOrbSize(parseFloat(field, orb.getOrbSize())); break;
case 103: orb.setMaxDistance(parseFloat(field, orb.getMaxDistance())); break;
case 105: orb.setHomingStrength(parseFloat(field, orb.getHomingStrength())); break;
case 107: orb.setExplosionRadius(parseFloat(field, orb.getExplosionRadius())); break;
case 108: orb.setKnockback(parseFloat(field, orb.getKnockback())); break;
case 109: orb.setMaxLifetime(field.getInteger()); break;
}
}
}
@@ -1,97 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Projectile ability type-specific settings.
*/
public class SubGuiAbilityProjectile extends SubGuiAbilityConfig {
private final AbilityProjectile projectile;
public SubGuiAbilityProjectile(AbilityProjectile ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.projectile = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Speed
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, projectile.getDamage()));
addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, projectile.getSpeed()));
y += 24;
// Row 2: Knockback + Projectile Type
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, projectile.getKnockback()));
addLabel(new GuiNpcLabel(103, "ability.projType", col2LabelX, y + 5));
String[] projTypes = {"fireball", "arrow", "magic"};
int typeIdx = 0;
String currType = projectile.getProjectileType();
for (int i = 0; i < projTypes.length; i++) {
if (projTypes[i].equals(currType)) {
typeIdx = i;
break;
}
}
addButton(new GuiNpcButton(103, col2FieldX, y, 60, 20, projTypes, typeIdx));
y += 24;
// Row 3: Explosive + Explosion Radius
addLabel(new GuiNpcLabel(104, "ability.explosive", labelX, y + 5));
addButton(new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, projectile.isExplosive() ? 1 : 0));
addLabel(new GuiNpcLabel(105, "ability.explosionRad", col2LabelX, y + 5));
addTextField(createFloatField(105, col2FieldX, y, 50, projectile.getExplosionRadius()));
y += 24;
// Row 4: Homing + Homing Strength
addLabel(new GuiNpcLabel(106, "ability.homing", labelX, y + 5));
addButton(new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, projectile.isHoming() ? 1 : 0));
addLabel(new GuiNpcLabel(107, "ability.homingStr", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, projectile.getHomingStrength()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 103:
String[] projTypes = {"fireball", "arrow", "magic"};
projectile.setProjectileType(projTypes[value]);
break;
case 104: projectile.setExplosive(value == 1); break;
case 106: projectile.setHoming(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: projectile.setDamage(parseFloat(field, projectile.getDamage())); break;
case 101: projectile.setSpeed(parseFloat(field, projectile.getSpeed())); break;
case 102: projectile.setKnockback(parseFloat(field, projectile.getKnockback())); break;
case 105: projectile.setExplosionRadius(parseFloat(field, projectile.getExplosionRadius())); break;
case 107: projectile.setHomingStrength(parseFloat(field, projectile.getHomingStrength())); break;
}
}
}
@@ -1,65 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Shockwave ability type-specific settings.
*/
public class SubGuiAbilityShockwave extends SubGuiAbilityConfig {
private final AbilityShockwave shockwave;
public SubGuiAbilityShockwave(AbilityShockwave ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.shockwave = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Push Radius
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, shockwave.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.pushRadius", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, shockwave.getPushRadius()));
y += 24;
// Row 2: Push Strength
addLabel(new GuiNpcLabel(102, "ability.pushStrength", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, shockwave.getPushStrength()));
y += 24;
// Row 3: Stun Duration + Max Targets
addLabel(new GuiNpcLabel(103, "ability.stunDuration", labelX, y + 5));
addTextField(createIntField(103, fieldX, y, 50, shockwave.getStunDuration()));
addLabel(new GuiNpcLabel(104, "ability.maxTargets", col2LabelX, y + 5));
addTextField(createIntField(104, col2FieldX, y, 50, shockwave.getMaxTargets()));
y += 24;
addLabel(new GuiNpcLabel(105, "ability.shockwaveFalloff", labelX, y + 5));
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: shockwave.setDamage(parseFloat(field, shockwave.getDamage())); break;
case 101: shockwave.setPushRadius(parseFloat(field, shockwave.getPushRadius())); break;
case 102: shockwave.setPushStrength(parseFloat(field, shockwave.getPushStrength())); break;
case 103: shockwave.setStunDuration(field.getInteger()); break;
case 104: shockwave.setMaxTargets(field.getInteger()); break;
}
}
}
@@ -1,62 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Slam ability type-specific settings.
*/
public class SubGuiAbilitySlam extends SubGuiAbilityConfig {
private final AbilitySlam slam;
public SubGuiAbilitySlam(AbilitySlam ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.slam = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Damage + Radius
addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, slam.getDamage()));
addLabel(new GuiNpcLabel(101, "ability.radius", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, slam.getRadius()));
y += 24;
// Row 2: Knockback + Leap Speed
addLabel(new GuiNpcLabel(102, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, slam.getKnockbackStrength()));
addLabel(new GuiNpcLabel(103, "ability.leapSpeed", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, slam.getLeapSpeed()));
y += 24;
// Row 3: Leap Height
addLabel(new GuiNpcLabel(104, "ability.leapHeight", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, slam.getLeapHeight()));
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: slam.setDamage(parseFloat(field, slam.getDamage())); break;
case 101: slam.setRadius(parseFloat(field, slam.getRadius())); break;
case 102: slam.setKnockbackStrength(parseFloat(field, slam.getKnockbackStrength())); break;
case 103: slam.setLeapSpeed(parseFloat(field, slam.getLeapSpeed())); break;
case 104: slam.setLeapHeight(parseFloat(field, slam.getLeapHeight())); break;
}
}
}
@@ -1,115 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Teleport ability type-specific settings.
*/
public class SubGuiAbilityTeleport extends SubGuiAbilityConfig {
private final AbilityTeleport teleport;
public SubGuiAbilityTeleport(AbilityTeleport ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.teleport = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Mode
addLabel(new GuiNpcLabel(100, "ability.mode", labelX, y + 5));
String[] modes = {"Blink", "Behind", "Single"};
addButton(new GuiNpcButton(100, fieldX, y, 80, 20, modes, teleport.getMode().ordinal()));
y += 24;
switch (teleport.getMode()) {
case BLINK:
// Row 2: Blink Radius + Blink Count
addLabel(new GuiNpcLabel(101, "ability.blinkRadius", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, teleport.getBlinkRadius()));
addLabel(new GuiNpcLabel(102, "ability.blinkCount", col2LabelX, y + 5));
addTextField(createIntField(102, col2FieldX, y, 50, teleport.getBlinkCount()));
y += 24;
// Row 3: Blink Delay + Line of Sight
addLabel(new GuiNpcLabel(103, "ability.blinkDelay", labelX, y + 5));
addTextField(createIntField(103, fieldX, y, 50, teleport.getBlinkDelayTicks()));
addLabel(new GuiNpcLabel(105, "ability.lineOfSight", col2LabelX, y + 5));
addButton(new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isRequireLineOfSight() ? 1 : 0));
y += 24;
break;
case SINGLE:
// Row 2: Blink Radius + Line of Sight
addLabel(new GuiNpcLabel(101, "ability.blinkRadius", labelX, y + 5));
addTextField(createFloatField(101, fieldX, y, 50, teleport.getBlinkRadius()));
addLabel(new GuiNpcLabel(105, "ability.lineOfSight", col2LabelX, y + 5));
addButton(new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isRequireLineOfSight() ? 1 : 0));
y += 24;
break;
case BEHIND:
// Row 2: Behind Distance
addLabel(new GuiNpcLabel(104, "ability.behindDistance", labelX, y + 5));
addTextField(createFloatField(104, fieldX, y, 50, teleport.getBehindDistance()));
y += 24;
break;
}
// Damage + Damage Radius
addLabel(new GuiNpcLabel(106, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(106, fieldX, y, 50, teleport.getDamage()));
addLabel(new GuiNpcLabel(107, "ability.dmgRadius", col2LabelX, y + 5));
addTextField(createFloatField(107, col2FieldX, y, 50, teleport.getDamageRadius()));
y += 24;
// Damage at Start/End
addLabel(new GuiNpcLabel(108, "ability.dmgAtStart", labelX, y + 5));
addButton(new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isDamageAtStart() ? 1 : 0));
addLabel(new GuiNpcLabel(109, "ability.dmgAtEnd", col2LabelX, y + 5));
addButton(new GuiNpcButton(109, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isDamageAtEnd() ? 1 : 0));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 100:
teleport.setMode(AbilityTeleport.TeleportMode.values()[value]);
initGui();
break;
case 105: teleport.setRequireLineOfSight(value == 1); break;
case 108: teleport.setDamageAtStart(value == 1); break;
case 109: teleport.setDamageAtEnd(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101: teleport.setBlinkRadius(parseFloat(field, teleport.getBlinkRadius())); break;
case 102: teleport.setBlinkCount(field.getInteger()); break;
case 103: teleport.setBlinkDelayTicks(field.getInteger()); break;
case 104: teleport.setBehindDistance(parseFloat(field, teleport.getBehindDistance())); break;
case 106: teleport.setDamage(parseFloat(field, teleport.getDamage())); break;
case 107: teleport.setDamageRadius(parseFloat(field, teleport.getDamageRadius())); break;
}
}
}
@@ -1,92 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Trap ability type-specific settings.
*/
public class SubGuiAbilityTrap extends SubGuiAbilityConfig {
private final AbilityTrap trap;
public SubGuiAbilityTrap(AbilityTrap ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.trap = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Placement + Trigger Radius
addLabel(new GuiNpcLabel(100, "ability.placement", labelX, y + 5));
String[] placements = {"Caster", "Target", "Ahead"};
addButton(new GuiNpcButton(100, fieldX, y, 55, 20, placements, trap.getPlacement().ordinal()));
addLabel(new GuiNpcLabel(101, "ability.triggerRad", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, trap.getTriggerRadius()));
y += 24;
// Row 2: Damage + Damage Radius
addLabel(new GuiNpcLabel(102, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, trap.getDamage()));
addLabel(new GuiNpcLabel(103, "ability.dmgRadius", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, trap.getDamageRadius()));
y += 24;
// Row 3: Arm Time + Max Triggers
addLabel(new GuiNpcLabel(104, "ability.armTime", labelX, y + 5));
addTextField(createIntField(104, fieldX, y, 50, trap.getArmTime()));
addLabel(new GuiNpcLabel(105, "ability.maxTriggers", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, trap.getMaxTriggers()));
y += 24;
// Row 4: Root Duration + Stun Duration
addLabel(new GuiNpcLabel(106, "ability.rootDuration", labelX, y + 5));
addTextField(createIntField(106, fieldX, y, 50, trap.getRootDuration()));
addLabel(new GuiNpcLabel(107, "ability.stunDuration", col2LabelX, y + 5));
addTextField(createIntField(107, col2FieldX, y, 50, trap.getStunDuration()));
y += 24;
// Row 5: Knockback
addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5));
addTextField(createFloatField(108, fieldX, y, 50, trap.getKnockback()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
if (id == 100) {
trap.setPlacement(AbilityTrap.TrapPlacement.values()[button.getValue()]);
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101: trap.setTriggerRadius(parseFloat(field, trap.getTriggerRadius())); break;
case 102: trap.setDamage(parseFloat(field, trap.getDamage())); break;
case 103: trap.setDamageRadius(parseFloat(field, trap.getDamageRadius())); break;
case 104: trap.setArmTime(field.getInteger()); break;
case 105: trap.setMaxTriggers(field.getInteger()); break;
case 106: trap.setRootDuration(field.getInteger()); break;
case 107: trap.setStunDuration(field.getInteger()); break;
case 108: trap.setKnockback(parseFloat(field, trap.getKnockback())); break;
}
}
}
@@ -1,96 +0,0 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
/**
* GUI for configuring Vortex ability type-specific settings.
*/
public class SubGuiAbilityVortex extends SubGuiAbilityConfig {
private final AbilityVortex vortex;
public SubGuiAbilityVortex(AbilityVortex ability, IAbilityConfigCallback callback) {
super(ability, callback);
this.vortex = ability;
}
@Override
protected void initTypeTab(int startY) {
int y = startY;
int labelX = guiLeft + 8;
int fieldX = guiLeft + 85;
int col2LabelX = guiLeft + 145;
int col2FieldX = guiLeft + 205;
// Row 1: Pull Radius + Pull Strength
addLabel(new GuiNpcLabel(100, "ability.pullRadius", labelX, y + 5));
addTextField(createFloatField(100, fieldX, y, 50, vortex.getPullRadius()));
addLabel(new GuiNpcLabel(101, "ability.pullStrength", col2LabelX, y + 5));
addTextField(createFloatField(101, col2FieldX, y, 50, vortex.getPullStrength()));
y += 24;
// Row 2: Damage + Knockback
addLabel(new GuiNpcLabel(102, "enchantment.damage", labelX, y + 5));
addTextField(createFloatField(102, fieldX, y, 50, vortex.getDamage()));
addLabel(new GuiNpcLabel(103, "ability.knockback", col2LabelX, y + 5));
addTextField(createFloatField(103, col2FieldX, y, 50, vortex.getKnockback()));
y += 24;
// Row 3: AOE + Max Targets
addLabel(new GuiNpcLabel(104, "ability.aoe", labelX, y + 5));
addButton(new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, vortex.isAoe() ? 1 : 0));
addLabel(new GuiNpcLabel(105, "ability.maxTargets", col2LabelX, y + 5));
addTextField(createIntField(105, col2FieldX, y, 50, vortex.getMaxTargets()));
y += 24;
// Row 4: Stun Duration + Root Duration
addLabel(new GuiNpcLabel(106, "ability.stunDuration", labelX, y + 5));
addTextField(createIntField(106, fieldX, y, 50, vortex.getStunDuration()));
addLabel(new GuiNpcLabel(107, "ability.rootDuration", col2LabelX, y + 5));
addTextField(createIntField(107, col2FieldX, y, 50, vortex.getRootDuration()));
y += 24;
// Row 5: Damage on Pull + Pull Damage
addLabel(new GuiNpcLabel(108, "ability.dmgOnPull", labelX, y + 5));
addButton(new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, vortex.isDamageOnPull() ? 1 : 0));
addLabel(new GuiNpcLabel(109, "ability.pullDamage", col2LabelX, y + 5));
addTextField(createFloatField(109, col2FieldX, y, 50, vortex.getPullDamage()));
}
@Override
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104: vortex.setAoe(value == 1); break;
case 108: vortex.setDamageOnPull(value == 1); break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: vortex.setPullRadius(parseFloat(field, vortex.getPullRadius())); break;
case 101: vortex.setPullStrength(parseFloat(field, vortex.getPullStrength())); break;
case 102: vortex.setDamage(parseFloat(field, vortex.getDamage())); break;
case 103: vortex.setKnockback(parseFloat(field, vortex.getKnockback())); break;
case 105: vortex.setMaxTargets(field.getInteger()); break;
case 106: vortex.setStunDuration(field.getInteger()); break;
case 107: vortex.setRootDuration(field.getInteger()); break;
case 109: vortex.setPullDamage(parseFloat(field, vortex.getPullDamage())); break;
}
}
}
@@ -5,6 +5,7 @@ import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket;
import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket;
import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket;
import kamkeel.npcs.network.packets.request.animation.BuiltInAnimationGetPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
@@ -37,13 +38,19 @@ import java.util.Vector;
public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrollData, ICustomScrollListener, ITextfieldListener, IGuiData, ISubGuiListener, GuiYesNoCallback {
private GuiCustomScroll scrollAnimations;
private HashMap<String, Integer> data = new HashMap<String, Integer>();
private HashMap<String, Integer> customData = new HashMap<String, Integer>();
private HashMap<String, Integer> builtInData = new HashMap<String, Integer>();
private Animation animation = new Animation();
public boolean playingAnimation = false;
private long prevTick;
private String selected = null;
private String search = "";
// Toggle between Custom (false) and Built-in (true) animations
private boolean showingBuiltIn = false;
// Track if current animation is built-in
private boolean currentIsBuiltIn = false;
public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save) {
super(npc);
this.setSave(save);
@@ -58,8 +65,15 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
public void initGui() {
super.initGui();
this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add"));
this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove"));
// Add/Remove buttons - only show for custom animations
if (!showingBuiltIn) {
this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add"));
this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove"));
}
// Toggle button for Custom/Built-in - under Remove button
String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom";
this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel));
if (scrollAnimations == null) {
scrollAnimations = new GuiCustomScroll(this, 0, 0);
@@ -68,13 +82,23 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
scrollAnimations.guiLeft = guiLeft + 220;
scrollAnimations.guiTop = guiTop + 4;
addScroll(scrollAnimations);
// Search field
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search));
if (animation.id == -1)
// Update scroll list based on current view
scrollAnimations.setList(getSearchList());
if (animation.id == -1 && !currentIsBuiltIn)
return;
addLabel(new GuiNpcLabel(10, "ID", guiLeft + 368, guiTop + 192));
addLabel(new GuiNpcLabel(11, animation.id + "", guiLeft + 368, guiTop + 192 + 10));
// ID label - only for custom animations
if (!currentIsBuiltIn) {
addLabel(new GuiNpcLabel(10, "ID", guiLeft + 368, guiTop + 192));
addLabel(new GuiNpcLabel(11, animation.id + "", guiLeft + 368, guiTop + 192 + 10));
} else {
addLabel(new GuiNpcLabel(10, "gui.builtin", guiLeft + 368, guiTop + 192));
}
AnimationData data = npc.display.animationData;
if (!playingAnimation) {
@@ -90,12 +114,13 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
}
}
if (animation != null) {
// Edit button - only for custom animations
if (animation != null && !currentIsBuiltIn) {
this.addButton(new GuiNpcButton(100, guiLeft + 10, guiTop + 192, 45, 20, "gui.edit"));
}
String animTexture = "customnpcs:textures/gui/animation.png";
int playButtonOffsetX = 140;
int playButtonOffsetX = currentIsBuiltIn ? 80 : 140;
if (animation != null && !animation.frames.isEmpty()) {
if (!this.playingAnimation || data.animation.paused) {//Play
this.addLabel(new GuiNpcLabel(90, data.animation.paused ? "animation.paused" : "animation.stopped", guiLeft + playButtonOffsetX - 15, guiTop + 198));
@@ -151,12 +176,17 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
}
}
private HashMap<String, Integer> getCurrentData() {
return showingBuiltIn ? builtInData : customData;
}
private List<String> getSearchList() {
HashMap<String, Integer> data = getCurrentData();
if (search.isEmpty()) {
return new ArrayList<String>(this.data.keySet());
return new ArrayList<String>(data.keySet());
}
List<String> list = new ArrayList<String>();
for (String name : this.data.keySet()) {
for (String name : data.keySet()) {
if (name.toLowerCase().contains(search))
list.add(name);
}
@@ -167,16 +197,31 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
protected void actionPerformed(GuiButton guibutton) {
GuiNpcButton button = (GuiNpcButton) guibutton;
if (button.id == 0) {
// Toggle button
if (button.id == 10) {
showingBuiltIn = !showingBuiltIn;
// Clear selection when switching views
selected = null;
animation = new Animation();
currentIsBuiltIn = false;
scrollAnimations.clear();
initGui();
return;
}
// Add button - only for custom
if (button.id == 0 && !showingBuiltIn) {
save();
String name = "New";
while (data.containsKey(name))
while (customData.containsKey(name))
name += "_";
Animation animation = new Animation(-1, name);
PacketClient.sendClient(new AnimationSavePacket(animation.writeToNBT()));
}
if (button.id == 1) {
if (data.containsKey(scrollAnimations.getSelected())) {
// Remove button - only for custom
if (button.id == 1 && !showingBuiltIn) {
if (customData.containsKey(scrollAnimations.getSelected())) {
GuiYesNo guiyesno = new GuiYesNo(this, scrollAnimations.getSelected(), StatCollector.translateToLocal("gui.delete"), 1);
displayGuiScreen(guiyesno);
}
@@ -204,7 +249,8 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
data.animation.paused = false;
}
if (guibutton.id == 100) {
// Edit button - only for custom
if (guibutton.id == 100 && !currentIsBuiltIn) {
NoppesUtil.openGUI(player, new GuiNPCEditAnimation(this, this.animation, npc));
}
@@ -215,6 +261,10 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
public void setGuiData(NBTTagCompound compound) {
this.animation = new Animation();
animation.readFromNBT(compound);
// Check if this is a built-in animation
currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn");
setSelected(animation.name);
npc.display.animationData.setAnimation(this.animation);
this.playingAnimation = false;
@@ -225,7 +275,13 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
String name = scrollAnimations.getSelected();
this.data = data;
if (type == EnumScrollData.ANIMATIONS) {
this.customData = data;
} else if (type == EnumScrollData.BUILTIN_ANIMATIONS) {
this.builtInData = data;
}
scrollAnimations.setList(getSearchList());
if (name != null)
@@ -242,28 +298,40 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0) {
selected = scrollAnimations.getSelected();
PacketClient.sendClient(new AnimationGetPacket(data.get(selected)));
HashMap<String, Integer> data = getCurrentData();
if (showingBuiltIn) {
// Fetch built-in animation by name
PacketClient.sendClient(new BuiltInAnimationGetPacket(selected));
} else {
// Fetch custom animation by ID
if (data.containsKey(selected)) {
PacketClient.sendClient(new AnimationGetPacket(data.get(selected)));
}
}
}
}
public void save() {
if (selected != null && data.containsKey(selected) && animation != null) {
// Only save custom animations
if (selected != null && customData.containsKey(selected) && animation != null && !currentIsBuiltIn) {
PacketClient.sendClient(new AnimationSavePacket(animation.writeToNBT()));
}
}
@Override
public void unFocused(GuiNpcTextField guiNpcTextField) {
if (animation.id == -1)
// Don't allow renaming built-in animations
if (animation.id == -1 || currentIsBuiltIn)
return;
if (guiNpcTextField.id == 0) {
String name = guiNpcTextField.getText();
if (!name.isEmpty() && !data.containsKey(name)) {
if (!name.isEmpty() && !customData.containsKey(name)) {
String old = animation.name;
data.remove(animation.name);
customData.remove(animation.name);
animation.name = name;
data.put(animation.name, animation.id);
customData.put(animation.name, animation.id);
selected = name;
scrollAnimations.replace(old, animation.name);
}
@@ -280,10 +348,12 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol
if (!result)
return;
if (id == 1) {
if (data.containsKey(scrollAnimations.getSelected())) {
PacketClient.sendClient(new AnimationRemovePacket(data.get(selected)));
// Only delete custom animations
if (customData.containsKey(scrollAnimations.getSelected()) && !showingBuiltIn) {
PacketClient.sendClient(new AnimationRemovePacket(customData.get(selected)));
scrollAnimations.clear();
animation = new Animation();
currentIsBuiltIn = false;
initGui();
}
}
@@ -338,21 +338,21 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
// Health
label = StatCollector.translateToLocal("stats.health") + ": ";
value = String.valueOf(npc.stats.maxHealth);
value = "" + npc.stats.maxHealth;
fontRendererObj.drawString(label, xLabel, y, 0x29d6b9, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
// Damage (using getAttackStrength)
label = StatCollector.translateToLocal("stats.meleestrength") + ": ";
value = String.valueOf(npc.stats.getAttackStrength());
value = "" + npc.stats.getAttackStrength();
fontRendererObj.drawString(label, xLabel, y, 0xff5714, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
// Attack Speed
label = StatCollector.translateToLocal("stats.meleespeed") + ": ";
value = String.valueOf(npc.stats.attackSpeed);
value = "" + npc.stats.attackSpeed;
fontRendererObj.drawString(label, xLabel, y, 0xf7ca28, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
@@ -381,7 +381,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
// Walk Speed
label = StatCollector.translateToLocal("stats.speed") + ": ";
value = String.valueOf(npc.ais.getWalkingSpeed());
value = "" + npc.ais.getWalkingSpeed();
fontRendererObj.drawString(label, xLabel, y, 0xffae0d, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
@@ -415,7 +415,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
// Version
label = StatCollector.translateToLocal("display.version") + ": ";
value = String.valueOf(linkedItem.version);
value = "" + linkedItem.version;
fontRendererObj.drawString(label, xLabel, y, labelColor, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
@@ -423,7 +423,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
// Max Stack Size
labelColor = 0xff5714;
label = StatCollector.translateToLocal("display.maxStack") + ": ";
value = String.valueOf(linkedItem.stackSize);
value = "" + linkedItem.stackSize;
fontRendererObj.drawString(label, xLabel, y, labelColor, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
@@ -431,7 +431,7 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
// Dig Speed
labelColor = 0xf7ca28;
label = StatCollector.translateToLocal("display.digSpeed") + ": ";
value = String.valueOf(linkedItem.digSpeed);
value = "" + linkedItem.digSpeed;
fontRendererObj.drawString(label, xLabel, y, labelColor, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
@@ -498,14 +498,14 @@ public class GuiNPCManageLinked extends GuiNPCInterface2 implements IScrollData,
labelColor = 0x7cff54;
// isTool
label = StatCollector.translateToLocal("display.isTool") + ": ";
value = String.valueOf(linkedItem.isTool).toUpperCase();
value = ("" + linkedItem.isTool).toUpperCase();
fontRendererObj.drawString(label, xLabel, y, labelColor, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
// isNormalItem
label = StatCollector.translateToLocal("display.isNormalItem") + ": ";
value = String.valueOf(linkedItem.isNormalItem).toUpperCase();
value = ("" + linkedItem.isNormalItem).toUpperCase();
fontRendererObj.drawString(label, xLabel, y, labelColor, false);
fontRendererObj.drawString(value, xValue, y, valueColor, false);
y += 15;
@@ -1,114 +1,269 @@
package noppes.npcs.client.gui.global;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket;
import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.SubGuiAbilityDeleteConfirm;
import noppes.npcs.client.gui.advanced.SubGuiAbilityLoad;
import noppes.npcs.client.gui.util.*;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.AbilityPreviewExecutor;
import noppes.npcs.client.gui.util.GuiAbilityInterface;
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.GuiTexturedButton;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IScrollData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
/**
* Global GUI for managing saved ability presets.
* Allows viewing, editing, and deleting saved abilities.
* Global GUI for managing saved ability presets with 3D preview.
*
* Features:
* - Left side: 3D preview of NPC with ability effects
* - Right side: Ability list with search
* - Play/Pause/Stop buttons to preview abilities
*/
public class GuiNpcManageAbilities extends GuiNPCInterface2 implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback {
public class GuiNpcManageAbilities extends GuiAbilityInterface
implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback,
ITextfieldListener, GuiYesNoCallback, IScrollData, IGuiData {
// ==================== DATA ====================
private GuiCustomScroll scroll;
private String selectedName = null;
private List<String> abilityNames = new ArrayList<>();
private HashMap<String, Integer> abilityData = new HashMap<>();
/** Maps display name -> UUID for custom abilities */
private final HashMap<String, String> displayToUuid = new HashMap<>();
private String selected = null;
private String selectedUuid = null;
private String search = "";
private Ability selectedAbility = null;
// ==================== PREVIEW ====================
private AbilityPreviewExecutor previewExecutor;
private long prevTick = 0;
public GuiNpcManageAbilities(EntityNPCInterface npc) {
super(npc);
loadAbilityNames();
}
private void loadAbilityNames() {
Set<String> names = AbilityController.Instance.getSavedAbilityNames();
abilityNames = new ArrayList<>(names);
// Layout offset
this.xOffset = -148 + 110;
this.yOffset = -170 + 167;
// Initialize preview executor
previewExecutor = new AbilityPreviewExecutor();
previewExecutor.setParentGui(this);
// Request ability data from server
PacketClient.sendClient(new CustomAbilitiesGetPacket());
// Enable animation data
AnimationData data = npc.display.animationData;
data.setEnabled(true);
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + 10;
// Edit button (above Remove)
addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 8, 45, 20, "gui.edit"));
getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null);
// Title label
addLabel(new GuiNpcLabel(0, "ability.manager.title", guiLeft + 10, y));
y += 20;
// Remove button
addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove"));
getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected));
// Scroll list of saved abilities
// Scroll list of saved abilities (right side)
if (scroll == null) {
scroll = new GuiCustomScroll(this, 0);
scroll.setSize(143, 185);
}
scroll.setSize(xSize - 90, 160);
scroll.guiLeft = guiLeft + 10;
scroll.guiTop = y;
scroll.setUnsortedList(getFilteredList());
if (selectedName != null && abilityNames.contains(selectedName)) {
scroll.setSelected(selectedName);
}
scroll.guiLeft = guiLeft + 220;
scroll.guiTop = guiTop + 4;
addScroll(scroll);
// Update scroll list
scroll.setList(getSearchList());
if (selected != null && displayToUuid.containsKey(selected)) {
scroll.setSelected(selected);
}
// Search bar
addTextField(new GuiNpcTextField(1, this, fontRendererObj, guiLeft + 10, y + 163, xSize - 90, 18, search));
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 220, guiTop + 192, 143, 20, search));
// Right side buttons
int btnX = guiLeft + xSize - 70;
addButton(new GuiNpcButton(1, btnX, y, 60, 20, "gui.edit"));
addButton(new GuiNpcButton(2, btnX, y + 25, 60, 20, "gui.delete"));
addButton(new GuiNpcButton(3, btnX, y + 60, 60, 20, "selectServer.refresh"));
// Show ability info only if one is selected
if (selectedAbility == null || selected == null) {
return;
}
// Enable/disable buttons based on selection
getButton(1).setEnabled(selectedName != null && !selectedName.isEmpty());
getButton(2).setEnabled(selectedName != null && !selectedName.isEmpty());
// ID/Name label (below search bar)
addLabel(new GuiNpcLabel(10, "ID: " + selectedAbility.getId(), guiLeft + 220, guiTop + 215));
// Play/Pause/Stop buttons (below model preview area)
String animTexture = "customnpcs:textures/gui/animation.png";
int playButtonOffsetX = 60;
boolean isPlaying = previewExecutor.isPlaying() && !previewExecutor.isPaused();
boolean isPaused = previewExecutor.isPaused();
boolean isActive = previewExecutor.isActive();
if (!isPlaying || isPaused) {
// Show Play button
String statusKey = isPaused ? "animation.paused" : "animation.stopped";
addLabel(new GuiNpcLabel(90, statusKey, guiLeft + playButtonOffsetX, guiTop + 198));
addButton(new GuiTexturedButton(91, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 11, 20, animTexture, 18, 71));
} else {
// Show Pause button
addLabel(new GuiNpcLabel(90, "animation.playing", guiLeft + playButtonOffsetX, guiTop + 198));
addButton(new GuiTexturedButton(92, "", guiLeft + playButtonOffsetX + 70, guiTop + 192, 14, 20, animTexture, 0, 71));
}
if (isActive) {
// Show Stop button
addButton(new GuiTexturedButton(93, "", guiLeft + playButtonOffsetX + 90, guiTop + 192, 14, 20, animTexture, 33, 71));
}
}
private List<String> getFilteredList() {
private List<String> getSearchList() {
if (search.isEmpty()) {
return new ArrayList<>(abilityNames);
return new ArrayList<>(displayToUuid.keySet());
}
List<String> filtered = new ArrayList<>();
for (String name : abilityNames) {
List<String> list = new ArrayList<>();
for (String name : displayToUuid.keySet()) {
if (name.toLowerCase().contains(search.toLowerCase())) {
filtered.add(name);
list.add(name);
}
}
return filtered;
return list;
}
@Override
public void buttonEvent(GuiButton guibutton) {
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
// IMPORTANT: Set NPC rotation BEFORE ticking entities
// This ensures anchor point calculations use the correct facing direction
npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW;
npc.prevRotationYaw = npc.rotationYaw = NPC_FACING_YAW;
npc.prevRotationYawHead = npc.rotationYawHead = NPC_FACING_YAW;
// Tick preview executor (entities will use the rotation set above)
tickPreview();
// Draw base (includes 3D preview via parent class)
super.drawScreen(mouseX, mouseY, partialTicks);
// Draw status text
if (previewExecutor.isActive()) {
String status = previewExecutor.getStatusString();
fontRendererObj.drawString(status, guiLeft + 12, guiTop + 175, 0xFFFFFF);
}
}
/**
* Tick the preview executor and animations.
*/
private void tickPreview() {
if (previewExecutor.isPlaying() && !previewExecutor.isPaused()) {
long time = mc.theWorld != null ? mc.theWorld.getTotalWorldTime() : System.currentTimeMillis() / 50;
if (time != prevTick) {
// Advance animation
npc.display.animationData.increaseTime();
// Tick preview
previewExecutor.tick();
// Sync telegraph to GUI for rendering
setPreviewTelegraph(previewExecutor.getTelegraph());
prevTick = time;
// Check if preview finished
if (!previewExecutor.isActive()) {
initGui();
}
}
}
}
@Override
protected void actionPerformed(GuiButton guibutton) {
super.actionPerformed(guibutton);
int id = guibutton.id;
if (id == 1 && selectedName != null) {
if (id == 1 && selected != null && selectedUuid != null) {
GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), 1);
displayGuiScreen(guiyesno);
} else if (id == 100 && selectedAbility != null) {
// Edit
Ability ability = AbilityController.Instance.getSavedAbility(selectedName);
if (ability != null) {
setSubGui(ability.createConfigGui(this));
previewExecutor.stop();
setSubGui(selectedAbility.createConfigGui(this));
} else if (id == 91) {
// Play button
if (selectedAbility != null) {
if (previewExecutor.isPaused()) {
previewExecutor.play();
} else {
previewExecutor.startPreview(selectedAbility, npc);
}
initGui();
}
} else if (id == 2 && selectedName != null) {
// Delete
setSubGui(new SubGuiAbilityDeleteConfirm(selectedName, null));
} else if (id == 3) {
// Refresh
AbilityController.Instance.load();
loadAbilityNames();
selectedName = null;
} else if (id == 92) {
// Pause button
previewExecutor.pause();
initGui();
} else if (id == 93) {
// Stop button
previewExecutor.stop();
initGui();
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(55) != null && getTextField(55).isFocused()) {
if (!search.equals(getTextField(55).getText())) {
search = getTextField(55).getText();
scroll.resetScroll();
scroll.setList(getSearchList());
}
}
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll.id == 0) {
selectedName = scroll.getSelected();
initGui();
String newSelection = scroll.getSelected();
if (newSelection != null && !newSelection.equals(selected)) {
previewExecutor.stop();
selected = newSelection;
selectedUuid = displayToUuid.get(selected);
if (selectedUuid != null) {
PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid));
}
}
}
}
@@ -116,48 +271,101 @@ public class GuiNpcManageAbilities extends GuiNPCInterface2 implements ICustomSc
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll.id == 0 && selection != null && !selection.isEmpty()) {
// Double-click to edit
Ability ability = AbilityController.Instance.getSavedAbility(selection);
if (ability != null) {
setSubGui(ability.createConfigGui(this));
if (selectedAbility != null) {
previewExecutor.stop();
setSubGui(selectedAbility.createConfigGui(this));
}
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(1) != null && getTextField(1).isFocused()) {
if (!search.equals(getTextField(1).getText())) {
search = getTextField(1).getText();
scroll.setUnsortedList(getFilteredList());
scroll.resetScroll();
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
if (type == EnumScrollData.CUSTOM_ABILITIES) {
String prevSelected = scroll != null ? scroll.getSelected() : null;
this.abilityData = data;
displayToUuid.clear();
for (String key : data.keySet()) {
// key format: "displayName\tUUID"
int tabIndex = key.indexOf('\t');
if (tabIndex > 0) {
String displayName = key.substring(0, tabIndex);
String uuid = key.substring(tabIndex + 1);
displayToUuid.put(displayName, uuid);
} else {
displayToUuid.put(key, key);
}
}
if (scroll != null) {
scroll.setList(getSearchList());
if (prevSelected != null && displayToUuid.containsKey(prevSelected)) {
scroll.setSelected(prevSelected);
}
}
initGui();
}
}
@Override
public void setGuiData(NBTTagCompound compound) {
// Received ability data from server
selectedAbility = AbilityController.Instance.fromNBT(compound);
if (selectedAbility != null) {
selected = selectedAbility.getName();
if (scroll != null) {
scroll.setSelected(selected);
}
}
previewExecutor.stop();
initGui();
}
@Override
public void setSelected(String selected) {
this.selected = selected;
if (scroll != null) {
scroll.setSelected(selected);
}
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
// Refresh list after any sub gui closes
loadAbilityNames();
if (subgui instanceof SubGuiAbilityDeleteConfirm) {
// After delete, clear selection if it was deleted
if (selectedName != null && !abilityNames.contains(selectedName)) {
selectedName = null;
}
}
initGui();
}
@Override
public void confirmClicked(boolean result, int id) {
NoppesUtil.openGUI(player, this);
if (!result) return;
if (id == 1 && selected != null && selectedUuid != null) {
PacketClient.sendClient(new CustomAbilityRemovePacket(selectedUuid));
scroll.clear();
selected = null;
selectedUuid = null;
selectedAbility = null;
initGui();
}
}
@Override
public void onAbilitySaved(Ability ability) {
// Save the edited ability
AbilityController.Instance.saveAbility(ability);
loadAbilityNames();
initGui();
PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT()));
}
@Override
public void unFocused(GuiNpcTextField textfield) {
// Search field handling is done in keyTyped
}
@Override
public void save() {
// Nothing to save - abilities are saved individually
// Nothing to save - abilities are saved individually via packets
}
@Override
public void onGuiClosed() {
super.onGuiClosed();
// Stop preview when GUI closes
previewExecutor.stop();
}
}
@@ -12,7 +12,7 @@ import net.minecraft.util.StatCollector;
import noppes.npcs.client.CustomNpcResourceListener;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.SubGuiNpcAvailability;
import noppes.npcs.client.gui.script.GuiScriptRecipe;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.GuiButtonBiDirectional;
import noppes.npcs.client.gui.util.GuiContainerNPCInterface2;
import noppes.npcs.client.gui.util.GuiCustomScroll;
@@ -31,6 +31,7 @@ import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.containers.ContainerManageRecipes;
import noppes.npcs.controllers.data.RecipeAnvil;
import noppes.npcs.controllers.data.RecipeCarpentry;
import noppes.npcs.controllers.data.RecipeScript;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
@@ -222,15 +223,9 @@ public class GuiNpcManageRecipes extends GuiContainerNPCInterface2 implements IS
if (button.id == 16) {
save();
if (container.width == 1) {
GuiScriptRecipe gui = new GuiScriptRecipe(this, container.recipeAnvil);
gui.setWorldAndResolution(mc, width, height);
gui.initGui();
mc.currentScreen = gui;
GuiScriptInterface.open(this, new RecipeScript(container.recipeAnvil.id, true));
} else if (!container.recipe.isGlobal) {
GuiScriptRecipe gui = new GuiScriptRecipe(this, container.recipe);
gui.setWorldAndResolution(mc, width, height);
gui.initGui();
mc.currentScreen = gui;
GuiScriptInterface.open(this, new RecipeScript(container.recipe.id, false));
}
}
}
@@ -90,7 +90,7 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
ArrayList<String> list = new ArrayList<>();
Set<Integer> keySet = this.spawn.spawnCompounds.keySet();
for (int i : keySet) {
list.add(String.valueOf(i));
list.add("" + i);
}
this.spawnEntryScroll.setList(list);
addScroll(this.spawnEntryScroll);
@@ -99,7 +99,7 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
if (this.spawnEntryScroll.hasSelected()) {
int selected = Integer.parseInt(this.spawnEntryScroll.getSelected());
addButton(new GuiNpcButton(22, guiLeft + 32, y, 20, 20, "-"));
GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, String.valueOf(selected));
GuiNpcTextField num = new GuiNpcTextField(25, this, guiLeft + 60, y += 10, 30, 20, "" + selected);
num.integersOnly = true;
addTextField(num);
addButton(new GuiNpcButton(26, guiLeft + 92, y, 100, 20, this.getTitle(this.spawn.spawnCompounds.get(selected))));
@@ -215,8 +215,8 @@ public class GuiNpcNaturalSpawns extends GuiNPCInterface2 implements IGuiData, I
}
if (textfield.id == 25 && this.spawnEntryScroll.hasSelected()) {
int selected = Integer.parseInt(spawnEntryScroll.getSelected());
if (spawnEntryScroll.getList().contains(String.valueOf(textfield.getInteger()))) {
textfield.setText(String.valueOf(selected));
if (spawnEntryScroll.getList().contains("" + textfield.getInteger())) {
textfield.setText("" + selected);
return;
}
NBTTagCompound compound = spawn.spawnCompounds.get(selected);
@@ -12,7 +12,7 @@ import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.CustomNpcResourceListener;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.script.GuiScriptLinkedItem;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.GuiButtonBiDirectional;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
@@ -25,6 +25,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.controllers.data.LinkedItem;
import noppes.npcs.controllers.data.LinkedItemScript;
import org.lwjgl.opengl.GL11;
public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListener, GuiYesNoCallback, ISubGuiListener {
@@ -119,8 +120,8 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
GuiNpcTextField digSpeedField = new GuiNpcTextField(12, this, x + 110, y, 50, 20, "" + linkedItem.digSpeed);
digSpeedField.setIntegersOnly().setMinMaxDefault(0, 20, 1);
addTextField(digSpeedField);
GuiNpcTextField attackSpeedField = new GuiNpcTextField(14, this, x +165, y, 50, 20, "" +linkedItem.attackSpeed);
attackSpeedField.setIntegersOnly().setMinMaxDefault(0,999999999,20);
GuiNpcTextField attackSpeedField = new GuiNpcTextField(14, this, x + 165, y, 50, 20, "" + linkedItem.attackSpeed);
attackSpeedField.setIntegersOnly().setMinMaxDefault(0, 999999999, 20);
addTextField(attackSpeedField);
y += spacing;
@@ -307,10 +308,7 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
return;
} else if (id == -3) {
PacketClient.sendClient(new LinkedItemSavePacket(linkedItem.writeToNBT(false), originalName));
GuiScriptLinkedItem scriptGUI = new GuiScriptLinkedItem((GuiNPCManageLinked) this.parent, linkedItem);
scriptGUI.setWorldAndResolution(mc, width, height);
scriptGUI.initGui();
mc.currentScreen = scriptGUI;
GuiScriptInterface.open(this.parent, new LinkedItemScript(linkedItem.id));
return;
} else if (id == 20) {
// Open confirmation for version bump.
@@ -39,6 +39,7 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 {
private GuiNpcSquareButton effectsButton;
private GuiNpcSquareButton magicsButton;
private GuiNpcSquareButton abilitiesButton;
private GuiNpcSquareButton auctionsButton;
public GuiNPCGlobalMainMenu(EntityNPCInterface npc) {
super(npc, 5);
@@ -96,7 +97,10 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 {
magicsButton.setIconPos(24, 24, 48, 56).setIconTexture(specialIcons);
registerButton(abilitiesButton = new GuiNpcSquareButton(21, 0, 0, 20, "global.abilities", 0xFF333333));
abilitiesButton.setIconPos(24, 24, 72, 56).setIconTexture(specialIcons); // Placeholder icon position
abilitiesButton.setIconPos(24, 24, 72, 56).setIconTexture(specialIcons);
registerButton(auctionsButton = new GuiNpcSquareButton(22, 0, 0, 20, "global.auction", 0xFF333333));
auctionsButton.setIconPos(24, 24, 96, 56).setIconTexture(specialIcons);
// Layout composite buttons optimally.
layoutButtons();
@@ -240,7 +244,10 @@ public class GuiNPCGlobalMainMenu extends GuiNPCInterface2 {
NoppesUtil.requestOpenGUI(EnumGuiType.ManageEffects);
}
if (id == 21) {
NoppesUtil.openGUI(player, new noppes.npcs.client.gui.global.GuiNpcManageAbilities(npc));
NoppesUtil.requestOpenGUI(EnumGuiType.ManageAbilities);
}
if (id == 22) {
// NoppesUtil.requestOpenGUI(EnumGuiType.ManageAuction);
}
}
@@ -9,11 +9,11 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.advanced.GuiNPCAbilities;
import noppes.npcs.client.gui.advanced.GuiNPCAdvancedLinkedNpc;
import noppes.npcs.client.gui.advanced.GuiNPCDialogNpcOptions;
import noppes.npcs.client.gui.advanced.GuiNPCFactionSetup;
import noppes.npcs.client.gui.advanced.GuiNPCLinesMenu;
import noppes.npcs.client.gui.advanced.GuiNPCAbilities;
import noppes.npcs.client.gui.advanced.GuiNPCMagic;
import noppes.npcs.client.gui.advanced.GuiNPCMarks;
import noppes.npcs.client.gui.advanced.GuiNPCNightSetup;
@@ -25,8 +25,8 @@ import noppes.npcs.client.gui.roles.GuiNpcConversation;
import noppes.npcs.client.gui.roles.GuiNpcFollowerJob;
import noppes.npcs.client.gui.roles.GuiNpcGuard;
import noppes.npcs.client.gui.roles.GuiNpcHealer;
import noppes.npcs.client.gui.roles.GuiNpcSpawner;
import noppes.npcs.client.gui.roles.GuiNpcMount;
import noppes.npcs.client.gui.roles.GuiNpcSpawner;
import noppes.npcs.client.gui.roles.GuiNpcTransporter;
import noppes.npcs.client.gui.util.GuiNPCInterface2;
import noppes.npcs.client.gui.util.GuiNpcButton;
@@ -50,7 +50,7 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData {
int y = guiTop + 10;
this.addButton(new GuiNpcButton(3, guiLeft + 85 + 160, y, 52, 20, "selectServer.edit"));
this.addButton(new GuiNpcButton(8, guiLeft + 85, y, 155, 20, new String[]{"role.none", "role.trader", "role.follower", "role.bank", "role.transporter", "role.mailman", NoppesStringUtils.translate("role.companion", "(WIP)"), "role.mount", "role.auctioneer"}, npc.advanced.role.ordinal()));
getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman);
getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman && npc.advanced.role != EnumRoleType.Auctioneer);
this.addButton(new GuiNpcButton(4, guiLeft + 85 + 160, y += 22, 52, 20, "selectServer.edit"));
this.addButton(new GuiNpcButton(5, guiLeft + 85, y, 155, 20, new String[]{"job.none", "job.bard", "job.healer", "job.guard", "job.itemgiver", "role.follower", "job.spawner", "job.conversation", "job.chunkloader"}, npc.advanced.job.ordinal()));
@@ -84,7 +84,7 @@ public class GuiNpcAdvanced extends GuiNPCInterface2 implements IGuiData {
hasChanges = true;
npc.advanced.setRole(button.getValue());
getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman);
getButton(3).setEnabled(npc.advanced.role != EnumRoleType.None && npc.advanced.role != EnumRoleType.Postman && npc.advanced.role != EnumRoleType.Auctioneer);
}
if (button.id == 4) {
save();
@@ -0,0 +1,281 @@
package noppes.npcs.client.gui.player;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.constants.EnumClaimType;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionListing;
import java.util.List;
/**
* Handles adding auction information to item tooltips when viewing auction GUIs.
* Called from MixinItem when Item.addInformation is invoked.
*/
@SideOnly(Side.CLIENT)
public class AuctionTooltipHandler {
/**
* Add auction information to an item's tooltip if we're in an auction GUI.
*/
public static void addAuctionInfo(ItemStack stack, List<String> tooltip) {
if (stack == null || tooltip == null) return;
Minecraft mc = Minecraft.getMinecraft();
if (mc == null || mc.currentScreen == null) return;
GuiScreen screen = mc.currentScreen;
// Check if we're in an auction listing GUI
if (screen instanceof GuiAuctionListing) {
addListingTooltip((GuiAuctionListing) screen, stack, tooltip);
}
// Check if we're in the trades GUI
else if (screen instanceof GuiAuctionTrades) {
addTradesTooltip((GuiAuctionTrades) screen, stack, tooltip);
}
// Check if we're in the sell GUI
else if (screen instanceof GuiAuctionSell) {
addSellTooltip((GuiAuctionSell) screen, stack, tooltip);
}
}
/**
* Add auction info when viewing the main listings page.
*/
private static void addListingTooltip(GuiAuctionListing gui, ItemStack stack, List<String> tooltip) {
ContainerAuctionListing container = (ContainerAuctionListing) gui.inventorySlots;
if (container == null) return;
// Find the listing that matches this ItemStack
AuctionListing listing = container.getListingForItem(stack);
if (listing == null) return;
tooltip.add("");
// Seller
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.seller")
.replace("%s", EnumChatFormatting.WHITE + listing.sellerName));
// Current bid or starting price
if (listing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), listing.bidCount));
} else {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.startingPrice")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(listing.startingPrice)));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
}
// Buyout price
if (listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.buyout")
.replace("%s", EnumChatFormatting.GREEN + formatCurrency(listing.buyoutPrice)));
}
// Time remaining
long timeRemaining = listing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
}
/**
* Add auction info when viewing the trades page.
*/
private static void addTradesTooltip(GuiAuctionTrades gui, ItemStack stack, List<String> tooltip) {
ContainerAuctionTrades container = (ContainerAuctionTrades) gui.inventorySlots;
if (container == null) return;
// Check if it's an item I'm selling
AuctionListing sellingListing = container.getSellingListingForItem(stack);
if (sellingListing != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.selling"));
if (sellingListing.hasBids()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(sellingListing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), sellingListing.bidCount));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.noBids"));
}
long timeRemaining = sellingListing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickToCancel"));
return;
}
// Check if it's an item I'm bidding on
AuctionListing biddingListing = container.getBiddingListingForItem(stack);
if (biddingListing != null) {
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.currentBid")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(biddingListing.currentBid)));
tooltip.add(EnumChatFormatting.GRAY + String.format(StatCollector.translateToLocal("auction.bids"), biddingListing.bidCount));
long timeRemaining = biddingListing.getTimeRemaining();
String timeText = StatCollector.translateToLocal("auction.timeLeft")
.replace("%s", formatTimeRemaining(timeRemaining));
tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText);
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.clickToRebid"));
return;
}
// Check if it's a claim
AuctionClaim claim = container.getClaimForItem(stack);
if (claim != null) {
tooltip.add("");
// Title based on claim type
switch (claim.type) {
case ITEM:
if (claim.isReturned) {
// Expired - returned to seller
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expired"));
} else {
// Won item
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.won"));
}
break;
case CURRENCY:
// Sold - money to claim
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.sold"));
if (claim.itemName != null && !claim.itemName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.soldItem")
.replace("%s", EnumChatFormatting.WHITE + claim.itemName));
}
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.buyer")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
break;
case REFUND:
// Outbid - refund available
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.outbid"));
if (claim.otherPlayerName != null && !claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.outbidBy")
.replace("%s", EnumChatFormatting.WHITE + claim.otherPlayerName));
}
break;
}
// Amount for currency claims (including REFUND)
if (claim.type.isCurrency()) {
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.claim.amount")
.replace("%s", EnumChatFormatting.GOLD + formatCurrency(claim.currency)));
}
// Expiration
int expirationDays = AuctionClientConfig.getClaimExpirationDays();
long daysLeft = claim.getDaysUntilExpiration(expirationDays);
if (daysLeft <= 1) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.claim.expiresSoon"));
} else {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.claim.expires")
.replace("%s", "" + daysLeft));
}
tooltip.add("");
// Show rebid option for REFUND claims with item (active auction)
if (claim.type == EnumClaimType.REFUND && claim.item != null) {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.leftClickRebid"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.rightClickRefund"));
} else {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.claim.clickToClaim"));
}
}
}
/**
* Add sell page tooltip info.
*/
private static void addSellTooltip(GuiAuctionSell gui, ItemStack stack, List<String> tooltip) {
ContainerAuctionSell container = (ContainerAuctionSell) gui.inventorySlots;
if (container == null) return;
// Check if this is the sell slot item
ItemStack sellItem = container.getItemToSell();
if (sellItem != null && ItemStack.areItemStacksEqual(stack, sellItem)) {
// This is the item in the sell slot
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.leftClear"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.rightRemove"));
return;
}
// This is an inventory item - show add controls
tooltip.add("");
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne"));
}
/**
* Format currency with commas.
*/
private static String formatCurrency(long amount) {
if (amount < 1000) {
return amount + " " + AuctionClientConfig.getCurrencyName();
}
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) {
sb.insert(0, ',');
}
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString() + " " + AuctionClientConfig.getCurrencyName();
}
/**
* Format time remaining.
*/
private static String formatTimeRemaining(long milliseconds) {
if (milliseconds <= 0) {
return StatCollector.translateToLocal("auction.ended");
}
long seconds = (milliseconds / 1000) % 60;
long minutes = (milliseconds / 60000) % 60;
long hours = (milliseconds / 3600000) % 24;
long days = milliseconds / 86400000;
StringBuilder sb = new StringBuilder();
if (days > 0) {
sb.append(days).append("d ");
}
if (hours > 0 || days > 0) {
sb.append(hours).append("h ");
}
if (minutes > 0 || hours > 0 || days > 0) {
sb.append(minutes).append("m");
} else {
sb.append(seconds).append("s");
}
return sb.toString();
}
}
@@ -237,7 +237,7 @@ public class GuiAnvilRecipes extends GuiNPCInterface {
fontRendererObj.drawString(percentText, percentTextX, percentTextY, CustomNpcResourceListener.DefaultTextColor);
// Add text overlay for percentage with the full unrounded value.
if (func_146978_c(percentTextX - guiLeft, percentTextY - guiTop, percentWidth, fontRendererObj.FONT_HEIGHT, mouseX, mouseY)) {
textOverlays.add(new TextOverlayData(percentTextX, percentTextY, percentWidth, fontRendererObj.FONT_HEIGHT, String.valueOf(recipe.getRepairPercentage())));
textOverlays.add(new TextOverlayData(percentTextX, percentTextY, percentWidth, fontRendererObj.FONT_HEIGHT, "" + recipe.getRepairPercentage()));
}
if (!recipe.availability.isDefault()) {
@@ -303,7 +303,7 @@ public class GuiAnvilRecipes extends GuiNPCInterface {
int xpBoxWidth = scaledTextWidth;
int xpBoxHeight = fontRendererObj.FONT_HEIGHT;
if (func_146978_c(xpTextX - guiLeft, xpTextY - guiTop, xpBoxWidth, xpBoxHeight, mouseX, mouseY)) {
textOverlays.add(new TextOverlayData(xpTextX, xpTextY, xpBoxWidth, xpBoxHeight, String.valueOf(recipe.getXpCost())));
textOverlays.add(new TextOverlayData(xpTextX, xpTextY, xpBoxWidth, xpBoxHeight, "" + recipe.getXpCost()));
}
}
@@ -326,7 +326,7 @@ public class GuiAnvilRecipes extends GuiNPCInterface {
private String formatXpCost(int xp) {
if (xp < 1000) {
return String.valueOf(xp);
return "" + xp;
}
double xpK = xp / 1000.0;
if (xpK == (int) xpK) {
@@ -0,0 +1,309 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.inventory.Slot;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.gui.util.GuiAuctionNavButton;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.containers.ContainerAuctionBidding;
import noppes.npcs.controllers.data.AuctionListing;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
/**
* GUI for viewing and bidding on a specific auction listing.
* Shows item, auction info, and bid/buyout buttons.
*/
public class GuiAuctionBidding extends GuiAuctionInterface implements ISubGuiListener, IGuiData {
// Icons
private static final ResourceLocation ICON_BID = new ResourceLocation("customnpcs", "textures/items/npcCoinDiamond.png");
private static final ResourceLocation ICON_BUYOUT = new ResourceLocation("customnpcs", "textures/items/npcCoinEmerald.png");
// Layout
private int itemSlotX = 70;
private int itemSlotY = 75;
private int btnBidX = 58;
private int btnBidY = 110;
private int btnBuyoutX = 82;
private int btnBuyoutY = 110;
private int infoX = 110;
private int infoY = 50;
// Button IDs
private int btnBidId = 200;
private int btnBuyoutId = 201;
private final ContainerAuctionBidding biddingContainer;
private AuctionListing listing;
private long playerBalance = 0;
private boolean dataLoaded = false;
private boolean isOwnListing = false;
// Buttons
private GuiAuctionNavButton btnBid;
private GuiAuctionNavButton btnBuyout;
public GuiAuctionBidding(EntityNPCInterface npc, ContainerAuctionBidding container) {
super(npc, container);
this.biddingContainer = container;
}
@Override
public void initGui() {
super.initGui();
// Bid button (diamond coin)
btnBid = new GuiAuctionNavButton(btnBidId, guiLeft + btnBidX, guiTop + btnBidY,
"auction.bid.place", ICON_BID);
addButton(btnBid);
// Buy Now button (emerald coin) - only visible if listing has buyout
btnBuyout = new GuiAuctionNavButton(btnBuyoutId, guiLeft + btnBuyoutX, guiTop + btnBuyoutY,
"auction.bid.buyout", ICON_BUYOUT);
addButton(btnBuyout);
updateButtonState();
}
@Override
protected int getCurrentPage() {
// Not a standard page - return -1 so nav buttons aren't selected
return -1;
}
/** Update button visibility based on listing state */
private void updateButtonState() {
if (listing == null) {
if (btnBid != null) btnBid.setVisible(false);
if (btnBuyout != null) btnBuyout.setVisible(false);
return;
}
// Hide buttons for own listings - can view but not bid/buy
if (isOwnListing) {
if (btnBid != null) btnBid.setVisible(false);
if (btnBuyout != null) btnBuyout.setVisible(false);
return;
}
// Bid button visible for other players' listings
if (btnBid != null) btnBid.setVisible(true);
// Buyout button only if listing has buyout
if (btnBuyout != null) {
btnBuyout.setVisible(listing.hasBuyout());
}
}
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
if (listing == null) return;
if (button.id == btnBidId) {
openBidSubGui();
} else if (button.id == btnBuyoutId) {
if (listing.hasBuyout()) {
openBuyNowSubGui();
}
}
}
private void openBidSubGui() {
if (listing == null) return;
long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement());
setSubGui(new SubGuiAuctionBid(listing.id, minBid, playerBalance));
}
private void openBuyNowSubGui() {
if (listing == null || !listing.hasBuyout()) return;
setSubGui(new SubGuiAuctionBuyNow(listing.id, listing.buyoutPrice, playerBalance));
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {
if (subgui instanceof SubGuiAuctionBid) {
SubGuiAuctionBid bidGui = (SubGuiAuctionBid) subgui;
if (bidGui.wasSuccessful()) {
// Bid placed - go to listings
AuctionActionPacket.openPage(PAGE_LISTINGS);
}
} else if (subgui instanceof SubGuiAuctionBuyNow) {
SubGuiAuctionBuyNow buyGui = (SubGuiAuctionBuyNow) subgui;
if (buyGui.wasSuccessful()) {
// Bought out - go to my trades
AuctionActionPacket.openPage(PAGE_CLAIMS);
}
}
}
// ========== Data Handling ==========
@Override
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("BiddingData")) {
playerBalance = compound.getLong("Balance");
isOwnListing = compound.getBoolean("IsOwnListing");
if (compound.hasKey("Listing")) {
listing = AuctionListing.fromNBT(compound.getCompoundTag("Listing"));
biddingContainer.setListing(listing);
}
dataLoaded = true;
updateButtonState();
}
}
// ========== Drawing ==========
@Override
protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) {
// Draw item slot background
drawAuctionSlot(guiLeft + itemSlotX, guiTop + itemSlotY);
if (!dataLoaded || listing == null) {
// Loading text
String loading = StatCollector.translateToLocal("gui.loading");
fontRendererObj.drawString(loading, guiLeft + infoX, guiTop + infoY, 0xFFFFFF);
return;
}
// Draw auction info on the right side
drawAuctionInfo();
}
/** Draw auction listing information on the right side */
private void drawAuctionInfo() {
int x = guiLeft + 105;
int y = guiTop + infoY;
int xRight = guiLeft + 215;
int lineHeight = 9;
// Seller
String sellerLabel = StatCollector.translateToLocal("auction.seller").replace("%s", "");
fontRendererObj.drawString(EnumChatFormatting.GRAY + sellerLabel, x, y, 0xFFFFFF);
String label = listing.sellerName;
int length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.WHITE + listing.sellerName, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
// Current Bid or Starting Price
if (listing.hasBids()) {
String bidLabel = StatCollector.translateToLocal("auction.info.currentBid") + ":";
fontRendererObj.drawString(EnumChatFormatting.YELLOW + bidLabel, x, y, 0xFFFFFF);
label = formatCurrency(listing.currentBid);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
// Current Bidder
String bidderLabel = StatCollector.translateToLocal("auction.info.highBidder");
fontRendererObj.drawString(EnumChatFormatting.GRAY + bidderLabel, x, y, 0xFFFFFF);
label = listing.highBidderName != null ? listing.highBidderName : "???";
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.WHITE + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
} else {
String startLabel = StatCollector.translateToLocal("auction.info.startingPrice");
fontRendererObj.drawString(EnumChatFormatting.YELLOW + startLabel, x, y, 0xFFFFFF);
label = formatCurrency(listing.startingPrice);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.GOLD + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
}
// Buyout Price (if available)
if (listing.hasBuyout()) {
String buyoutLabel = StatCollector.translateToLocal("auction.info.buyoutPrice");
fontRendererObj.drawString(EnumChatFormatting.GREEN + buyoutLabel, x, y, 0xFFFFFF);
label = formatCurrency(listing.buyoutPrice);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.GREEN + label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
}
// Time Remaining
String timeLabel = StatCollector.translateToLocal("auction.info.timeLeft");
fontRendererObj.drawString(EnumChatFormatting.GRAY + timeLabel, x, y, 0xFFFFFF);
long timeRemaining = listing.getTimeRemaining();
EnumChatFormatting timeColor = timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE;
label = timeColor + formatTimeRemaining(timeRemaining);
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(label, xRight - length, y, 0xFFFFFF);
y += lineHeight + 4;
// Bid Count
String bidCountLabel = StatCollector.translateToLocal("auction.info.bidCount");
fontRendererObj.drawString(EnumChatFormatting.GRAY + bidCountLabel, x, y, 0xFFFFFF);
label = "" + listing.bidCount;
length = fontRendererObj.getStringWidth(label);
fontRendererObj.drawString(EnumChatFormatting.WHITE + label, xRight - length, y, 0xFFFFFF);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
if (hasSubGui()) return;
// Draw button tooltips
drawBiddingPageTooltips(mouseX, mouseY);
}
private void drawBiddingPageTooltips(int mouseX, int mouseY) {
List<String> tooltip = null;
if (btnBid != null && btnBid.visible && btnBid.isHovered()) {
tooltip = new ArrayList<>();
tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.bid.place"));
if (listing != null) {
long minBid = listing.getMinimumBid(AuctionClientConfig.getMinBidIncrement());
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.bid.minimum")
.replace("%s", EnumChatFormatting.WHITE + formatCurrency(minBid) + " " + AuctionClientConfig.getCurrencyName()));
}
} else if (btnBuyout != null && btnBuyout.visible && btnBuyout.isHovered()) {
tooltip = new ArrayList<>();
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.bid.buyout"));
if (listing != null && listing.hasBuyout()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.info.buyoutPrice") + ":");
tooltip.add(EnumChatFormatting.GREEN + formatCurrency(listing.buyoutPrice) + " " + AuctionClientConfig.getCurrencyName());
}
}
if (tooltip != null && !tooltip.isEmpty()) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
}
// ========== Slot Handling ==========
@Override
protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) {
// Block all slot interactions - view only
}
public AuctionListing getListing() { return listing; }
}
@@ -0,0 +1,232 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.gui.util.GuiAuctionNavButton;
import noppes.npcs.client.gui.util.GuiContainerNPCInterface;
import noppes.npcs.containers.ContainerAuction;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.List;
/**
* Base GUI for all auction interfaces.
* 256x256 texture with player inventory at bottom.
*/
public abstract class GuiAuctionInterface extends GuiContainerNPCInterface {
// Textures
protected static final ResourceLocation AUCTION_BACKGROUND = new ResourceLocation("customnpcs", "textures/gui/auction/auction.png");
protected static final ResourceLocation AUCTION_SLOT = new ResourceLocation("customnpcs", "textures/gui/auction/auction_slot.png");
// Navigation icons
protected static final ResourceLocation ICON_LISTINGS = new ResourceLocation("customnpcs", "textures/items/npcAncientScroll.png");
protected static final ResourceLocation ICON_SELL = new ResourceLocation("customnpcs", "textures/gui/auction/sell.png");
protected static final ResourceLocation ICON_CLAIMS = new ResourceLocation("customnpcs", "textures/gui/auction/my_auctions.png");
protected static final ResourceLocation ICON_FILTER = new ResourceLocation("customnpcs", "textures/gui/auction/search.png");
// Page constants
public static final int PAGE_LISTINGS = 0;
public static final int PAGE_SELL = 1;
public static final int PAGE_CLAIMS = 2;
// Navigation button IDs
protected static final int BTN_NAV_LISTINGS = 100;
protected static final int BTN_NAV_SELL = 101;
protected static final int BTN_NAV_CLAIMS = 102;
protected static final int BTN_NAV_FILTER = 103;
// Navigation positions - non-final for testing/positioning
protected int navX = 35;
protected int navYListings = 46;
protected int navYSell = 67;
protected int navYClaims = 88;
protected final ContainerAuction auctionContainer;
protected GuiAuctionNavButton btnListings;
protected GuiAuctionNavButton btnSell;
protected GuiAuctionNavButton btnClaims;
public GuiAuctionInterface(EntityNPCInterface npc, ContainerAuction container) {
super(npc, container);
this.auctionContainer = container;
this.xSize = 256;
this.ySize = 256;
this.closeOnEsc = true;
this.title = "";
}
@Override
public void initGui() {
super.initGui();
initNavigationButtons();
}
/** Initialize navigation buttons */
protected void initNavigationButtons() {
int page = getCurrentPage();
btnListings = new GuiAuctionNavButton(BTN_NAV_LISTINGS, guiLeft + navX, guiTop + navYListings,
"auction.nav.listings", ICON_LISTINGS);
btnListings.setSelected(page == PAGE_LISTINGS);
addButton(btnListings);
btnSell = new GuiAuctionNavButton(BTN_NAV_SELL, guiLeft + navX, guiTop + navYSell,
"auction.nav.sell", ICON_SELL);
btnSell.setSelected(page == PAGE_SELL);
addButton(btnSell);
btnClaims = new GuiAuctionNavButton(BTN_NAV_CLAIMS, guiLeft + navX, guiTop + navYClaims,
"auction.nav.trades", ICON_CLAIMS);
btnClaims.setSelected(page == PAGE_CLAIMS);
addButton(btnClaims);
}
/** Returns current page constant - implement in subclass */
protected abstract int getCurrentPage();
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
int page = getCurrentPage();
if (button.id == BTN_NAV_LISTINGS && page != PAGE_LISTINGS) {
AuctionActionPacket.openPage(PAGE_LISTINGS);
} else if (button.id == BTN_NAV_SELL && page != PAGE_SELL) {
AuctionActionPacket.openPage(PAGE_SELL);
} else if (button.id == BTN_NAV_CLAIMS && page != PAGE_CLAIMS) {
AuctionActionPacket.openPage(PAGE_CLAIMS);
}
}
// ========== Background Drawing ==========
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
drawWorldBackground(0);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(AUCTION_BACKGROUND);
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
GL11.glEnable(GL11.GL_LIGHTING);
drawAuctionContent(partialTicks, mouseX, mouseY);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
if (!hasSubGui()) {
drawNavButtonTooltips(mouseX, mouseY);
}
}
/** Draw navigation button tooltips */
protected void drawNavButtonTooltips(int mouseX, int mouseY) {
List<String> tooltip = null;
if (btnListings != null && btnListings.isHovered()) tooltip = btnListings.getTooltipLines();
else if (btnSell != null && btnSell.isHovered()) tooltip = btnSell.getTooltipLines();
else if (btnClaims != null && btnClaims.isHovered()) tooltip = btnClaims.getTooltipLines();
if (tooltip != null) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
}
// ========== Slot Drawing Utilities ==========
/** Draw auction slot background (18x18) */
protected void drawAuctionSlot(int x, int y) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(AUCTION_SLOT);
Gui.func_146110_a(x, y, 0, 0, 18, 18, 18, 18);
}
/** Draw colored overlay on slot (ARGB format) */
protected void drawColoredOverlay(int x, int y, int color) {
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
Gui.drawRect(x + 1, y + 1, x + 17, y + 17, color);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_LIGHTING);
}
/** Draw dark overlay for unavailable slots */
protected void drawDarkenedOverlay(int x, int y) {
drawColoredOverlay(x, y, 0x80000000);
}
/** Draw icon texture on slot (16x16) */
protected void drawIconOverlay(int x, int y, ResourceLocation icon) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.renderEngine.bindTexture(icon);
Gui.func_146110_a(x + 1, y + 1, 0, 0, 16, 16, 16, 16);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
/** Subclasses implement this to draw specific content */
protected abstract void drawAuctionContent(float partialTicks, int mouseX, int mouseY);
// ========== Formatting Utilities ==========
/** Format currency with commas (e.g., 1000 -> "1,000") */
protected String formatCurrency(long amount) {
if (amount < 1000) return "" + amount;
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) sb.insert(0, ',');
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString();
}
/** Format time remaining (e.g., "2d 5h 30m") */
protected String formatTimeRemaining(long ms) {
if (ms <= 0) return "Ended";
long seconds = (ms / 1000) % 60;
long minutes = (ms / 60000) % 60;
long hours = (ms / 3600000) % 24;
long days = ms / 86400000;
StringBuilder sb = new StringBuilder();
if (days > 0) sb.append(days).append("d ");
if (hours > 0 || days > 0) sb.append(hours).append("h ");
if (minutes > 0 || hours > 0 || days > 0) sb.append(minutes).append("m");
else sb.append(seconds).append("s");
return sb.toString();
}
@Override
public void save() {
// Override in subclasses if needed
}
}
@@ -0,0 +1,302 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.inventory.Slot;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.GuiAuctionNavButton;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumAuctionSort;
import noppes.npcs.containers.ContainerAuctionListing;
import noppes.npcs.controllers.data.AuctionFilter;
import noppes.npcs.controllers.data.AuctionListing;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
/**
* GUI for browsing auction listings.
* Displays 9x5 grid with pagination and filter controls.
*/
public class GuiAuctionListing extends GuiAuctionInterface implements ISubGuiListener, IGuiData {
// Small button textures (10x10)
private static final ResourceLocation SMALL_BUTTON = new ResourceLocation("customnpcs", "textures/gui/auction/small_button.png");
private static final ResourceLocation SMALL_BUTTON_PRESS = new ResourceLocation("customnpcs", "textures/gui/auction/small_button_press.png");
// Arrow icons (8x8)
private static final ResourceLocation ICON_UP = new ResourceLocation("customnpcs", "textures/gui/auction/up.png");
private static final ResourceLocation ICON_DOWN = new ResourceLocation("customnpcs", "textures/gui/auction/down.png");
// Grid layout - non-final for testing/positioning
protected int gridX = 56;
protected int gridY = 46;
protected int cols = 9;
protected int rows = 5;
// Pagination positions (side by side horizontally)
protected int pageUpX = 33;
protected int pageDownX = 45;
protected int pageBtnY = 128;
// Filter button position
protected int navYFilter = 109;
// Button IDs
private static final int BTN_PAGE_UP = 200;
private static final int BTN_PAGE_DOWN = 201;
private final ContainerAuctionListing listingContainer;
private AuctionFilter filter;
private int currentPage = 0;
private int totalPages = 1;
private int totalListings = 0;
private boolean dataLoaded = false;
// Buttons defined on this page
private GuiAuctionNavButton btnFilter;
private GuiAuctionNavButton btnPageUp;
private GuiAuctionNavButton btnPageDown;
public GuiAuctionListing(EntityNPCInterface npc, ContainerAuctionListing container) {
super(npc, container);
this.listingContainer = container;
this.filter = new AuctionFilter();
}
@Override
public void initGui() {
super.initGui();
// Filter button (18x18 with 16x16 icon)
btnFilter = new GuiAuctionNavButton(BTN_NAV_FILTER, guiLeft + navX, guiTop + navYFilter,
"auction.nav.filter", ICON_FILTER);
addButton(btnFilter);
// Page Up button (10x10 with 8x8 icon)
btnPageUp = new GuiAuctionNavButton(BTN_PAGE_UP, guiLeft + pageUpX, guiTop + pageBtnY,
10, 8, "auction.page.prev", ICON_UP, SMALL_BUTTON, SMALL_BUTTON_PRESS);
addButton(btnPageUp);
// Page Down button (10x10 with 8x8 icon)
btnPageDown = new GuiAuctionNavButton(BTN_PAGE_DOWN, guiLeft + pageDownX, guiTop + pageBtnY,
10, 8, "auction.page.next", ICON_DOWN, SMALL_BUTTON, SMALL_BUTTON_PRESS);
addButton(btnPageDown);
updateFilterTooltip();
requestListings();
}
@Override
protected int getCurrentPage() {
return PAGE_LISTINGS;
}
/** Request listings from server */
private void requestListings() {
AuctionActionPacket.requestListings(filter, currentPage);
}
/** Update pagination button visibility based on current page state */
private void updatePaginationVisibility() {
if (btnPageUp != null) {
btnPageUp.setVisible(currentPage > 0);
}
if (btnPageDown != null) {
btnPageDown.setVisible(currentPage < totalPages - 1);
}
}
// ========== Filter Handling ==========
private void updateFilterTooltip() {
if (btnFilter == null) return;
List<String> tooltip = new ArrayList<>();
tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.nav.filter"));
tooltip.add("");
// Sort mode
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.filter.sort") + ":");
tooltip.add(EnumChatFormatting.WHITE + " " + filter.getSortBy().getDisplayName());
tooltip.add("");
// Search term
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.filter.search") + ":");
if (filter.hasSearchText()) {
tooltip.add(EnumChatFormatting.GREEN + " \"" + filter.getSearchText() + "\"");
} else {
tooltip.add(EnumChatFormatting.DARK_GRAY + " " + StatCollector.translateToLocal("auction.filter.none"));
}
tooltip.add("");
// Instructions
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.filter.leftClick"));
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.filter.rightClick"));
btnFilter.setCustomTooltip(tooltip);
}
@Override
public void mouseEvent(int mouseX, int mouseY, int mouseButton) {
if (btnFilter != null && btnFilter.isMouseOver(mouseX, mouseY) && mouseButton == 1) {
cycleSortMode();
}
}
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
switch (button.id) {
case BTN_NAV_FILTER:
setSubGui(new SubGuiAuctionSearch(filter.getSearchText()));
break;
case BTN_PAGE_UP:
if (currentPage > 0) {
currentPage--;
requestListings();
NoppesUtil.clickSound();
}
break;
case BTN_PAGE_DOWN:
if (currentPage < totalPages - 1) {
currentPage++;
requestListings();
NoppesUtil.clickSound();
}
break;
}
}
private void cycleSortMode() {
EnumAuctionSort[] values = EnumAuctionSort.values();
int next = (filter.getSortBy().ordinal() + 1) % values.length;
filter.setSortBy(values[next]);
updateFilterTooltip();
currentPage = 0;
requestListings();
NoppesUtil.clickSound();
}
public void onSearchSubmit(String searchText) {
filter.setSearchText(searchText);
updateFilterTooltip();
currentPage = 0;
requestListings();
}
@Override
public void subGuiClosed(SubGuiInterface subgui) {}
// ========== Data Handling ==========
@Override
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("ListingsData")) {
currentPage = compound.getInteger("Page");
totalPages = compound.getInteger("TotalPages");
totalListings = compound.getInteger("TotalListings");
// Load listings
listingContainer.displayInventory.clear();
NBTTagList list = compound.getTagList("Listings", 10);
for (int i = 0; i < list.tagCount() && i < 45; i++) {
AuctionListing listing = AuctionListing.fromNBT(list.getCompoundTagAt(i));
listingContainer.displayInventory.setListing(i, listing);
}
dataLoaded = true;
} else if (compound.hasKey("ListingsRefresh")) {
requestListings();
}
}
// ========== Drawing ==========
@Override
protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) {
// Draw slot backgrounds
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int x = guiLeft + gridX + col * 18;
int y = guiTop + gridY + row * 18;
drawAuctionSlot(x, y);
}
}
// Draw page indicator below pagination buttons
drawPageIndicator();
}
private void drawPageIndicator() {
if (totalPages > 1) {
String text = (currentPage + 1) + "/" + totalPages;
// Center between the two buttons (horizontally centered), below buttons
int centerX = guiLeft + pageUpX + 11;
int x = centerX - fontRendererObj.getStringWidth(text) / 2;
fontRendererObj.drawString(text, x, guiTop + pageBtnY + 12, 0xFFFFFF);
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
if (hasSubGui()) return;
// Draw tooltips for buttons on this page
drawListingPageTooltips(mouseX, mouseY);
}
private void drawListingPageTooltips(int mouseX, int mouseY) {
List<String> tooltip = null;
// Filter button tooltip
if (btnFilter != null && btnFilter.isHovered()) {
tooltip = btnFilter.getTooltipLines();
}
// Page up tooltip
else if (btnPageUp != null && btnPageUp.visible && btnPageUp.isHovered()) {
tooltip = btnPageUp.getTooltipLines();
}
// Page down tooltip
else if (btnPageDown != null && btnPageDown.visible && btnPageDown.isHovered()) {
tooltip = btnPageDown.getTooltipLines();
}
if (tooltip != null && !tooltip.isEmpty()) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
}
// ========== Slot Handling ==========
@Override
protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) {
// Check if clicking on a display slot with a listing
if (slot != null && listingContainer.isDisplaySlot(slot.slotNumber)) {
int listingIndex = slot.slotNumber - listingContainer.getDisplaySlotStart();
AuctionListing listing = listingContainer.displayInventory.getListing(listingIndex);
if (listing != null) {
// Open bidding page for this listing
AuctionActionPacket.openBidding(listing.id);
NoppesUtil.clickSound();
}
}
// Block other slot interactions
}
public AuctionFilter getFilter() { return filter; }
public ContainerAuctionListing getListingContainer() { return listingContainer; }
}
@@ -0,0 +1,332 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.GuiAuctionNavButton;
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.ITextfieldListener;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.containers.ContainerAuctionSell;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.List;
/**
* GUI for creating auction listings.
* Sell slot interactions: left-click=clear, right-click=remove 1.
* Inventory interactions: left-click=add stack, right-click=add 1.
*/
public class GuiAuctionSell extends GuiAuctionInterface implements ITextfieldListener {
private static final ResourceLocation ICON_COIN = new ResourceLocation("customnpcs", "textures/items/npcCoinBronze.png");
private static final ResourceLocation ICON_BAG = new ResourceLocation("customnpcs", "textures/items/npcBag.png");
// Layout
private int contentX = 58;
private int contentY = 50;
private int confirmBtnX = 200;
private int confirmBtnY = 118;
private int navYBuyout = 109;
// Component IDs
private int txtStartingPriceId = 1;
private int txtBuyoutPriceId = 2;
private int btnConfirmId = 10;
private int btnAllowBuyoutId = 11;
private final ContainerAuctionSell sellContainer;
private long startingPrice = 0;
private long buyoutPrice = 0;
private boolean allowBuyout = true;
private String errorMessage = null;
// Buttons
private GuiAuctionNavButton btnAllowBuyout;
private GuiNpcLabel lblBuyout;
private GuiNpcTextField txtBuyout;
public GuiAuctionSell(EntityNPCInterface npc, ContainerAuctionSell container) {
super(npc, container);
this.sellContainer = container;
}
@Override
public void initGui() {
super.initGui();
int y = guiTop + contentY;
// Starting Price label and field
addLabel(new GuiNpcLabel(1, "auction.sell.startingPrice", guiLeft + contentX, y + 5, 0xFFFFFF));
GuiNpcTextField startingField = new GuiNpcTextField(txtStartingPriceId, this, fontRendererObj,
guiLeft + contentX + 80, y, 80, 18, startingPrice > 0 ? "" + startingPrice : "");
startingField.setIntegersOnly();
addTextField(startingField);
y += 25;
// Buyout Price label and field (only visible when allowBuyout is true)
lblBuyout = new GuiNpcLabel(2, "auction.sell.buyoutPrice", guiLeft + contentX, y + 5, 0xFFFFFF);
addLabel(lblBuyout);
txtBuyout = new GuiNpcTextField(txtBuyoutPriceId, this, fontRendererObj,
guiLeft + contentX + 80, y, 80, 18, buyoutPrice > 0 ? "" + buyoutPrice : "");
txtBuyout.setIntegersOnly();
addTextField(txtBuyout);
// Allow Buyout toggle button (18x18 with bag icon)
btnAllowBuyout = new GuiAuctionNavButton(btnAllowBuyoutId, guiLeft + navX, guiTop + navYBuyout,
"auction.sell.allowBuyout", ICON_BAG);
btnAllowBuyout.setToggle(true); // This is a toggle, not a nav button
btnAllowBuyout.setSelected(allowBuyout);
addButton(btnAllowBuyout);
// Confirm button (custom textured button - using GuiAuctionNavButton)
GuiAuctionNavButton btnConfirm = new GuiAuctionNavButton(btnConfirmId, guiLeft + confirmBtnX - 20, guiTop + confirmBtnY - 10,
"auction.sell.confirm", ICON_COIN);
addButton(btnConfirm);
updateBuyoutVisibility();
updateBuyoutTooltip();
}
@Override
protected int getCurrentPage() {
return PAGE_SELL;
}
/** Update visibility of buyout price field based on toggle state */
private void updateBuyoutVisibility() {
if (lblBuyout != null) {
lblBuyout.enabled = allowBuyout;
}
if (txtBuyout != null) {
txtBuyout.setVisible(allowBuyout);
if (!allowBuyout) {
txtBuyout.setText("");
buyoutPrice = 0;
}
}
}
/** Update the buyout toggle button tooltip */
private void updateBuyoutTooltip() {
if (btnAllowBuyout == null) return;
List<String> tooltip = new ArrayList<>();
tooltip.add(EnumChatFormatting.GOLD + StatCollector.translateToLocal("auction.sell.allowBuyout"));
tooltip.add("");
if (allowBuyout) {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.sell.buyoutEnabled"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.buyoutEnabledDesc"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.buyoutEnabledDesc2"));
} else {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.sell.buyoutDisabled"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.buyoutDisabledDesc"));
}
tooltip.add("");
tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.clickToToggle"));
btnAllowBuyout.setCustomTooltip(tooltip);
}
@Override
public void unFocused(GuiNpcTextField textfield) {
if (textfield.id == txtStartingPriceId) {
try {
startingPrice = Long.parseLong(textfield.getText());
} catch (NumberFormatException e) {
startingPrice = 0;
}
} else if (textfield.id == txtBuyoutPriceId) {
try {
String text = textfield.getText().trim();
buyoutPrice = text.isEmpty() ? 0 : Long.parseLong(text);
} catch (NumberFormatException e) {
buyoutPrice = 0;
}
}
errorMessage = null;
}
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
if (button.id == btnConfirmId) {
createListing();
} else if (button.id == btnAllowBuyoutId) {
allowBuyout = !allowBuyout;
btnAllowBuyout.setSelected(allowBuyout);
updateBuyoutVisibility();
updateBuyoutTooltip();
NoppesUtil.clickSound();
}
}
private void createListing() {
// Get latest values from text fields
GuiNpcTextField startingField = getTextField(txtStartingPriceId);
GuiNpcTextField buyoutField = getTextField(txtBuyoutPriceId);
if (startingField != null) {
try {
startingPrice = Long.parseLong(startingField.getText());
} catch (NumberFormatException e) {
startingPrice = 0;
}
}
if (buyoutField != null && allowBuyout) {
try {
String text = buyoutField.getText().trim();
buyoutPrice = text.isEmpty() ? 0 : Long.parseLong(text);
} catch (NumberFormatException e) {
buyoutPrice = 0;
}
} else {
buyoutPrice = 0;
}
// Validate
ItemStack item = sellContainer.getItemToSell();
if (item == null) {
errorMessage = StatCollector.translateToLocal("auction.sell.noItem");
return;
}
if (startingPrice <= 0) {
errorMessage = StatCollector.translateToLocal("auction.sell.invalidPrice");
return;
}
if (allowBuyout && buyoutPrice > 0 && buyoutPrice < startingPrice) {
errorMessage = StatCollector.translateToLocal("auction.sell.buyoutTooLow");
return;
}
// Validate player has enough items
int inventoryCount = sellContainer.countItemInInventory(item);
if (item.stackSize > inventoryCount) {
errorMessage = StatCollector.translateToLocal("auction.sell.notEnoughItems");
return;
}
// Send create listing packet
AuctionActionPacket.createListing(item, startingPrice, allowBuyout ? buyoutPrice : 0);
// Clear the sell slot (server will also clear it)
sellContainer.clearSellSlot();
// Navigate back to listings page
AuctionActionPacket.openPage(PAGE_LISTINGS);
}
@Override
protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) {
// Draw sell slot background (centered in content area)
int slotX = guiLeft + contentX;
int slotY = guiTop + contentY + 50;
drawAuctionSlot(slotX, slotY);
// Draw listing fee info (uses cached config from server)
String feeText = StatCollector.translateToLocal("auction.sell.fee")
.replace("%s", formatCurrency(AuctionClientConfig.getListingFee()) + " " + AuctionClientConfig.getCurrencyName());
fontRendererObj.drawString(EnumChatFormatting.GRAY + feeText, guiLeft + contentX, guiTop + contentY + 77, 0xFFFFFF);
// Draw error message if any
if (errorMessage != null) {
fontRendererObj.drawString(EnumChatFormatting.RED + errorMessage, guiLeft + contentX, guiTop + contentY + 95, 0xFFFFFF);
}
drawSellSlotIndicator(slotX, slotY);
}
/** Draw indicator showing staged vs available items */
private void drawSellSlotIndicator(int slotX, int slotY) {
ItemStack sellItem = sellContainer.getItemToSell();
if (sellItem != null) {
int inventoryCount = sellContainer.countItemInInventory(sellItem);
String countText = sellItem.stackSize + "/" + inventoryCount;
// Color: green if valid, red if over limit
int color = sellItem.stackSize <= inventoryCount ? 0x55FF55 : 0xFF5555;
fontRendererObj.drawStringWithShadow(countText, slotX + 18 + 4, slotY + 5, color);
} else {
// Draw "Place item here" hint
String hint = StatCollector.translateToLocal("auction.sell.placeItem");
fontRendererObj.drawString(EnumChatFormatting.GRAY + hint, slotX + 20, slotY + 5, 0xFFFFFF);
}
}
/**
* Handle sell page click behavior.
* Sell slot: left=clear, right=remove 1.
* Inventory: left=add stack, right=add 1.
*/
@Override
protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) {
if (slot == null) return;
// Sell slot clicks
if (sellContainer.isSellSlot(slotIndex)) {
ItemStack sellItem = sellContainer.getItemToSell();
if (sellItem != null) {
boolean removeAll = (mouseButton == 0); // Left=clear, Right=remove 1
sellContainer.removeFromSellSlot(removeAll);
NoppesUtil.clickSound();
}
return;
}
// Inventory clicks
if (sellContainer.isPlayerInventorySlot(slotIndex)) {
ItemStack sourceStack = slot.getStack();
if (sourceStack != null) {
boolean fullStack = (mouseButton == 0); // Left=stack, Right=1 item
sellContainer.addToSellSlot(slotIndex, fullStack);
NoppesUtil.clickSound();
}
return;
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
if (hasSubGui()) return;
// Draw tooltips for buttons (icons, not items - item tooltips handled by AuctionTooltipHandler)
drawSellPageTooltips(mouseX, mouseY);
}
/** Draw tooltips for sell page buttons */
private void drawSellPageTooltips(int mouseX, int mouseY) {
List<String> tooltip = null;
// Check all buttons
GuiNpcButton confirmBtn = getButton(btnConfirmId);
if (confirmBtn instanceof GuiAuctionNavButton) {
GuiAuctionNavButton btn = (GuiAuctionNavButton) confirmBtn;
if (btn.isHovered()) {
tooltip = btn.getTooltipLines();
}
}
if (btnAllowBuyout != null && btnAllowBuyout.isHovered()) {
tooltip = btnAllowBuyout.getTooltipLines();
}
if (tooltip != null && !tooltip.isEmpty()) {
drawHoveringText(tooltip, mouseX - guiLeft, mouseY - guiTop, fontRendererObj);
}
}
}
@@ -0,0 +1,388 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.inventory.Slot;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.constants.EnumClaimType;
import noppes.npcs.containers.ContainerAuctionTrades;
import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionListing;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
/**
* GUI for viewing player's auction trades.
* Shows active listings, bids, and claims with confirmation system.
*/
public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData {
// Icon textures
private static final ResourceLocation ICON_X = new ResourceLocation("customnpcs", "textures/gui/auction/x_icon.png");
private static final ResourceLocation ICON_CHECK = new ResourceLocation("customnpcs", "textures/gui/auction/check_icon.png");
private static final ResourceLocation ICON_COIN = new ResourceLocation("customnpcs", "textures/items/npcCoinGold.png");
// Grid layout
private static final int GRID_X = 56;
private static final int GRID_Y = 46;
private static final int COLS = 9;
private static final int ROWS = 5;
private static final int TOTAL_SLOTS = COLS * ROWS;
// Slot tint colors (ARGB)
private static final int TINT_BLUE = 0x303060FF; // Active listing/bid (selling)
private static final int TINT_GREEN = 0x3030FF30; // Sold (currency claim) or Won (item claim)
private static final int TINT_YELLOW = 0x30FFFF30; // Outbid (refund claim)
private static final int TINT_RED = 0x30FF3030; // Expired/Returned (item returned to seller)
private final ContainerAuctionTrades tradesContainer;
private int maxTradeSlots;
// Pending operation state
private int pendingSlot = -1;
private PendingOp pendingOp = PendingOp.NONE;
private enum PendingOp { NONE, CANCEL, CLAIM }
public GuiAuctionTrades(EntityNPCInterface npc, ContainerAuctionTrades container) {
super(npc, container);
this.tradesContainer = container;
// Initial value from client config, updated when server sends trades data
this.maxTradeSlots = AuctionClientConfig.getMaxActiveListings();
}
@Override
protected int getCurrentPage() {
return PAGE_CLAIMS;
}
// ========== Mouse Handling ==========
@Override
public void mouseEvent(int mouseX, int mouseY, int mouseButton) {
if (hasSubGui()) return;
int slot = getSlotAt(mouseX, mouseY);
if (slot < 0 || slot >= TOTAL_SLOTS) {
clearPending();
return;
}
// Clicking on pending slot - confirm or cancel
if (slot == pendingSlot && pendingOp != PendingOp.NONE) {
handlePendingClick(mouseButton);
return;
}
// Clear existing pending, start new operation
clearPending();
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();
} else if (listing != null && tradesContainer.isBiddingAt(slot) && mouseButton == 0) {
// Left-click on active bid = open bidding GUI to increase bid
AuctionActionPacket.openBidding(listing.id);
NoppesUtil.clickSound();
} else if (claim != null) {
// Handle claim clicks
if (claim.type == EnumClaimType.REFUND && claim.item != null) {
// REFUND with item = can rebid
if (mouseButton == 0) {
// Left-click = open bidding to rebid
AuctionActionPacket.openBidding(claim.listingId);
NoppesUtil.clickSound();
} else if (mouseButton == 1) {
// Right-click = show refund claim confirmation
setPending(slot, PendingOp.CLAIM);
NoppesUtil.clickSound();
}
} else if (mouseButton == 0) {
// Normal claim - left-click shows claim confirmation
setPending(slot, PendingOp.CLAIM);
NoppesUtil.clickSound();
}
}
}
/** Handle click on pending operation slot */
private void handlePendingClick(int mouseButton) {
if (pendingOp == PendingOp.CANCEL && mouseButton == 1) {
// Right-click confirms cancel
AuctionListing listing = tradesContainer.getListingAt(pendingSlot);
if (listing != null) {
AuctionActionPacket.cancelListing(listing.id);
playConfirmSound();
}
clearPending();
} else if (pendingOp == PendingOp.CLAIM) {
AuctionClaim claim = tradesContainer.getClaimAt(pendingSlot);
if (claim != null) {
// For REFUND claims with item (rebid option), right-click confirms refund
// For all others, left-click confirms claim
boolean shouldClaim = (claim.type == EnumClaimType.REFUND && claim.item != null)
? mouseButton == 1 // Right-click for rebiddable refunds
: mouseButton == 0; // Left-click for normal claims
if (shouldClaim) {
if (claim.type.isItem()) {
AuctionActionPacket.claimItem(claim.id);
} else {
AuctionActionPacket.claimCurrency(claim.id);
}
playConfirmSound();
clearPending();
} else {
// Wrong button - cancel operation
clearPending();
NoppesUtil.clickSound();
}
} else {
clearPending();
}
} else {
// Wrong button - cancel operation
clearPending();
NoppesUtil.clickSound();
}
}
/** Set pending operation and hide slot item */
private void setPending(int slot, PendingOp op) {
pendingSlot = slot;
pendingOp = op;
tradesContainer.setHiddenSlot(slot);
}
/** Clear pending operation and restore slot */
private void clearPending() {
if (pendingSlot >= 0) {
tradesContainer.clearHiddenSlot();
}
pendingSlot = -1;
pendingOp = PendingOp.NONE;
}
/** Play confirmation sound */
private void playConfirmSound() {
mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(
new ResourceLocation("random.orb"), 1.0F));
}
/** Get slot index at mouse position */
private int getSlotAt(int mouseX, int mouseY) {
int relX = mouseX - guiLeft - GRID_X;
int relY = mouseY - guiTop - GRID_Y;
if (relX < 0 || relY < 0) return -1;
int col = relX / 18;
int row = relY / 18;
if (col >= COLS || row >= ROWS) return -1;
return col + row * COLS;
}
// ========== Drawing ==========
@Override
protected void drawAuctionContent(float partialTicks, int mouseX, int mouseY) {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
int slot = col + row * COLS;
int x = guiLeft + GRID_X + col * 18;
int y = guiTop + GRID_Y + row * 18;
drawAuctionSlot(x, y);
// Color tint based on slot contents
int tint = getSlotTint(slot);
if (tint != 0 && slot != pendingSlot) {
drawColoredOverlay(x, y, tint);
}
// Darken unavailable slots
if (slot >= maxTradeSlots) {
drawDarkenedOverlay(x, y);
}
// Pending operation icon or currency claim coin
if (slot == pendingSlot) {
if (pendingOp == PendingOp.CANCEL) {
drawIconOverlay(x, y, ICON_X);
} else if (pendingOp == PendingOp.CLAIM) {
drawIconOverlay(x, y, ICON_CHECK);
}
} else {
// Draw coin icon for currency claims or refund claims without item
AuctionClaim claim = tradesContainer.getClaimAt(slot);
if (claim != null) {
// Show coin if: CURRENCY claim OR REFUND claim without item
if (claim.type == EnumClaimType.CURRENCY ||
(claim.type == EnumClaimType.REFUND && claim.item == null)) {
drawIconOverlay(x, y, ICON_COIN);
}
}
}
}
}
}
/** Get tint color for slot based on contents */
private int getSlotTint(int slot) {
AuctionListing listing = tradesContainer.getListingAt(slot);
AuctionClaim claim = tradesContainer.getClaimAt(slot);
if (listing != null) {
if (tradesContainer.isSellingAt(slot)) {
// Selling - Blue
return TINT_BLUE;
} else {
// Bidding - Yellow
return TINT_YELLOW;
}
} else if (claim != null) {
switch (claim.type) {
case CURRENCY:
// Sold item - Green
return TINT_GREEN;
case REFUND:
// Outbid - Red (whether rebiddable or not)
return TINT_RED;
case ITEM:
// Won item (green) or Returned/Expired (red)
return claim.isReturned ? TINT_RED : TINT_GREEN;
default:
return TINT_GREEN;
}
}
return 0;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
if (hasSubGui()) return;
int slot = getSlotAt(mouseX, mouseY);
if (slot >= 0 && slot < TOTAL_SLOTS) {
drawTradeTooltip(slot, mouseX - guiLeft, mouseY - guiTop);
}
}
/** Draw tooltip for a trade slot */
private void drawTradeTooltip(int slot, int x, int y) {
List<String> tooltip = new ArrayList<>();
if (slot == pendingSlot) {
// Pending operation tooltip
if (pendingOp == PendingOp.CANCEL) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.confirmCancel"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.rightClickConfirm"));
tooltip.add(EnumChatFormatting.DARK_GRAY + StatCollector.translateToLocal("auction.trades.otherClickCancel"));
} else if (pendingOp == PendingOp.CLAIM) {
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.confirmClaim"));
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.leftClickConfirm"));
tooltip.add(EnumChatFormatting.DARK_GRAY + StatCollector.translateToLocal("auction.trades.otherClickCancel"));
}
} else {
// Normal slot tooltip
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) {
switch (claim.type) {
case CURRENCY:
tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.soldClaim"));
if (!claim.itemName.isEmpty()) {
tooltip.add(EnumChatFormatting.WHITE + claim.itemName);
}
if (!claim.otherPlayerName.isEmpty()) {
tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.trades.buyer") + ": " + EnumChatFormatting.AQUA + claim.otherPlayerName);
}
tooltip.add(EnumChatFormatting.GOLD + String.format("%,d", claim.currency) + " " + AuctionClientConfig.getCurrencyName());
break;
case REFUND:
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.outbid"));
if (!claim.otherPlayerName.isEmpty()) {
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"));
} else if (slot >= maxTradeSlots) {
tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.unavailable"));
}
}
if (!tooltip.isEmpty()) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
drawHoveringText(tooltip, x, y, fontRendererObj);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
}
// ========== Slot Handling ==========
@Override
protected void handleMouseClick(Slot slot, int slotIndex, int mouseButton, int clickType) {
// Block all slot interactions
}
// ========== Server Updates ==========
@Override
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("TradesData")) {
// Full trades data received from server
tradesContainer.setTradesData(compound);
// Update max trade slots from server (permission-aware)
this.maxTradeSlots = tradesContainer.getMaxTradeSlots();
clearPending();
} else if (compound.hasKey("TradesUpdate")) {
// Legacy flag - should not happen now but keep for safety
tradesContainer.refreshData();
}
}
public ContainerAuctionTrades getTradesContainer() {
return tradesContainer;
}
}
@@ -172,7 +172,7 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData {
// Draw stock count to the RIGHT of the trade (after output slot)
if (stockEnabled && availableStock[slotIdx] < Integer.MAX_VALUE) {
String stockText = String.valueOf(availableStock[slotIdx]);
String stockText = "" + availableStock[slotIdx];
int stockColor = availableStock[slotIdx] > 0 ? 0x00AA00 : 0xAA0000;
fontRendererObj.drawString(stockText, x + OUTPUT_OFFSET + 20, y + 5, stockColor);
}
@@ -317,10 +317,10 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData {
*/
private String formatCurrency(long amount) {
if (amount < 1000) {
return String.valueOf(amount);
return "" + amount;
}
StringBuilder sb = new StringBuilder();
String str = String.valueOf(amount);
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) {
@@ -0,0 +1,160 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.AuctionClientConfig;
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.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Sub GUI for placing a bid on an auction.
* Shows minimum bid, player balance, and input field.
*/
public class SubGuiAuctionBid extends SubGuiInterface implements ITextfieldListener {
private int txtBidId = 1;
private int btnBidId = 10;
private int btnCancelId = 11;
private final String listingId;
private final long minimumBid;
private final long playerBalance;
private long bidAmount;
private boolean successful = false;
private String errorMessage = null;
public SubGuiAuctionBid(String listingId, long minimumBid, long playerBalance) {
this.listingId = listingId;
this.minimumBid = minimumBid;
this.playerBalance = playerBalance;
this.bidAmount = minimumBid;
setBackground("menubg.png");
xSize = 200;
ySize = 120;
closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
int centerX = guiLeft + xSize / 2;
int y = guiTop + 15;
String currencyName = AuctionClientConfig.getCurrencyName();
// Minimum bid info
String minText = StatCollector.translateToLocal("auction.bid.minimum")
.replace("%s", EnumChatFormatting.DARK_RED + formatCurrency(minimumBid) + " " + currencyName);
addLabel(new GuiNpcLabel(1, minText, guiLeft + 15, y));
y += 14;
// Your balance
String balanceText = StatCollector.translateToLocal("auction.bid.yourBalance")
.replace("%s", EnumChatFormatting.DARK_GREEN + formatCurrency(playerBalance) + " " + currencyName);
addLabel(new GuiNpcLabel(2, balanceText, guiLeft + 15, y));
y += 18;
// Bid amount field
addLabel(new GuiNpcLabel(3, "auction.bid.yourBid", guiLeft + 15, y + 4));
GuiNpcTextField bidField = new GuiNpcTextField(txtBidId, this, fontRendererObj,
guiLeft + 80, y, 100, 18, "" + minimumBid);
bidField.setIntegersOnly();
addTextField(bidField);
y += 28;
// Error message area (empty initially)
addLabel(new GuiNpcLabel(4, "", guiLeft + 15, y, 0xFF5555));
y += 16;
// Buttons
int btnWidth = 70;
int btnSpacing = 20;
int totalBtnWidth = btnWidth * 2 + btnSpacing;
int btnX = centerX - totalBtnWidth / 2;
addButton(new GuiNpcButton(btnBidId, btnX, y, btnWidth, 20, "auction.bid.placeBid"));
addButton(new GuiNpcButton(btnCancelId, btnX + btnWidth + btnSpacing, y, btnWidth, 20, "gui.cancel"));
}
@Override
public void unFocused(GuiNpcTextField textfield) {
if (textfield.id == txtBidId) {
try {
bidAmount = Long.parseLong(textfield.getText());
} catch (NumberFormatException e) {
bidAmount = 0;
}
errorMessage = null;
updateErrorLabel();
}
}
@Override
public void buttonEvent(GuiButton button) {
if (button.id == btnBidId) {
placeBid();
} else if (button.id == btnCancelId) {
close();
}
}
private void placeBid() {
// Get latest value from text field
GuiNpcTextField bidField = getTextField(txtBidId);
if (bidField != null) {
try {
bidAmount = Long.parseLong(bidField.getText());
} catch (NumberFormatException e) {
bidAmount = 0;
}
}
// Validate
if (bidAmount < minimumBid) {
errorMessage = StatCollector.translateToLocal("auction.error.bidTooLow")
.replace("%s", formatCurrency(minimumBid));
updateErrorLabel();
return;
}
if (bidAmount > playerBalance) {
errorMessage = StatCollector.translateToLocal("auction.error.notEnoughCurrency");
updateErrorLabel();
return;
}
// Send bid packet
AuctionActionPacket.placeBid(listingId, bidAmount);
successful = true;
close();
}
private void updateErrorLabel() {
GuiNpcLabel errorLabel = getLabel(4);
if (errorLabel != null) {
errorLabel.label = errorMessage != null ? EnumChatFormatting.RED + errorMessage : "";
}
}
public boolean wasSuccessful() {
return successful;
}
private String formatCurrency(long amount) {
if (amount < 1000) return "" + amount;
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) sb.insert(0, ',');
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString();
}
}
@@ -0,0 +1,121 @@
package noppes.npcs.client.gui.player;
import kamkeel.npcs.network.packets.player.AuctionActionPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.AuctionClientConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Sub GUI for confirming a buyout purchase.
* Shows buyout price, player balance, and confirmation buttons.
*/
public class SubGuiAuctionBuyNow extends SubGuiInterface {
private int btnConfirmId = 10;
private int btnCancelId = 11;
private final String listingId;
private final long buyoutPrice;
private final long playerBalance;
private boolean successful = false;
public SubGuiAuctionBuyNow(String listingId, long buyoutPrice, long playerBalance) {
this.listingId = listingId;
this.buyoutPrice = buyoutPrice;
this.playerBalance = playerBalance;
setBackground("menubg.png");
xSize = 220;
ySize = 130;
closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
int centerX = guiLeft + xSize / 2;
int y = guiTop + 15;
String currencyName = AuctionClientConfig.getCurrencyName();
// Title
String title = StatCollector.translateToLocal("auction.buyout.title");
int titleWidth = fontRendererObj.getStringWidth(title);
addLabel(new GuiNpcLabel(0, title, centerX - titleWidth / 2, y));
y += 20;
// Confirmation message
String confirmMsg = StatCollector.translateToLocal("auction.buyout.confirm");
int confirmWidth = fontRendererObj.getStringWidth(confirmMsg);
addLabel(new GuiNpcLabel(1, confirmMsg, centerX - confirmWidth / 2, y));
y += 16;
// Buyout price
String priceText = EnumChatFormatting.DARK_RED + formatCurrency(buyoutPrice) + " " + currencyName;
int priceWidth = fontRendererObj.getStringWidth(priceText);
addLabel(new GuiNpcLabel(2, priceText, centerX - priceWidth / 2, y));
y += 20;
// Your balance
String balanceLabel = StatCollector.translateToLocal("auction.bid.yourBalance");
String balanceText = balanceLabel.replace("%s", EnumChatFormatting.DARK_GREEN + formatCurrency(playerBalance) + " " + currencyName);
addLabel(new GuiNpcLabel(3, balanceText, guiLeft + 20, y));
y += 14;
// Insufficient funds warning
if (playerBalance < buyoutPrice) {
String warning = StatCollector.translateToLocal("auction.error.notEnoughCurrency");
addLabel(new GuiNpcLabel(4, EnumChatFormatting.RED + warning, guiLeft + 20, y, 0xFFFFFF));
}
y += 20;
// Buttons
int btnWidth = 70;
int btnSpacing = 20;
int totalBtnWidth = btnWidth * 2 + btnSpacing;
int btnX = centerX - totalBtnWidth / 2;
GuiNpcButton confirmBtn = new GuiNpcButton(btnConfirmId, btnX, y, btnWidth, 20, "gui.yes");
confirmBtn.enabled = playerBalance >= buyoutPrice;
addButton(confirmBtn);
addButton(new GuiNpcButton(btnCancelId, btnX + btnWidth + btnSpacing, y, btnWidth, 20, "gui.cancel"));
}
@Override
public void buttonEvent(GuiButton button) {
if (button.id == btnConfirmId) {
if (playerBalance >= buyoutPrice) {
confirmPurchase();
}
} else if (button.id == btnCancelId) {
close();
}
}
private void confirmPurchase() {
// Send buyout packet
AuctionActionPacket.buyout(listingId);
successful = true;
close();
}
public boolean wasSuccessful() {
return successful;
}
private String formatCurrency(long amount) {
if (amount < 1000) return "" + amount;
StringBuilder sb = new StringBuilder();
String str = "" + amount;
int count = 0;
for (int i = str.length() - 1; i >= 0; i--) {
if (count > 0 && count % 3 == 0) sb.insert(0, ',');
sb.insert(0, str.charAt(i));
count++;
}
return sb.toString();
}
}
@@ -0,0 +1,85 @@
package noppes.npcs.client.gui.player;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* Small SubGui for entering auction search text.
*/
public class SubGuiAuctionSearch extends SubGuiInterface implements ITextfieldListener {
private static final int TXT_SEARCH = 0;
private static final int BTN_SUBMIT = 1;
private static final int BTN_CLEAR = 2;
private static final int BTN_CLOSE = 3;
private String searchText;
public SubGuiAuctionSearch(String currentSearchText) {
this.searchText = currentSearchText != null ? currentSearchText : "";
setBackground("menubg.png");
xSize = 180;
ySize = 80;
closeOnEsc = true;
}
@Override
public void initGui() {
super.initGui();
// Close button
addButton(new GuiNpcButton(BTN_CLOSE, guiLeft + xSize - 22, guiTop + 4, 18, 18, "X"));
// Search label
addLabel(new GuiNpcLabel(0, "auction.filter.search", guiLeft + 10, guiTop + 10, 0xFFFFFF));
// Search text field
addTextField(new GuiNpcTextField(TXT_SEARCH, this, fontRendererObj, guiLeft + 10, guiTop + 25, 160, 18, searchText));
// Submit and Clear buttons
addButton(new GuiNpcButton(BTN_SUBMIT, guiLeft + 10, guiTop + 50, 70, 20, "gui.apply"));
addButton(new GuiNpcButton(BTN_CLEAR, guiLeft + 85, guiTop + 50, 70, 20, "gui.clear"));
}
@Override
public void unFocused(GuiNpcTextField textfield) {
if (textfield.id == TXT_SEARCH) {
searchText = textfield.getText();
}
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == BTN_SUBMIT) {
GuiNpcTextField field = getTextField(TXT_SEARCH);
if (field != null) {
searchText = field.getText();
}
// Notify parent and close
if (parent instanceof GuiAuctionListing) {
((GuiAuctionListing) parent).onSearchSubmit(searchText);
}
close();
} else if (guibutton.id == BTN_CLEAR) {
searchText = "";
GuiNpcTextField field = getTextField(TXT_SEARCH);
if (field != null) {
field.setText("");
}
// Notify parent and close
if (parent instanceof GuiAuctionListing) {
((GuiAuctionListing) parent).onSearchSubmit("");
}
close();
} else if (guibutton.id == BTN_CLOSE) {
close();
}
}
public String getSearchText() {
return searchText;
}
}
@@ -180,7 +180,7 @@ public class GuiProfiles extends GuiCNPCInventory implements ISubGuiListener, IC
if (slot.isTemporary()) {
label = StatCollector.translateToLocal("profile.temporary");
result = (String.valueOf(slot.isTemporary())).toUpperCase();
result = ("" + slot.isTemporary()).toUpperCase();
labelColor = 0xfc60dd;
resultColor = 0x35fc81;
fontRendererObj.drawString(label, xLabel, y, labelColor, false);
@@ -56,7 +56,7 @@ public class GuiNpcTraderSetup extends GuiContainerNPCInterface2 implements ITex
int x = guiLeft + i % 3 * 130 + 15; // First position after "$" label
int y = guiTop + i / 3 * 22 + 14;
long cost = role.getCurrencyCost(i);
GuiNpcTextField field = new GuiNpcTextField(CURRENCY_FIELD_ID_START + i, this, x, y, 36, 16, cost > 0 ? String.valueOf(cost) : "");
GuiNpcTextField field = new GuiNpcTextField(CURRENCY_FIELD_ID_START + i, this, x, y, 36, 16, cost > 0 ? "" + cost : "");
field.setMaxStringLength(8);
field.setIntegersOnly();
addTextField(field);
@@ -95,7 +95,7 @@ public class SubGuiNpcTraderStock extends SubGuiInterface implements ISubGuiList
return "-1"; // Mixed values, return unlimited
}
}
return String.valueOf(first);
return "" + first;
}
@Override
@@ -47,7 +47,7 @@ public class SubGuiNpcTraderStockSlots extends SubGuiInterface implements ITextf
// Max stock textfield
int maxStock = role.stock.maxStock[i];
String value = maxStock < 0 ? "-1" : String.valueOf(maxStock);
String value = maxStock < 0 ? "-1" : "" + maxStock;
GuiNpcTextField field = new GuiNpcTextField(i, this, fontRendererObj, x + 42, y, 32, 18, value);
field.setIntegersOnly();
field.setMinMaxDefault(-1, Integer.MAX_VALUE, -1);
@@ -5,7 +5,7 @@ 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.SubGuiInterface;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.data.IScriptUnit;
import java.util.ArrayList;
import java.util.Iterator;
@@ -14,10 +14,10 @@ import java.util.List;
public class EventGuiScriptList extends SubGuiInterface {
private GuiCustomScroll scroll1;
private GuiCustomScroll scroll2;
private ScriptContainer container;
private IScriptUnit container;
private List<String> scripts;
public EventGuiScriptList(List<String> scripts, ScriptContainer container) {
public EventGuiScriptList(List<String> scripts, IScriptUnit container) {
this.container = container;
this.setBackground("menubg.png");
this.xSize = 346;
@@ -50,9 +50,9 @@ public class EventGuiScriptList extends SubGuiInterface {
this.addScroll(this.scroll2);
this.addLabel(new GuiNpcLabel(2, "script.loadedScripts", this.guiLeft + 200, this.guiTop + 4));
ArrayList temp = new ArrayList(this.scripts);
temp.removeAll(this.container.scripts);
temp.removeAll(getScripts());
this.scroll1.setList(temp);
this.scroll2.setList(this.container.scripts);
this.scroll2.setList(getScripts());
this.addButton(new GuiNpcButton(1, this.guiLeft + 145, this.guiTop + 40, 55, 20, ">"));
this.addButton(new GuiNpcButton(2, this.guiLeft + 145, this.guiTop + 62, 55, 20, "<"));
this.addButton(new GuiNpcButton(3, this.guiLeft + 145, this.guiTop + 90, 55, 20, ">>"));
@@ -63,25 +63,25 @@ public class EventGuiScriptList extends SubGuiInterface {
protected void actionPerformed(GuiButton guibutton) {
GuiNpcButton button = (GuiNpcButton) guibutton;
if (button.id == 1 && this.scroll1.hasSelected()) {
this.container.scripts.add(this.scroll1.getSelected());
getScripts().add(this.scroll1.getSelected());
this.scroll1.selected = -1;
this.scroll2.selected = -1;
this.initGui();
}
if (button.id == 2 && this.scroll2.hasSelected()) {
this.container.scripts.remove(this.scroll2.getSelected());
getScripts().remove(this.scroll2.getSelected());
this.scroll2.selected = -1;
this.initGui();
}
if (button.id == 3) {
this.container.scripts.clear();
getScripts().clear();
Iterator var3 = this.scripts.iterator();
while (var3.hasNext()) {
String script = (String) var3.next();
this.container.scripts.add(script);
getScripts().add(script);
}
this.scroll1.selected = -1;
@@ -90,7 +90,7 @@ public class EventGuiScriptList extends SubGuiInterface {
}
if (button.id == 4) {
this.container.scripts.clear();
getScripts().clear();
this.scroll1.selected = -1;
this.scroll2.selected = -1;
this.initGui();
@@ -102,6 +102,10 @@ public class EventGuiScriptList extends SubGuiInterface {
}
public List<String> getScripts() {
return this.container.getExternalScripts();
}
public void save() {
}
}
@@ -0,0 +1,429 @@
package noppes.npcs.client.gui.script;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.janino.JaninoScript;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback, ITextChangeListener, ICustomScrollListener, ISubGuiListener {
private GuiScriptTextArea textArea;
private int activeTab = 0;
public List<String> allExternalScripts = new ArrayList<>();
private final int scriptLimit = 1;
public String previousHookClicked = "";
// GUI display list
List<String> hooklist = new ArrayList<>();
// Map from display name (with parameters if overloaded) to Method
Map<String, Method> hookMap = new HashMap<>();
public final GuiScreen parent;
private final JaninoScript container;
public Runnable saveFunction;
public GuiJaninoScript(GuiScreen parent, JaninoScript handler) {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.setBackground("menubg.png");
this.parent = parent;
this.container = handler;
createHookList();
String lang = handler.getLanguage();
allExternalScripts.addAll(ScriptController.Instance.getScripts(lang));
}
public GuiJaninoScript setSave(Runnable run) {
saveFunction = run;
return this;
}
public void createHookList() {
// Group all declared methods of the handler's type by their method name
Map<String, List<Method>> grouped = Arrays.stream(container.type.getDeclaredMethods())
.collect(Collectors.groupingBy(Method::getName));
for (Map.Entry<String, List<Method>> entry : grouped.entrySet()) {
List<Method> methods = entry.getValue();
// Sort overloads by number of parameters (ascending)
// This ensures the simplest overload comes first
methods.sort(Comparator.comparingInt(Method::getParameterCount));
boolean first = true;
for (Method m : methods) {
if (Modifier.isFinal(m.getModifiers()))
continue; //skip finals
String displayName = first ? m.getName() :
m.getName() + "(" + Arrays.stream(m.getParameterTypes())
.map(Class::getSimpleName)
.collect(Collectors.joining(", ")) + ")";
hooklist.add(displayName);
hookMap.put(displayName, m);
first = false;
}
}
}
public void initGui() {
this.ySize = (int) ((double) this.xSize * 0.56);
if ((double) this.ySize > (double) this.height * 0.95) {
this.ySize = (int) ((double) this.height * 0.95);
this.xSize = (int) ((double) this.ySize / 0.56);
}
this.bgScale = (float) this.xSize / 400.0F;
super.initGui();
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02);
GuiMenuTopButton top;
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 2, guiTop - 17, "X"));
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
if (this.container != null) {
this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script"));
} else {
this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
}
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
}
top.active = true;
if (this.activeTab == 1) {
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.allowUserInput = false;
hooks.setSize(108, 198);
hooks.guiLeft = this.guiLeft - 110;
hooks.guiTop = this.guiTop + 14;
hooks.setUnsortedList(this.hooklist);
this.addScroll(hooks);
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5);
hookLabel.color = 11184810;
this.addLabel(hookLabel);
JaninoScript container = this.container;
if (textArea == null)
textArea = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
else
textArea.init(this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
textArea.enableCodeHighlighting();
textArea.setListener(this);
this.closeOnEsc(textArea::closeOnEsc);
this.addTextField(textArea);
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
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"));
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
// this.getButton(107).enabled = false;
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2);
scroll.guiLeft = left1;
scroll.guiTop = this.guiTop + 88 + yoffset;
if (container != null)
scroll.setList(container.externalScripts);
this.addScroll(scroll);
} else {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.enabled = false;
this.addTextField(var8);
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));
String containerLang = container.getLanguage();
this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, new String[]{containerLang.equals("Java") ? "Janino (JVM 8)" : containerLang},
this.getLanguageIndex()));
// this.getButton(103).enabled = !this.languages.isEmpty();
this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36));
// Note: GuiJaninoScript is deprecated; enabled button disabled
this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20, new String[]{"gui.no", "gui.yes"}, 0));
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
}
this.xSize = 420;
this.ySize = 256;
}
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
String hook = scroll.getSelected();
if (this.previousHookClicked.equals(hook)) {
String addString = "";
if (!this.getTextField(2)
.getText()
.isEmpty()) {
addString = addString + "\n";
}
addString = addString + generateMethodStub(hookMap.get(hook));
this.getTextField(2)
.setText(this.getTextField(2)
.getText() + addString);
this.previousHookClicked = "";
} else {
this.previousHookClicked = hook;
}
}
public void confirmClicked(boolean flag, int i) {
if (flag) {
if (i == 0)
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
else if (i == 1)
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
else if (i == 2)
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
else if (i == 3)
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
if (i == 10) { //Remove
this.container.setScript("");
this.activeTab = 0;
} else if (i == 101) { //Paste
this.getTextField(2)
.setText(NoppesStringUtils.getClipboardContents());
this.setScript();
} else if (i == 102) { //Clear
if (this.activeTab == 1)
container.script = "";
else
this.container.clearConsole();
this.initGui();
}
}
this.displayGuiScreen(this);
}
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == -1) {
close();
return;
}
if (guibutton.id == 0) {
this.setScript();
this.activeTab = 0;
this.initGui();
container.ensureCompiled();
}
if (guibutton.id == this.scriptLimit) {
// if (container.container == null)
//this.container.container = new ScriptContainer(this.container);
// else
// this.setScript();
this.activeTab = 1;
this.initGui();
}
if (guibutton.id == 109) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
} else if (guibutton.id == 110) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
} else if (guibutton.id == 111) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
} else if (guibutton.id == 112) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
}
GuiYesNo confirmScreen;
//Copy
if (guibutton.id == 100) {
NoppesStringUtils.setClipboardContents(this.getTextField(2)
.getText());
}
//Paste
else if (guibutton.id == 101) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
this.displayGuiScreen(guiyesno);
}
//Clear
else if (guibutton.id == 102) {
confirmScreen = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
this.displayGuiScreen(confirmScreen);
}
//Enable
else if (guibutton.id == 104) {
// Deprecated GUI - enabled is now per-handler, not per-unit
}
//Remove
else if (guibutton.id == 105) {
confirmScreen = new GuiYesNo(this, "", guibutton.displayString, 10);
this.displayGuiScreen(confirmScreen);
}
//Load Script
else if (guibutton.id == 107) {
setSubGui(new SubGuiSelectList(allExternalScripts, container.externalScripts, "All Scripts", "Selected Scripts"));
}
}
public void subGuiClosed(SubGuiInterface sub) {
if (sub instanceof SubGuiSelectList)
container.setExternalScripts(((SubGuiSelectList) sub).selected);
}
/**
* Generates a stub string for a given Method.
*/
public static String generateMethodStub(Method method) {
String mods = java.lang.reflect.Modifier.toString(method.getModifiers());
if (!mods.isEmpty())
mods += " ";
String returnTypeStr = method.getReturnType()
.getSimpleName();
String name = method.getName();
Map<String, Integer> typeCount = new HashMap<>();
String params = Arrays.stream(method.getParameters())
.map(p -> {
String typeName = p.getType()
.getSimpleName();
String baseName = Character.toLowerCase(typeName.charAt(0)) + typeName.substring(1);
int count = typeCount.getOrDefault(baseName, 0) + 1;
typeCount.put(baseName, count);
// append number if same type of arg exists
String paramName = count == 1 ? baseName : baseName + (count - 1);
return typeName + " " + paramName;
})
.collect(Collectors.joining(", "));
String body;
Class<?> returnType = method.getReturnType();
if (returnType == void.class)
body = "";
else if (returnType.isPrimitive()) {
if (returnType == boolean.class)
body = " return false;";
else if (returnType == char.class)
body = " return '\\0';";
else
body = " return 0;";
} else {
body = " return null;";
}
return String.format("%s%s %s(%s) {\n%s\n}\n", mods, returnTypeStr, name, params, body);
}
private String getConsoleText() {
Map<Long, String> map = this.container.getConsole();
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet()
.iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date(entry.getKey()) + entry.getValue() + "\n");
}
return builder.toString();
}
private int getLanguageIndex() {
return 0;
}
private void setScript() {
if (this.activeTab == 1) {
String text = this.getTextField(2)
.getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.setScript(text);
}
}
public void save() {
if (saveFunction != null)
saveFunction.run();
else if (parent instanceof GuiNPCInterface)
((GuiNPCInterface) parent).save();
}
public void textUpdate(String text) {
// container.setScript(text);
}
public static GuiJaninoScript create(GuiScreen parent, JaninoScript script, int width, int height) {
GuiJaninoScript gui = new GuiJaninoScript(parent, script);
gui.setWorldAndResolution(Minecraft.getMinecraft(), width, height);
Minecraft.getMinecraft().currentScreen = gui;
gui.initGui();
return gui;
}
@Override
public void close() {
this.save();
this.setScript();
container.ensureCompiled();
parent.setWorldAndResolution(mc, width, height);
parent.initGui();
mc.currentScreen = parent;
}
}
@@ -1,64 +1,13 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.EventScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NBTTags;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.DataScript;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.ArrayList;
import java.util.List;
public class GuiNPCEventScripts extends GuiScriptInterface {
private final DataScript script;
public GuiNPCEventScripts(EntityNPCInterface npc) {
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_NPC));
this.script = new DataScript(npc);
this.handler = this.script;
EventScriptPacket.Get();
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
script.setLanguage(compound.getString("ScriptLanguage"));
script.setEnabled(compound.getBoolean("ScriptEnabled"));
super.setGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(script);
container.readFromNBT(compound.getCompoundTag("Script"));
if (script.getScripts().isEmpty()) {
for (int i = 0; i < compound.getInteger("TotalScripts"); i++) {
script.getScripts().add(new ScriptContainer(script));
}
}
script.getScripts().set(tab, container);
initGui();
}
}
public void save() {
if (loaded) {
super.save();
List<ScriptContainer> containers = this.script.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
EventScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.script.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.script.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText()));
EventScriptPacket.Save(-1, containers.size(), scriptData);
}
this.handler = new DataScript(npc);
if (this.handler instanceof IScriptHandlerPacket)
((IScriptHandlerPacket) this.handler).requestData();
}
}
@@ -1,62 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.GlobalNPCScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NBTTags;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.GlobalNPCDataScript;
import java.util.ArrayList;
import java.util.List;
public class GuiScriptAllNPCs extends GuiScriptInterface {
private final GlobalNPCDataScript script = new GlobalNPCDataScript(null);
public GuiScriptAllNPCs() {
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_NPC));
this.handler = this.script;
GlobalNPCScriptPacket.Get();
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
script.setLanguage(compound.getString("ScriptLanguage"));
script.setEnabled(compound.getBoolean("ScriptEnabled"));
super.setGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(script);
container.readFromNBT(compound.getCompoundTag("Script"));
if (script.getScripts().isEmpty()) {
for (int i = 0; i < compound.getInteger("TotalScripts"); i++) {
script.getScripts().add(new ScriptContainer(script));
}
}
script.getScripts().set(tab, container);
initGui();
}
}
public void save() {
if (loaded) {
super.save();
List<ScriptContainer> containers = this.script.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
GlobalNPCScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.script.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.script.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText()));
GlobalNPCScriptPacket.Save(-1, containers.size(), scriptData);
}
}
}
@@ -1,34 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.BlockScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.blocks.tiles.TileScripted;
import noppes.npcs.controllers.ScriptHookController;
import java.util.ArrayList;
public class GuiScriptBlock extends GuiScriptInterface {
private final TileScripted tileScripted;
public GuiScriptBlock(int x, int y, int z) {
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_BLOCK));
this.handler = this.tileScripted = (TileScripted) player.worldObj.getTileEntity(x, y, z);
BlockScriptPacket.Get(tileScripted.xCoord, tileScripted.yCoord, tileScripted.zCoord);
}
public void setGuiData(NBTTagCompound compound) {
this.tileScripted.setNBT(compound);
super.setGuiData(compound);
loaded = true;
}
public void save() {
if (loaded) {
super.save();
BlockScriptPacket.Save(tileScripted.xCoord, tileScripted.yCoord, tileScripted.zCoord, this.tileScripted.getNBT(new NBTTagCompound()));
}
}
}
@@ -1,415 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.EffectScriptPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.StatCollector;
import noppes.npcs.NBTTags;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.EffectScript;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GuiScriptEffect extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener {
private int activeTab = 0;
public Map<String, List<String>> languages = new HashMap();
private final int scriptLimit = 1;
public List<String> hookList = new ArrayList();
public String previousHookClicked = "";
public final GuiNPCManageEffects parent;
public final CustomEffect effect;
private final EffectScript scriptHandler;
boolean loaded = false;
public GuiScriptEffect(GuiNPCManageEffects parent, CustomEffect effect) {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.setBackground("menubg.png");
this.parent = parent;
this.effect = effect;
this.scriptHandler = new EffectScript();
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_EFFECT));
EffectScriptPacket.Get(effect.id);
}
public void initGui() {
this.ySize = (int) ((double) this.xSize * 0.56);
if ((double) this.ySize > (double) this.height * 0.95) {
this.ySize = (int) ((double) this.height * 0.95);
this.xSize = (int) ((double) this.ySize / 0.56);
}
this.bgScale = (float) this.xSize / 400.0F;
super.initGui();
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02);
GuiMenuTopButton top;
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
if (this.scriptHandler.container != null) {
this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script"));
} else {
this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
}
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
}
top.active = true;
if (this.activeTab == 1) {
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.allowUserInput = false;
hooks.setSize(108, 198);
hooks.guiLeft = this.guiLeft - 110;
hooks.guiTop = this.guiTop + 14;
hooks.setUnsortedList(this.hookList);
this.addScroll(hooks);
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5);
hookLabel.color = 11184810;
this.addLabel(hookLabel);
ScriptContainer container = this.scriptHandler.container;
GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
ta.enableCodeHighlighting();
ta.setListener(this);
this.addTextField(ta);
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
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"));
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
this.getButton(107).enabled = false;
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2);
scroll.guiLeft = left1;
scroll.guiTop = this.guiTop + 88 + yoffset;
if (container != null) {
scroll.setList(container.scripts);
}
this.addScroll(scroll);
} else {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.enabled = false;
this.addTextField(var8);
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.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex()));
this.getButton(103).enabled = !this.languages.isEmpty();
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.scriptHandler.getEnabled() ? 1 : 0));
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
}
this.xSize = 420;
this.ySize = 256;
}
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
String hook = scroll.getSelected();
if (this.previousHookClicked.equals(hook)) {
String addString = "";
if (!this.getTextField(2).getText().isEmpty()) {
addString = addString + "\n";
}
addString = addString + "function " + hook + "(event) {\n \n}\n";
this.getTextField(2).setText(this.getTextField(2).getText() + addString);
this.previousHookClicked = "";
} else {
this.previousHookClicked = hook;
}
}
public void unFocused(GuiNpcTextField textfield) {
}
private String getConsoleText() {
Map<Long, String> map = this.scriptHandler.getConsoleText();
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet().iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n");
}
return builder.toString();
}
private int getScriptIndex() {
int i = 0;
for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) {
String language = (String) var2.next();
if (language.equalsIgnoreCase(this.scriptHandler.getLanguage())) {
return i;
}
}
return 0;
}
public void confirmClicked(boolean flag, int i) {
if (flag) {
if (i == 0) {
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
}
if (i == 1) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 2) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 3) {
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
}
if (i == 10) {
this.scriptHandler.container = null;
this.activeTab = 0;
}
if (i == 101) {
this.getTextField(2).setText(NoppesStringUtils.getClipboardContents());
this.setScript();
}
if (i == 102) {
if (this.activeTab == 1) {
ScriptContainer container = this.scriptHandler.container;
container.script = "";
} else {
this.scriptHandler.clearConsole();
}
this.initGui();
}
}
this.displayGuiScreen(this);
}
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
this.setScript();
this.activeTab = 0;
this.initGui();
}
if (guibutton.id == this.scriptLimit) {
if (scriptHandler.container == null)
this.scriptHandler.container = new ScriptContainer(this.scriptHandler);
else
this.setScript();
this.activeTab = 1;
this.initGui();
}
if (guibutton.id == 109) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
}
if (guibutton.id == 110) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
}
if (guibutton.id == 111) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
}
if (guibutton.id == 112) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
}
if (guibutton.id == 100) {
NoppesStringUtils.setClipboardContents(this.getTextField(2).getText());
}
if (guibutton.id == 101) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
this.displayGuiScreen(guiyesno);
}
GuiYesNo container1;
if (guibutton.id == 102) {
container1 = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
this.displayGuiScreen(container1);
}
if (guibutton.id == 103) {
this.scriptHandler.setLanguage(guibutton.displayString);
}
if (guibutton.id == 104) {
this.scriptHandler.setEnabled(((GuiNpcButton) guibutton).getValue() == 1);
}
if (guibutton.id == 105) {
container1 = new GuiYesNo(this, "", ((GuiNpcButton) guibutton).displayString, 10);
this.displayGuiScreen(container1);
}
if (guibutton.id == 107) {
ScriptContainer container = this.scriptHandler.container;
if (container == null) {
container = new ScriptContainer(this.scriptHandler);
this.scriptHandler.container = container;
}
// this.setSubGui(new EventGuiScriptList((List)this.languages.get(this.script.getLanguage()), container));
}
}
private void setScript() {
if (this.activeTab == 1) {
ScriptContainer container = this.scriptHandler.container;
if (container == null) {
container = new ScriptContainer(this.scriptHandler);
this.scriptHandler.container = container;
}
String text = this.getTextField(2).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.script = text;
}
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
this.scriptHandler.setLanguage(compound.getString("ScriptLanguage"));
this.scriptHandler.setEnabled(compound.getBoolean("ScriptEnabled"));
this.copiedSetGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(this.scriptHandler);
container.readFromNBT(compound.getCompoundTag("Script"));
this.scriptHandler.container = container;
this.initGui();
}
}
private void copiedSetGuiData(NBTTagCompound compound) {
NBTTagList data = compound.getTagList("Languages", 10);
HashMap languages = new HashMap();
for (int i = 0; i < data.tagCount(); ++i) {
NBTTagCompound comp = data.getCompoundTagAt(i);
ArrayList scripts = new ArrayList();
NBTTagList list = comp.getTagList("Scripts", 8);
for (int j = 0; j < list.tagCount(); ++j) {
scripts.add(list.getStringTagAt(j));
}
languages.put(comp.getString("Language"), scripts);
}
this.languages = languages;
this.initGui();
}
public void save() {
if (loaded) {
this.setScript();
List<ScriptContainer> containers = this.scriptHandler.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
EffectScriptPacket.Save(effect.id, i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.scriptHandler.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.scriptHandler.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.scriptHandler.getConsoleText()));
EffectScriptPacket.Save(effect.id, -1, containers.size(), scriptData);
}
}
public void textUpdate(String text) {
ScriptContainer container = this.scriptHandler.container;
if (container != null) {
container.script = text;
}
}
public void saveText(String text) {
ScriptContainer container = this.scriptHandler.container;
if (container != null) {
container.script = text;
}
this.initGui();
}
@Override
public void close() {
this.save();
parent.setWorldAndResolution(mc, width, height);
parent.initGui();
mc.currentScreen = parent;
}
}
@@ -1,117 +0,0 @@
package noppes.npcs.client.gui.script;
import com.google.common.reflect.ClassPath;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent;
import kamkeel.npcs.network.packets.request.script.ForgeScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.event.world.ChunkDataEvent;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.event.world.ChunkWatchEvent;
import net.minecraftforge.event.world.WorldEvent;
import noppes.npcs.NBTTags;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.ForgeDataScript;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class GuiScriptForge extends GuiScriptInterface {
private final ForgeDataScript script = new ForgeDataScript();
public GuiScriptForge() {
// Add built-in "init" hook from controller
hookList.addAll(ScriptHookController.Instance.getBuiltInHooks(IScriptHookHandler.CONTEXT_FORGE));
// Dynamically discover Forge event hooks
ArrayList<ClassPath.ClassInfo> list = new ArrayList();
try {
list.addAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("cpw.mods.fml.common.gameevent"));
list.addAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("net.minecraftforge.event"));
list.removeAll(ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive("net.minecraftforge.event.terraingen"));
} catch (IOException e) {
e.printStackTrace();
}
for (ClassPath.ClassInfo e1 : list) {
ClassPath.ClassInfo classLoader = e1;
Class infoClass = classLoader.load();
ArrayList c = new ArrayList(Arrays.asList(infoClass.getDeclaredClasses()));
if (c.isEmpty()) {
c.add(infoClass);
}
Iterator var10 = c.iterator();
while (var10.hasNext()) {
Class c1 = (Class) var10.next();
if (!EntityEvent.EntityConstructing.class.isAssignableFrom(c1) && !WorldEvent.PotentialSpawns.class.isAssignableFrom(c1) && !TickEvent.RenderTickEvent.class.isAssignableFrom(c1) && !TickEvent.ClientTickEvent.class.isAssignableFrom(c1) && !FMLNetworkEvent.ClientCustomPacketEvent.class.isAssignableFrom(c1) && !ItemTooltipEvent.class.isAssignableFrom(c1) && Event.class.isAssignableFrom(c1) && !Modifier.isAbstract(c1.getModifiers()) && Modifier.isPublic(c1.getModifiers()) && !ChunkEvent.class.isAssignableFrom(c1) && !ChunkWatchEvent.class.isAssignableFrom(c1) && !ChunkDataEvent.class.isAssignableFrom(c1)) {
String eventName = c1.getName();
int i = eventName.lastIndexOf(".");
eventName = StringUtils.uncapitalize(eventName.substring(i + 1).replace("$", ""));
hookList.add(eventName);
}
}
}
hookList.add("onCNPCNaturalSpawn");
// Add any addon-registered hooks for the forge context
for (String addonHook : ScriptHookController.Instance.getAddonHooks(IScriptHookHandler.CONTEXT_FORGE)) {
if (!hookList.contains(addonHook)) {
hookList.add(addonHook);
}
}
this.handler = this.script;
ForgeScriptPacket.Get();
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
script.setLanguage(compound.getString("ScriptLanguage"));
script.setEnabled(compound.getBoolean("ScriptEnabled"));
super.setGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(script);
container.readFromNBT(compound.getCompoundTag("Script"));
if (script.getScripts().isEmpty()) {
for (int i = 0; i < compound.getInteger("TotalScripts"); i++) {
script.getScripts().add(new ScriptContainer(script));
}
}
script.getScripts().set(tab, container);
initGui();
}
}
public void save() {
if (loaded) {
super.save();
List<ScriptContainer> containers = this.script.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
ForgeScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.script.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.script.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText()));
ForgeScriptPacket.Save(-1, containers.size(), scriptData);
}
}
}
@@ -8,6 +8,9 @@ import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.controllers.data.ForgeDataScript;
import noppes.npcs.controllers.data.GlobalNPCDataScript;
import noppes.npcs.controllers.data.PlayerDataScript;
import org.lwjgl.opengl.GL11;
import java.util.HashMap;
@@ -65,13 +68,13 @@ public class GuiScriptGlobal extends GuiNPCInterface implements IGuiData {
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
this.displayGuiScreen(new GuiScriptPlayers());
GuiScriptInterface.open(this, new PlayerDataScript(null));
}
if (guibutton.id == 1) {
this.displayGuiScreen(new GuiScriptForge());
GuiScriptInterface.open(this, new ForgeDataScript());
}
if (guibutton.id == 2) {
this.displayGuiScreen(new GuiScriptAllNPCs());
GuiScriptInterface.open(this, new GlobalNPCDataScript(null));
}
if (guibutton.id > 2) {
try {
@@ -1,7 +1,9 @@
package noppes.npcs.client.gui.script;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
@@ -17,16 +19,21 @@ import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.GuiUtil;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.ForgeDataScript;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.scripted.item.ScriptCustomItem;
import org.lwjgl.opengl.Display;
import java.util.ArrayList;
import java.util.Date;
@@ -40,10 +47,59 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
protected int activeTab = 0;
public IScriptHandler handler;
public Map<String, List<String>> languages = new HashMap();
private int scriptLimit = 1;
protected int scriptLimit = 1;
public List<String> hookList = new ArrayList<String>();
protected boolean loaded = false;
protected Map<Integer, GuiScriptTextArea> textAreas = new HashMap<>();
protected GuiScreen parent;
/**
* If true, uses scroll-based tab selection instead of top buttons
*/
protected boolean useScrollTabs = false;
/**
* If true, shows settings/script toggle instead of numbered tabs
*/
protected boolean useSettingsToggle = false;
// ==================== FULLSCREEN MODE ====================
/**
* Whether the editor viewport is currently in fullscreen mode
*/
public static boolean isFullscreen = false;
/**
* Fullscreen Layout Configuration
* Adjust these values to customize the fullscreen viewport appearance.
* All padding values are in scaled GUI pixels.
*/
public static class FullscreenConfig {
/**
* Padding from the top edge of the screen
*/
public static int paddingTop = 20;
/**
* Padding from the bottom edge of the screen
*/
public static int paddingBottom = 20;
/**
* Padding from the left edge of the screen
*/
public static int paddingLeft = 20;
/**
* Padding from the right edge of the screen
*/
public static int paddingRight = 20;
}
/**
* Fullscreen toggle button drawn at top-right of viewport
*/
public final FullscreenButton fullscreenButton = new FullscreenButton();
public GuiScriptInterface() {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
@@ -51,8 +107,37 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.setBackground("menubg.png");
}
/**
* Create a GuiScriptInterface for a handler without displaying it.
* Useful when a caller needs to return a GuiScreen (e.g. ClientProxy).
*/
public static GuiScriptInterface create(GuiScreen parent, IScriptHandler handler) {
GuiScriptInterface gui = new GuiScriptInterface();
gui.handler = handler;
gui.parent = parent;
// Initialize hooks from handler
gui.hookList = new ArrayList<>(handler.getHooks());
// Request data from server
if (handler instanceof IScriptHandlerPacket)
((IScriptHandlerPacket) handler).requestData();
return gui;
}
/**
* Open a GuiScriptInterface for a handler.
* Wraps the script in a SingleScriptHandler automatically.
*/
public static GuiScriptInterface open(GuiScreen parent, IScriptHandler handler) {
GuiScriptInterface gui = create(parent, handler);
Minecraft.getMinecraft().displayGuiScreen(gui);
return gui;
}
public void initGui() {
//this.xSize = (int)((double)this.width * 0.88D);
// ==================== BASE LAYOUT CALCULATION ====================
this.ySize = (int) ((double) this.xSize * 0.56D);
if ((double) this.ySize > (double) this.height * 0.95D) {
this.ySize = (int) ((double) this.height * 0.95D);
@@ -63,33 +148,96 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
super.initGui();
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02D);
GuiMenuTopButton top;
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
for (int ta = 0; ta < this.handler.getScripts().size(); ++ta) {
if (ta % 20 == 0 && ta > 0) {
topYoffset -= 20;
topXoffset -= top.width + 20 * 22;
if (hookList.isEmpty())
hookList = new ArrayList<>(handler.getHooks());
// ==================== TAB BUTTONS ====================
// Skip standard tab creation for GUIs that use custom toggle/scroll tabs
if (!useSettingsToggle) {
GuiMenuTopButton top;
int topButtonsX = isFullscreen && activeTab != 0 ? FullscreenConfig.paddingLeft : this.guiLeft + 4;
int topButtonsY = isFullscreen && activeTab != 0 ? FullscreenConfig.paddingTop - 20 : this.guiTop - 17;
this.addTopButton(top = new GuiMenuTopButton(0, topButtonsX, topButtonsY, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
boolean isSingle = handler.isSingleContainer();
if (!isSingle) {
for (int ta = 0; ta < this.handler.getScripts().size(); ++ta) {
if (ta % 20 == 0 && ta > 0) {
topYoffset -= 20;
topXoffset -= top.width + 20 * 22;
}
this.addTopButton(top = new GuiMenuTopButton(ta + 1, top.xPosition + top.width + topXoffset,
top.yPosition + topYoffset, ta + 1 + ""));
topXoffset = 0;
topYoffset = 0;
scriptLimit = ta + 2;
}
}
this.addTopButton(top = new GuiMenuTopButton(ta + 1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, ta + 1 + ""));
topXoffset = 0;
topYoffset = 0;
scriptLimit = ta + 2;
if (isSingle && handler.getSingleScript() != null)
this.addTopButton(
top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset,
"Script"));
else if (this.handler.getScripts().size() < 100)
this.addTopButton(new GuiMenuTopButton(scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
}
top.active = true;
}
if (this.handler.getScripts().size() < 100)
this.addTopButton(new GuiMenuTopButton(scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
// ==================== SCRIPT EDITOR TAB (activeTab > 0) ====================
// Skip for GUIs that handle their own view initialization (useSettingsToggle)
if (!useSettingsToggle) {
if (this.activeTab > 0) {
initScriptEditorTab(yoffset);
} else {
// ==================== SETTINGS TAB (activeTab == 0) ====================
initSettingsTab(yoffset);
}
}
top.active = true;
if (this.activeTab > 0) {
this.xSize = 420;
this.ySize = 256;
}
/**
* Initialize the script editor tab layout.
* Handles both normal and fullscreen modes.
*/
private void initScriptEditorTab(int yoffset) {
IScriptUnit container = getCurrentContainer();
// ==================== CALCULATE VIEWPORT BOUNDS ====================
int editorX, editorY, editorWidth, editorHeight;
FullscreenConfig.paddingTop = 30;
FullscreenConfig.paddingBottom = 20;
FullscreenConfig.paddingLeft = 20;
FullscreenConfig.paddingRight = 20;
if (isFullscreen) {
// Fullscreen: viewport fills screen with configured padding
editorX = FullscreenConfig.paddingLeft;
editorY = FullscreenConfig.paddingTop;
editorWidth = this.width - FullscreenConfig.paddingLeft - FullscreenConfig.paddingRight;
editorHeight = this.height - FullscreenConfig.paddingTop - FullscreenConfig.paddingBottom;
} else {
// Normal: viewport within the GUI panel, leaving space for right panel
editorX = guiLeft + 1 + yoffset;
editorY = guiTop + yoffset;
editorWidth = xSize - 108 - yoffset;
editorHeight = (int) (ySize * 0.96) - yoffset * 2;
}
// ==================== HOOKS SCROLL (hidden in fullscreen) ====================
if (!isFullscreen) {
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.allowUserInput = false;
hooks.setSize(108, 198);
@@ -106,54 +254,143 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, guiTop + 5);
hookLabel.color = 0xaaaaaa;
addLabel(hookLabel);
}
ScriptContainer container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1);
GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, guiLeft + 1 + yoffset, guiTop + yoffset, xSize - 108 - yoffset, (int) (ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
ta.enableCodeHighlighting();
ta.setListener(this);
// ==================== SCRIPT TEXT AREA ====================
int idx = getActiveScriptIndex();
GuiScriptTextArea activeArea = getActiveScriptArea();
if (activeArea == null) {
activeArea = new GuiScriptTextArea(this, 2, editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.getScript());
activeArea.setListener(this);
this.closeOnEsc(activeArea::closeOnEsc);
textAreas.put(idx, activeArea);
} else {
activeArea.init(editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.getScript());
}
this.addTextField(ta);
// Set the scripting language for proper syntax highlighting
// Use the container's language if available, otherwise fall back to handler's language
String language = (container != null) ? container.getLanguage() : this.handler.getLanguage();
activeArea.setLanguage(language);
// Set the script context for context-aware hook autocomplete
activeArea.setScriptContext(getScriptContext());
// Setup fullscreen key binding
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
if (e.isPress()) {
toggleFullscreen();
}
});
activeArea.enableCodeHighlighting();
this.addTextField(activeArea);
// ==================== FULLSCREEN BUTTON ====================
int scrollbarOffset = activeArea.hasVerticalScrollbar() ? -8 : -2;
fullscreenButton.initGui(editorX + editorWidth, editorY, scrollbarOffset);
// ==================== RIGHT PANEL BUTTONS (hidden in fullscreen) ====================
if (!isFullscreen) {
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
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()));
}
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54D) - yoffset * 2);
scroll.guiLeft = left1;
scroll.guiTop = this.guiTop + 88 + yoffset;
if (container != null) {
scroll.setList(container.scripts);
scroll.setList(container.getExternalScripts());
}
this.addScroll(scroll);
} else {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.canEdit = false;
var8.setFocused(true);
this.addTextField(var8);
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.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, (String[]) this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex()));
this.getButton(103).enabled = this.languages.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));
if (this.player.worldObj.isRemote) {
this.addButton(new GuiNpcButton(106, var9, this.guiTop + 55, 150, 20, "script.openfolder"));
}
}
}
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
/**
* Initialize the settings tab layout (console view).
*/
private void initSettingsTab(int yoffset) {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset,
this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.canEdit = false;
var8.setFocused(true);
this.addTextField(var8);
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));
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));
if (this.player.worldObj.isRemote) {
this.addButton(new GuiNpcButton(106, var9, this.guiTop + 55, 150, 20, "script.openfolder"));
}
this.xSize = 420;
this.ySize = 256;
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
}
public GuiScriptInterface setDimensions(int x, int y) {
this.xSize = x;
this.ySize = y;
return this;
}
/**
* Get the script context for this GUI.
* Override in subclasses to return a different context.
*
* @return The script context (default: GLOBAL, or handler's context if available)
*/
protected ScriptContext getScriptContext() {
return handler.getContext();
}
// ==================== RENDERING ====================
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
// Draw fullscreen button on top of everything when on script editor tab
// Skip for useSettingsToggle GUIs (like GuiScript) - they handle this themselves
if (this.activeTab > 0 && !useSettingsToggle && !handler.isSingleContainer()) {
fullscreenButton.draw(mouseX, mouseY);
}
}
// ==================== MOUSE HANDLING ====================
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
// Check fullscreen button first when on script editor tab
// Skip for useSettingsToggle GUIs (like GuiScript) - they handle this themselves
if (this.activeTab > 0 && !useSettingsToggle && !handler.isSingleContainer() && fullscreenButton.mouseClicked(mouseX, mouseY, mouseButton)) {
return;
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
public String previousHookClicked = "";
@@ -162,10 +399,17 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
String hook = scroll.getSelected();
if (previousHookClicked.equals(hook)) {
IScriptUnit container = getCurrentContainer();
if (container == null)
return;
String addString = "";
if (!this.getTextField(2).getText().isEmpty())
addString += "\n";
addString += "function " + hook + "(event) {\n \n}\n";
// Generate the appropriate stub based on language
// hook is already the proper method name from EnumScriptType.function
addString += container.generateHookStub(hook, null);
this.getTextField(2).setText(this.getTextField(2).getText() + addString);
previousHookClicked = "";
@@ -192,19 +436,66 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return builder.toString();
}
private int getScriptIndex() {
int i = 0;
for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) {
String language = (String) var2.next();
if (language.equalsIgnoreCase(this.handler.getLanguage())) {
/**
* Finds the index of the current handler's language within the available options.
*
* @return The 0-based index, or 0 if not found.
*/
public int getLanguageIndex() {
return getLanguageIndex(getLanguageOptions());
}
/**
* Finds the index of the current handler's language within the provided list.
*
* @param languageOptions The list of available languages to search.
* @return The 0-based index, or 0 if not found.
*/
protected int getLanguageIndex(List<String> languageOptions) {
if (languageOptions == null || languageOptions.isEmpty())
return 0;
int i = 0;
String current = this.handler != null ? this.handler.getLanguage() : null;
for (String language : languageOptions) {
if (current != null && language.equalsIgnoreCase(current))
return i;
}
i++;
}
return 0;
}
/**
* Retrieves the list of available scripting languages for this handler.
* <p>
* This method prioritizes languages provided by the server through the {@link #languages} map.
* If "Java" is not present but the handler supports Janino, it injects "Java" into the options
* and ensures the client-side Janino script list is synchronized for the {@link EventGuiScriptList}.
*
* @return A list of language names available for selection.
*/
protected List<String> getLanguageOptions() {
List<String> options = new ArrayList<>();
if (this.languages != null && !this.languages.isEmpty())
options.addAll(this.languages.keySet());
if ((options.isEmpty() || !options.contains("Java")) && this.handler != null && this.handler.supportsJanino()) {
List<String> scripts = new ArrayList<>();
if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) {
scripts.addAll(ScriptController.Instance.scripts.keySet());
}
if (this.languages == null)
this.languages = new HashMap();
if (!this.languages.containsKey("Java"))
this.languages.put("Java", scripts);
options.add("Java");
}
return options;
}
public void confirmClicked(boolean flag, int i) {
if (flag) {
if (i == 0) {
@@ -223,7 +514,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
}
if (i == 10) {
this.handler.getScripts().remove(this.activeTab - 1);
handler.removeScriptUnit(this.activeTab - 1);
this.activeTab = 0;
}
if (i == 101) {
@@ -231,10 +522,10 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.setScript();
}
if (i == 102) {
ScriptContainer container;
IScriptUnit container;
if (this.activeTab > 0) {
container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1);
container.script = "";
container = this.handler.getScripts().get(this.activeTab - 1);
container.setScript("");
} else {
this.handler.clearConsole();
if (this.handler instanceof ScriptCustomItem) {
@@ -248,17 +539,67 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.displayGuiScreen(this);
}
public GuiScriptTextArea getActiveScriptArea() {
int idx = getActiveScriptIndex();
if (idx >= 0 && textAreas.containsKey(idx))
return textAreas.get(idx);
return null;
}
/**
* Get the current script index for text area storage.
* Override in subclasses with different tab logic.
*/
protected int getActiveScriptIndex() {
return this.activeTab - 1;
}
/**
* Get the current script container.
* Override in subclasses with different container access patterns.
*/
protected IScriptUnit getCurrentContainer() {
int idx = getActiveScriptIndex();
if (idx >= 0 && idx < this.handler.getScripts().size())
return this.handler.getScripts().get(idx);
return null;
}
@Override
public GuiNpcTextField getTextField(int id) {
if (id == 2) {
GuiScriptTextArea area = getActiveScriptArea();
if (area != null)
return area;
}
return super.getTextField(id);
}
@Override
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id >= 0 && guibutton.id < scriptLimit) {
this.setScript();
this.activeTab = guibutton.id;
this.initGui();
// Ensure JaninoScript is compiled after editing
IScriptUnit current = getCurrentContainer();
if (current != null)
current.ensureCompiled();
}
if (guibutton.id == scriptLimit) {
this.handler.getScripts().add(new ScriptContainer(this.handler));
this.activeTab = this.handler.getScripts().size();
if (handler.isSingleContainer()) {
if (handler.getSingleScript() == null) {
handler.addScriptUnit(new ScriptContainer(handler));
} else {
this.setScript();
}
this.activeTab = 1;
} else {
handler.addScriptUnit(new ScriptContainer(this.handler));
this.activeTab = this.handler.getScripts().size();
}
this.initGui();
}
@@ -287,7 +628,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
displayGuiScreen(guiyesno);
}
ScriptContainer container;
if (guibutton.id == 102) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
displayGuiScreen(guiyesno);
@@ -313,37 +653,103 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
if (guibutton.id == 107) {
container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1);
IScriptUnit container = getCurrentContainer();
if (container == null) {
this.handler.getScripts().add(container = new ScriptContainer(this.handler));
container = new ScriptContainer(this.handler);
handler.addScriptUnit(container);
}
this.setSubGui(new EventGuiScriptList((List) this.languages.get(this.handler.getLanguage()), container));
String language = container != null ? container.getLanguage() : this.handler.getLanguage();
this.setSubGui(new EventGuiScriptList((List) this.languages.get(language), container));
}
// Language toggle button - switch between ECMAScript and Java
if (guibutton.id == 113) {
int idx = getActiveScriptIndex();
if (idx >= 0 && idx < handler.getScripts().size()) {
IScriptUnit currentUnit = handler.getScripts().get(idx);
IScriptUnit newUnit;
if (currentUnit.isJanino()) {
// Switch from Java to ECMAScript
newUnit = new ScriptContainer(handler);
newUnit.setScript(currentUnit.getScript());
newUnit.setExternalScripts(new ArrayList<>(currentUnit.getExternalScripts()));
} else {
// Switch from ECMAScript to Java
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);
// Clear the cached text area so it recreates with new language
textAreas.remove(idx);
// Reinitialize the GUI
initGui();
}
}
}
private void setScript() {
if (this.activeTab > 0) {
ScriptContainer container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1);
protected void setScript() {
if (this.activeTab > 0 || useScrollTabs) {
IScriptUnit container = getCurrentContainer();
if (container == null) {
this.handler.getScripts().add(container = new ScriptContainer(this.handler));
container = new ScriptContainer(this.handler);
handler.addScriptUnit(container);
}
String text = (this.getTextField(2)).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.script = text;
if (container != null) {
String text = (this.getTextField(2)).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.setScript(text);
}
}
}
public void setGuiData(NBTTagCompound compound) {
if (handler instanceof IScriptHandlerPacket) {
IScriptHandlerPacket.GuiDataResult result = ((IScriptHandlerPacket) handler).setGuiData(compound);
if (result.kind == IScriptHandlerPacket.GuiDataKind.LOAD_COMPLETE) {
loaded = true;
return;
}
if (result.kind == IScriptHandlerPacket.GuiDataKind.METADATA) {
loadLanguagesData(compound);
return;
}
if (result.kind == IScriptHandlerPacket.GuiDataKind.TAB) {
initGui();
return;
}
return;
}
loadLanguagesData(compound);
}
// ==================== UNIFIED SCRIPT DATA HANDLING ====================
/**
* Load languages data from NBT.
* Separated for potential override in subclasses if needed.
*/
protected void loadLanguagesData(NBTTagCompound compound) {
NBTTagList data = compound.getTagList("Languages", 10);
HashMap languages = new HashMap();
for (int i = 0; i < data.tagCount(); ++i) {
NBTTagCompound comp = data.getCompoundTagAt(i);
ArrayList scripts = new ArrayList();
java.util.ArrayList scripts = new java.util.ArrayList();
NBTTagList list = comp.getTagList("Scripts", 8);
for (int j = 0; j < list.tagCount(); ++j) {
@@ -353,28 +759,193 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
languages.put(comp.getString("Language"), scripts);
}
if (handler != null && handler.supportsJanino()) {
List<String> javaScripts = (List<String>) languages.get("Java");
if (javaScripts == null || javaScripts.isEmpty()) {
javaScripts = new ArrayList<>();
if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) {
javaScripts.addAll(ScriptController.Instance.scripts.keySet());
}
languages.put("Java", javaScripts);
}
}
this.languages = languages;
this.initGui();
}
public void save() {
if (loaded)
this.setScript();
if (!loaded)
return;
this.setScript();
if (handler instanceof IScriptHandlerPacket)
((IScriptHandlerPacket) handler).sync();
}
public void textUpdate(String text) {
ScriptContainer container = (ScriptContainer) this.handler.getScripts().get(this.activeTab - 1);
IScriptUnit container = getCurrentContainer();
if (container != null) {
container.script = text;
container.setScript(text);
}
}
@Deprecated
@Override
//NEVER USED
public void saveText(String text) {
ScriptContainer container = handler.getScripts().get(activeTab);
IScriptUnit container = getCurrentContainer();
if (container != null)
container.script = text;
container.setScript(text);
initGui();
}
@Override
public void close() {
// Ensure JaninoScript is compiled after editing
IScriptUnit current = getCurrentContainer();
if (current != null)
current.ensureCompiled();
if (parent != null) {
this.save();
parent.setWorldAndResolution(mc, width, height);
parent.initGui();
mc.currentScreen = parent;
} else
super.close();
}
// ==================== FULLSCREEN METHODS ====================
/**
* Toggle fullscreen mode for the editor viewport.
* When entering fullscreen, maximizes the game window if it's not already.
*/
public void toggleFullscreen() {
isFullscreen = !isFullscreen;
// When entering fullscreen, maximize the game window if not already fullscreen
if (isFullscreen && !Display.isFullscreen()) {
// Note: Display.setFullscreen(true) would make it truly fullscreen,
// but that's usually not desirable for an in-game editor.
// The viewport will expand to fill whatever window size exists.
}
initGui();
}
/**
* Check if editor is currently in fullscreen mode
*/
public boolean isEditorFullscreen() {
return isFullscreen;
}
// ==================== FULLSCREEN BUTTON ====================
/**
* Button to toggle fullscreen mode, displayed at top-right corner of viewport.
* Shows expand icon when minimized, collapse icon when fullscreen.
*/
public class FullscreenButton {
public int x, y;
public int size = 12;
public boolean hovered = false;
/**
* Initialize button position relative to viewport bounds
*/
public void initGui(int viewportEndX, int viewportY, int scrollbarOffset) {
// Position at top-right, accounting for scrollbar
this.x = viewportEndX + scrollbarOffset - size - 4;
this.y = viewportY + 4;
}
/**
* Draw the fullscreen toggle button
*/
public void draw(int mouseX, int mouseY) {
hovered = isMouseOver(mouseX, mouseY);
int y = this.y + getYOffset();
// Button background
int bgColor = hovered ? 0x80666666 : 0x60444444;
GuiUtil.drawRectD(x, y, x + size, y + size, bgColor);
// Draw corner brackets to indicate expand/collapse
int iconColor = hovered ? 0xFFFFFFFF : 0xFFAAAAAA;
int inset = 2;
int cornerLen = 3;
if (isFullscreen) {
// Draw collapse icon (corners pointing inward) — inward L-shapes
int top = y + inset + 2;
int left = x + inset + 2;
int right = x + size - inset - 3;
int bottom = y + size - inset - 3;
drawRect(left, top - cornerLen + 1, left + 1, top + 1, iconColor);
drawRect(left - cornerLen + 1, top, left + 1, top + 1, iconColor);
drawRect(right, top, right + cornerLen, top + 1, iconColor);
drawRect(right, top - cornerLen + 1, right + 1, top + 1, iconColor);
drawRect(left - cornerLen + 1, bottom, left + 1, bottom + 1, iconColor);
drawRect(left, bottom, left + 1, bottom + cornerLen, iconColor);
drawRect(right, bottom, right + cornerLen, bottom + 1, iconColor);
drawRect(right, bottom, right + 1, bottom + cornerLen, iconColor);
} else {
// Draw expand icon (corners pointing outward) ⌐¬⌙⌞
// Top-left corner pointing outward
drawRect(x + inset, y + inset, x + inset + 1, y + inset + cornerLen, iconColor);
drawRect(x + inset, y + inset, x + inset + cornerLen, y + inset + 1, iconColor);
// Top-right corner pointing outward
drawRect(x + size - inset - 1, y + inset, x + size - inset, y + inset + cornerLen, iconColor);
drawRect(x + size - inset - cornerLen, y + inset, x + size - inset, y + inset + 1, iconColor);
// Bottom-left corner pointing outward
drawRect(x + inset, y + size - inset - cornerLen, x + inset + 1, y + size - inset, iconColor);
drawRect(x + inset, y + size - inset - 1, x + inset + cornerLen, y + size - inset, iconColor);
// Bottom-right corner pointing outward
drawRect(x + size - inset - 1, y + size - inset - cornerLen, x + size - inset, y + size - inset,
iconColor);
drawRect(x + size - inset - cornerLen, y + size - inset - 1, x + size - inset, y + size - inset,
iconColor);
}
}
public void drawRect(int x1, int y1, int x2, int y2, int color) {
GuiUtil.drawRectD(x1, y1, x2, y2, color);
}
/**
* Check if mouse is over the button
*/
public boolean isMouseOver(int mouseX, int mouseY) {
int y = this.y + getYOffset();
return mouseX >= x && mouseX < x + size && mouseY >= y && mouseY < y + size;
}
/**
* Handle click - returns true if click was consumed
*/
public boolean mouseClicked(int mouseX, int mouseY, int button) {
if (button == 0 && isMouseOver(mouseX, mouseY)) {
toggleFullscreen();
return true;
}
return false;
}
public int getYOffset() {
return GuiScriptTextArea.searchBar.getTotalHeight();
}
}
}
@@ -1,72 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.item.ItemScriptErrorPacket;
import kamkeel.npcs.network.packets.request.script.item.ItemScriptPacket;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomItems;
import noppes.npcs.NBTTags;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.scripted.item.ScriptCustomItem;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class GuiScriptItem extends GuiScriptInterface {
private ScriptCustomItem item;
public static Map<Long, String> consoleText = new HashMap<>();
public GuiScriptItem() {
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_ITEM));
this.handler = this.item = new ScriptCustomItem(new ItemStack(CustomItems.scripted_item));
ItemScriptErrorPacket.Get();
ItemScriptPacket.Get();
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("ItemScriptConsole")) {
consoleText = NBTTags.GetLongStringMap(compound.getTagList("ItemScriptConsole", 10));
initGui();
} else {
this.item.setMCNbt(compound);
this.item.loadScriptData();
super.setGuiData(compound);
loaded = true;
}
}
public void save() {
if (loaded) {
super.save();
ItemScriptPacket.Save(this.item.getMCNbt());
}
}
protected String getConsoleText() {
Map<Long, String> map = consoleText;
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet().iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n");
}
return builder.toString();
}
public void confirmClicked(boolean flag, int i) {
if (i == 102) {
if (activeTab <= 0) {
consoleText = new HashMap<>();
ItemScriptErrorPacket.Clear();
}
}
super.confirmClicked(flag, i);
}
}
@@ -1,416 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.item.LinkedItemScriptPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.StatCollector;
import noppes.npcs.NBTTags;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.LinkedItem;
import noppes.npcs.controllers.data.LinkedItemScript;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GuiScriptLinkedItem extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener {
private int activeTab = 0;
public Map<String, List<String>> languages = new HashMap();
private final int scriptLimit = 1;
public List<String> hookList = new ArrayList();
public String previousHookClicked = "";
public final GuiNPCManageLinked parent;
public final LinkedItem linkedItem;
private final LinkedItemScript scriptHandler;
boolean loaded = false;
public GuiScriptLinkedItem(GuiNPCManageLinked parent, LinkedItem linkedItem) {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.setBackground("menubg.png");
this.parent = parent;
this.linkedItem = linkedItem;
this.scriptHandler = new LinkedItemScript();
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_LINKED_ITEM));
LinkedItemScriptPacket.Get(linkedItem.id);
}
public void initGui() {
this.ySize = (int) ((double) this.xSize * 0.56);
if ((double) this.ySize > (double) this.height * 0.95) {
this.ySize = (int) ((double) this.height * 0.95);
this.xSize = (int) ((double) this.ySize / 0.56);
}
this.bgScale = (float) this.xSize / 400.0F;
super.initGui();
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02);
GuiMenuTopButton top;
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
if (this.scriptHandler.container != null) {
this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script"));
} else {
this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
}
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
}
top.active = true;
if (this.activeTab == 1) {
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.allowUserInput = false;
hooks.setSize(108, 198);
hooks.guiLeft = this.guiLeft - 110;
hooks.guiTop = this.guiTop + 14;
hooks.setUnsortedList(this.hookList);
this.addScroll(hooks);
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5);
hookLabel.color = 11184810;
this.addLabel(hookLabel);
ScriptContainer container = this.scriptHandler.container;
GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
ta.enableCodeHighlighting();
ta.setListener(this);
this.addTextField(ta);
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
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"));
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
this.getButton(107).enabled = false;
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2);
scroll.guiLeft = left1;
scroll.guiTop = this.guiTop + 88 + yoffset;
if (container != null) {
scroll.setList(container.scripts);
}
this.addScroll(scroll);
} else {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.enabled = false;
this.addTextField(var8);
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.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex()));
this.getButton(103).enabled = !this.languages.isEmpty();
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.scriptHandler.getEnabled() ? 1 : 0));
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
}
this.xSize = 420;
this.ySize = 256;
}
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
String hook = scroll.getSelected();
if (this.previousHookClicked.equals(hook)) {
String addString = "";
if (!this.getTextField(2).getText().isEmpty()) {
addString = addString + "\n";
}
addString = addString + "function " + hook + "(event) {\n \n}\n";
this.getTextField(2).setText(this.getTextField(2).getText() + addString);
this.previousHookClicked = "";
} else {
this.previousHookClicked = hook;
}
}
public void unFocused(GuiNpcTextField textfield) {
}
private String getConsoleText() {
Map<Long, String> map = this.scriptHandler.getConsoleText();
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet().iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n");
}
return builder.toString();
}
private int getScriptIndex() {
int i = 0;
for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) {
String language = (String) var2.next();
if (language.equalsIgnoreCase(this.scriptHandler.getLanguage())) {
return i;
}
}
return 0;
}
public void confirmClicked(boolean flag, int i) {
if (flag) {
if (i == 0) {
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
}
if (i == 1) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 2) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 3) {
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
}
if (i == 10) {
this.scriptHandler.container = null;
this.activeTab = 0;
}
if (i == 101) {
this.getTextField(2).setText(NoppesStringUtils.getClipboardContents());
this.setScript();
}
if (i == 102) {
if (this.activeTab == 1) {
ScriptContainer container = this.scriptHandler.container;
container.script = "";
} else {
this.scriptHandler.clearConsole();
}
this.initGui();
}
}
this.displayGuiScreen(this);
}
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
this.setScript();
this.activeTab = 0;
this.initGui();
}
if (guibutton.id == this.scriptLimit) {
if (scriptHandler.container == null)
this.scriptHandler.container = new ScriptContainer(this.scriptHandler);
else
this.setScript();
this.activeTab = 1;
this.initGui();
}
if (guibutton.id == 109) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
}
if (guibutton.id == 110) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
}
if (guibutton.id == 111) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
}
if (guibutton.id == 112) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
}
if (guibutton.id == 100) {
NoppesStringUtils.setClipboardContents(this.getTextField(2).getText());
}
if (guibutton.id == 101) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
this.displayGuiScreen(guiyesno);
}
GuiYesNo container1;
if (guibutton.id == 102) {
container1 = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
this.displayGuiScreen(container1);
}
if (guibutton.id == 103) {
this.scriptHandler.setLanguage(guibutton.displayString);
}
if (guibutton.id == 104) {
this.scriptHandler.setEnabled(((GuiNpcButton) guibutton).getValue() == 1);
}
if (guibutton.id == 105) {
container1 = new GuiYesNo(this, "", ((GuiNpcButton) guibutton).displayString, 10);
this.displayGuiScreen(container1);
}
if (guibutton.id == 107) {
ScriptContainer container = this.scriptHandler.container;
if (container == null) {
container = new ScriptContainer(this.scriptHandler);
this.scriptHandler.container = container;
}
// this.setSubGui(new EventGuiScriptList((List)this.languages.get(this.script.getLanguage()), container));
}
}
private void setScript() {
if (this.activeTab == 1) {
ScriptContainer container = this.scriptHandler.container;
if (container == null) {
container = new ScriptContainer(this.scriptHandler);
this.scriptHandler.container = container;
}
String text = this.getTextField(2).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.script = text;
}
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
this.scriptHandler.setLanguage(compound.getString("ScriptLanguage"));
this.scriptHandler.setEnabled(compound.getBoolean("ScriptEnabled"));
this.copiedSetGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(this.scriptHandler);
container.readFromNBT(compound.getCompoundTag("Script"));
this.scriptHandler.container = container;
this.initGui();
}
}
private void copiedSetGuiData(NBTTagCompound compound) {
NBTTagList data = compound.getTagList("Languages", 10);
HashMap languages = new HashMap();
for (int i = 0; i < data.tagCount(); ++i) {
NBTTagCompound comp = data.getCompoundTagAt(i);
ArrayList scripts = new ArrayList();
NBTTagList list = comp.getTagList("Scripts", 8);
for (int j = 0; j < list.tagCount(); ++j) {
scripts.add(list.getStringTagAt(j));
}
languages.put(comp.getString("Language"), scripts);
}
this.languages = languages;
this.initGui();
}
public void save() {
if (loaded) {
this.setScript();
List<ScriptContainer> containers = this.scriptHandler.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
LinkedItemScriptPacket.Save(linkedItem.id, i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.scriptHandler.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.scriptHandler.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.scriptHandler.getConsoleText()));
LinkedItemScriptPacket.Save(linkedItem.id, -1, containers.size(), scriptData);
}
}
public void textUpdate(String text) {
ScriptContainer container = this.scriptHandler.container;
if (container != null) {
container.script = text;
}
}
public void saveText(String text) {
ScriptContainer container = this.scriptHandler.container;
if (container != null) {
container.script = text;
}
this.initGui();
}
@Override
public void close() {
this.save();
parent.setWorldAndResolution(mc, width, height);
parent.initGui();
mc.currentScreen = parent;
}
}
@@ -1,64 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.PlayerScriptPacket;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NBTTags;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.PlayerDataScript;
import java.util.ArrayList;
import java.util.List;
public class GuiScriptPlayers extends GuiScriptInterface {
private PlayerDataScript script = new PlayerDataScript((EntityPlayer) null);
public GuiScriptPlayers() {
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_PLAYER));
this.handler = this.script;
PlayerScriptPacket.Get();
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
script.setLanguage(compound.getString("ScriptLanguage"));
script.setEnabled(compound.getBoolean("ScriptEnabled"));
super.setGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(script);
container.readFromNBT(compound.getCompoundTag("Script"));
if (script.getScripts().isEmpty()) {
for (int i = 0; i < compound.getInteger("TotalScripts"); i++) {
script.getScripts().add(new ScriptContainer(script));
}
}
script.getScripts().set(tab, container);
initGui();
}
}
public void save() {
if (loaded) {
super.save();
List<ScriptContainer> containers = this.script.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
PlayerScriptPacket.Save(i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.script.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.script.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.script.getConsoleText()));
PlayerScriptPacket.Save(-1, containers.size(), scriptData);
}
}
}
@@ -1,435 +0,0 @@
package noppes.npcs.client.gui.script;
import kamkeel.npcs.network.packets.request.script.RecipeScriptPacket;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.StatCollector;
import noppes.npcs.NBTTags;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.gui.global.GuiNpcManageRecipes;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptHookController;
import noppes.npcs.controllers.data.RecipeAnvil;
import noppes.npcs.controllers.data.RecipeCarpentry;
import noppes.npcs.controllers.data.RecipeScript;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GuiScriptRecipe extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ITextChangeListener, ICustomScrollListener, IJTextAreaListener, ITextfieldListener {
private int activeTab = 0;
public Map<String, List<String>> languages = new HashMap();
private final int scriptLimit = 1;
public List<String> hookList = new ArrayList();
public String previousHookClicked = "";
public final GuiNpcManageRecipes parent;
public final int recipeId;
public final boolean anvil;
private final RecipeScript scriptHandler;
boolean loaded = false;
public GuiScriptRecipe(GuiNpcManageRecipes parent, RecipeCarpentry recipe) {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.setBackground("menubg.png");
this.parent = parent;
this.scriptHandler = new RecipeScript();
this.anvil = false;
this.recipeId = recipe.id;
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_RECIPE));
RecipeScriptPacket.Get(false, recipeId);
}
public GuiScriptRecipe(GuiNpcManageRecipes parent, RecipeAnvil recipe) {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
this.xSize = 420;
this.setBackground("menubg.png");
this.parent = parent;
this.scriptHandler = new RecipeScript();
this.anvil = true;
this.recipeId = recipe.id;
this.hookList = new ArrayList<>(ScriptHookController.Instance.getAllHooks(IScriptHookHandler.CONTEXT_RECIPE));
RecipeScriptPacket.Get(true, recipeId);
}
public void initGui() {
this.ySize = (int) ((double) this.xSize * 0.56);
if ((double) this.ySize > (double) this.height * 0.95) {
this.ySize = (int) ((double) this.height * 0.95);
this.xSize = (int) ((double) this.ySize / 0.56);
}
this.bgScale = (float) this.xSize / 400.0F;
super.initGui();
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02);
GuiMenuTopButton top;
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
if (this.scriptHandler.container != null) {
this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script"));
} else {
this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
}
top = this.getTopButton(this.activeTab);
if (top == null) {
this.activeTab = 0;
top = this.getTopButton(0);
}
top.active = true;
if (this.activeTab == 1) {
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.allowUserInput = false;
hooks.setSize(108, 198);
hooks.guiLeft = this.guiLeft - 110;
hooks.guiTop = this.guiTop + 14;
hooks.setUnsortedList(this.hookList);
this.addScroll(hooks);
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5);
hookLabel.color = 11184810;
this.addLabel(hookLabel);
ScriptContainer container = this.scriptHandler.container;
GuiScriptTextArea ta = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
ta.enableCodeHighlighting();
ta.setListener(this);
this.addTextField(ta);
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
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"));
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
this.getButton(107).enabled = false;
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2);
scroll.guiLeft = left1;
scroll.guiTop = this.guiTop + 88 + yoffset;
if (container != null) {
scroll.setList(container.scripts);
}
this.addScroll(scroll);
} else {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.enabled = false;
this.addTextField(var8);
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.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, this.languages.keySet().toArray(new String[this.languages.keySet().size()]), this.getScriptIndex()));
this.getButton(103).enabled = !this.languages.isEmpty();
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.scriptHandler.getEnabled() ? 1 : 0));
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
}
this.xSize = 420;
this.ySize = 256;
}
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
String hook = scroll.getSelected();
if (this.previousHookClicked.equals(hook)) {
String addString = "";
if (!this.getTextField(2).getText().isEmpty()) {
addString = addString + "\n";
}
addString = addString + "function " + hook + "(event) {\n \n}\n";
this.getTextField(2).setText(this.getTextField(2).getText() + addString);
this.previousHookClicked = "";
} else {
this.previousHookClicked = hook;
}
}
public void unFocused(GuiNpcTextField textfield) {
}
private String getConsoleText() {
Map<Long, String> map = this.scriptHandler.getConsoleText();
StringBuilder builder = new StringBuilder();
Iterator var3 = map.entrySet().iterator();
while (var3.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
builder.insert(0, new Date((Long) entry.getKey()) + (String) entry.getValue() + "\n");
}
return builder.toString();
}
private int getScriptIndex() {
int i = 0;
for (Iterator var2 = this.languages.keySet().iterator(); var2.hasNext(); ++i) {
String language = (String) var2.next();
if (language.equalsIgnoreCase(this.scriptHandler.getLanguage())) {
return i;
}
}
return 0;
}
public void confirmClicked(boolean flag, int i) {
if (flag) {
if (i == 0) {
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
}
if (i == 1) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 2) {
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
}
if (i == 3) {
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
}
if (i == 10) {
this.scriptHandler.container = null;
this.activeTab = 0;
}
if (i == 101) {
this.getTextField(2).setText(NoppesStringUtils.getClipboardContents());
this.setScript();
}
if (i == 102) {
if (this.activeTab == 1) {
ScriptContainer container = this.scriptHandler.container;
container.script = "";
} else {
this.scriptHandler.clearConsole();
}
this.initGui();
}
}
this.displayGuiScreen(this);
}
protected void actionPerformed(GuiButton guibutton) {
if (guibutton.id == 0) {
this.setScript();
this.activeTab = 0;
this.initGui();
}
if (guibutton.id == this.scriptLimit) {
if (scriptHandler.container == null)
this.scriptHandler.container = new ScriptContainer(this.scriptHandler);
else
this.setScript();
this.activeTab = 1;
this.initGui();
}
if (guibutton.id == 109) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
}
if (guibutton.id == 110) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
}
if (guibutton.id == 111) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
}
if (guibutton.id == 112) {
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
}
if (guibutton.id == 100) {
NoppesStringUtils.setClipboardContents(this.getTextField(2).getText());
}
if (guibutton.id == 101) {
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
this.displayGuiScreen(guiyesno);
}
GuiYesNo container1;
if (guibutton.id == 102) {
container1 = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
this.displayGuiScreen(container1);
}
if (guibutton.id == 103) {
this.scriptHandler.setLanguage(guibutton.displayString);
}
if (guibutton.id == 104) {
this.scriptHandler.setEnabled(((GuiNpcButton) guibutton).getValue() == 1);
}
if (guibutton.id == 105) {
container1 = new GuiYesNo(this, "", ((GuiNpcButton) guibutton).displayString, 10);
this.displayGuiScreen(container1);
}
if (guibutton.id == 107) {
ScriptContainer container = this.scriptHandler.container;
if (container == null) {
container = new ScriptContainer(this.scriptHandler);
this.scriptHandler.container = container;
}
// this.setSubGui(new EventGuiScriptList((List)this.languages.get(this.script.getLanguage()), container));
}
}
private void setScript() {
if (this.activeTab == 1) {
ScriptContainer container = this.scriptHandler.container;
if (container == null) {
container = new ScriptContainer(this.scriptHandler);
this.scriptHandler.container = container;
}
String text = this.getTextField(2).getText();
text = text.replace("\r\n", "\n");
text = text.replace("\r", "\n");
container.script = text;
}
}
public void setGuiData(NBTTagCompound compound) {
if (compound.hasKey("LoadComplete")) {
loaded = true;
return;
}
if (!compound.hasKey("Tab")) {
this.scriptHandler.setLanguage(compound.getString("ScriptLanguage"));
this.scriptHandler.setEnabled(compound.getBoolean("ScriptEnabled"));
this.copiedSetGuiData(compound);
} else {
int tab = compound.getInteger("Tab");
ScriptContainer container = new ScriptContainer(this.scriptHandler);
container.readFromNBT(compound.getCompoundTag("Script"));
this.scriptHandler.container = container;
this.initGui();
}
}
private void copiedSetGuiData(NBTTagCompound compound) {
NBTTagList data = compound.getTagList("Languages", 10);
HashMap languages = new HashMap();
for (int i = 0; i < data.tagCount(); ++i) {
NBTTagCompound comp = data.getCompoundTagAt(i);
ArrayList scripts = new ArrayList();
NBTTagList list = comp.getTagList("Scripts", 8);
for (int j = 0; j < list.tagCount(); ++j) {
scripts.add(list.getStringTagAt(j));
}
languages.put(comp.getString("Language"), scripts);
}
this.languages = languages;
this.initGui();
}
public void save() {
if (loaded) {
this.setScript();
List<ScriptContainer> containers = this.scriptHandler.getScripts();
for (int i = 0; i < containers.size(); i++) {
ScriptContainer container = containers.get(i);
RecipeScriptPacket.Save(anvil, recipeId, i, containers.size(), container.writeToNBT(new NBTTagCompound()));
}
NBTTagCompound scriptData = new NBTTagCompound();
scriptData.setString("ScriptLanguage", this.scriptHandler.getLanguage());
scriptData.setBoolean("ScriptEnabled", this.scriptHandler.getEnabled());
scriptData.setTag("ScriptConsole", NBTTags.NBTLongStringMap(this.scriptHandler.getConsoleText()));
RecipeScriptPacket.Save(anvil, recipeId, -1, containers.size(), scriptData);
}
}
public void textUpdate(String text) {
ScriptContainer container = this.scriptHandler.container;
if (container != null) {
container.script = text;
}
}
public void saveText(String text) {
ScriptContainer container = this.scriptHandler.container;
if (container != null) {
container.script = text;
}
this.initGui();
}
@Override
public void close() {
this.save();
parent.setWorldAndResolution(mc, width, height);
parent.initGui();
mc.currentScreen = parent;
}
}
@@ -0,0 +1,123 @@
package noppes.npcs.client.gui.script;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
public class SubGuiSelectList extends SubGuiInterface {
private GuiCustomScroll scroll1;
private GuiCustomScroll scroll2;
public String allName, selectedName;
public List<String> all;
public List<String> selected;
public SubGuiSelectList(List<String> all, List<String> selected, String allName, String selectedName) {
setBackground("menubg.png");
xSize = 346;
ySize = 216;
this.allName = allName;
this.selectedName = selectedName;
if (all == null)
all = new ArrayList<>();
this.all = all;
if (selected == null)
selected = new ArrayList<>();
this.selected = selected;
}
@Override
public void initGui() {
super.initGui();
if (scroll1 == null) {
scroll1 = new GuiCustomScroll(this, 0);
scroll1.setSize(140, 180);
}
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 22, guiTop - 17, "X"));
scroll1.guiLeft = guiLeft + 4;
scroll1.guiTop = guiTop + 14;
this.addScroll(scroll1);
addLabel(new GuiNpcLabel(1, allName, guiLeft + 4, guiTop + 4));
if (scroll2 == null) {
scroll2 = new GuiCustomScroll(this, 1);
scroll2.setSize(140, 180);
}
scroll2.guiLeft = guiLeft + 200;
scroll2.guiTop = guiTop + 14;
this.addScroll(scroll2);
addLabel(new GuiNpcLabel(2, selectedName, guiLeft + 200, guiTop + 4));
List<String> tempAll = new ArrayList<>(all);
tempAll.removeAll(selected);
scroll1.setList(tempAll);
scroll2.setList(selected);
addButton(new GuiNpcButton(1, guiLeft + 145, guiTop + 40, 55, 20, ">"));
addButton(new GuiNpcButton(2, guiLeft + 145, guiTop + 62, 55, 20, "<"));
addButton(new GuiNpcButton(3, guiLeft + 145, guiTop + 90, 55, 20, ">>"));
addButton(new GuiNpcButton(4, guiLeft + 145, guiTop + 112, 55, 20, "<<"));
addButton(new GuiNpcButton(66, guiLeft + 260, guiTop + 194, 60, 20, "gui.done"));
}
protected void actionPerformed(GuiButton guibutton) {
GuiNpcButton button = (GuiNpcButton) guibutton;
if (button.id == -1) {
close();
return;
}
if (button.id == 1) {
if (scroll1.hasSelected()) {
selected.add(scroll1.getSelected());
scroll1.selected = -1;
scroll2.selected = -1;
initGui();
}
}
if (button.id == 2) {
if (scroll2.hasSelected()) {
selected.remove(scroll2.getSelected());
scroll2.selected = -1;
initGui();
}
}
if (button.id == 3) {
selected.clear();
for (String type : all)
selected.add(type);
scroll1.selected = -1;
scroll2.selected = -1;
initGui();
}
if (button.id == 4) {
selected.clear();
scroll1.selected = -1;
scroll2.selected = -1;
initGui();
}
if (button.id == 66) {
close();
}
}
@Override
public void save() {
}
}
@@ -19,20 +19,42 @@ import java.util.Vector;
/**
* Animation selection dialog for choosing global animations.
* Requests animation data from the server via packets.
* Toggle between Built-in animations (by name) and Custom animations (by ID).
*/
public class GuiAnimationSelection extends SubGuiInterface implements ICustomScrollListener, IScrollData {
private GuiCustomScroll scrollAnimations;
private HashMap<String, Integer> animationData = new HashMap<String, Integer>();
// Built-in animations (name only, no ID)
private HashMap<String, Integer> builtInData = new HashMap<>();
// Custom/user animations (name -> ID)
private HashMap<String, Integer> customData = new HashMap<>();
// View mode: true = built-in, false = custom
private boolean showingBuiltIn = true;
// Initial values passed in
private int initialAnimationId;
public int selectedAnimationId = -1;
private String selectedName = null;
private String initialAnimationName;
// Selected values to return
public int selectedAnimationId = -1;
public String selectedBuiltInName = "";
private String selectedCustomName = null;
private String search = "";
/**
* Constructor for selecting by ID (user animations).
*/
public GuiAnimationSelection(int animationId) {
this(animationId, "");
}
/**
* Constructor for selecting by name (built-in) or ID (user).
*/
public GuiAnimationSelection(int animationId, String animationName) {
drawDefaultBackground = false;
title = "";
setBackground("menubg.png");
@@ -40,7 +62,12 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
ySize = 226;
this.initialAnimationId = animationId;
this.initialAnimationName = animationName != null ? animationName : "";
this.selectedAnimationId = animationId;
this.selectedBuiltInName = this.initialAnimationName;
// Start showing built-in if we have a built-in name, otherwise custom
this.showingBuiltIn = !this.initialAnimationName.isEmpty();
// Request animation data from server
PacketClient.sendClient(new AnimationsGetPacket());
@@ -50,55 +77,87 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
public void initGui() {
super.initGui();
this.addLabel(new GuiNpcLabel(0, "menu.animations", guiLeft + 8, guiTop + 4));
int y = guiTop + 4;
this.addButton(new GuiNpcButton(1, guiLeft + 4, guiTop + ySize - 35, 50, 20, "gui.clear"));
this.addButton(new GuiNpcButton(2, guiLeft + xSize - 56, guiTop + ySize - 35, 50, 20, "gui.done"));
this.addButton(new GuiNpcButton(3, guiLeft + xSize - 108, guiTop + ySize - 35, 50, 20, "gui.cancel"));
// Toggle button for switching views
String viewLabel = showingBuiltIn ? "gui.builtinAnimations" : "gui.customAnimations";
this.addButton(new GuiNpcButton(10, guiLeft + 4, y, 212, 20, viewLabel));
y += 24;
// Animation scroll list
if (scrollAnimations == null) {
scrollAnimations = new GuiCustomScroll(this, 0, 0);
scrollAnimations.setSize(212, 163);
scrollAnimations.setSize(212, 130);
}
scrollAnimations.setList(getSearchList());
if (selectedName != null) {
scrollAnimations.setSelected(selectedName);
}
scrollAnimations.guiLeft = guiLeft + 4;
scrollAnimations.guiTop = guiTop + 14;
this.addScroll(scrollAnimations);
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 179, 212, 20, search));
// Set selection based on current mode
if (showingBuiltIn && !selectedBuiltInName.isEmpty()) {
scrollAnimations.setSelected(selectedBuiltInName);
} else if (!showingBuiltIn && selectedCustomName != null) {
scrollAnimations.setSelected(selectedCustomName);
}
scrollAnimations.guiLeft = guiLeft + 4;
scrollAnimations.guiTop = y;
this.addScroll(scrollAnimations);
y += 134;
// Search textbox
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, y, 212, 20, search));
y += 24;
// Buttons
this.addButton(new GuiNpcButton(1, guiLeft + 4, y, 50, 20, "gui.clear"));
this.addButton(new GuiNpcButton(3, guiLeft + xSize - 108, y, 50, 20, "gui.cancel"));
this.addButton(new GuiNpcButton(2, guiLeft + xSize - 56, y, 50, 20, "gui.done"));
}
@Override
public void setData(Vector<String> list, HashMap<String, Integer> data, EnumScrollData type) {
this.animationData = data;
if (type == EnumScrollData.BUILTIN_ANIMATIONS) {
this.builtInData = data;
// Find the name for our initial animation ID
if (initialAnimationId >= 0) {
for (String name : data.keySet()) {
if (data.get(name) == initialAnimationId) {
selectedName = name;
break;
// Check if initial name matches a built-in animation
if (!initialAnimationName.isEmpty()) {
for (String name : builtInData.keySet()) {
if (name.equalsIgnoreCase(initialAnimationName)) {
selectedBuiltInName = name;
selectedAnimationId = -1;
selectedCustomName = null;
showingBuiltIn = true;
break;
}
}
}
} else if (type == EnumScrollData.ANIMATIONS) {
this.customData = data;
// Find the name for our initial animation ID (if not using built-in)
if (selectedBuiltInName.isEmpty() && initialAnimationId >= 0) {
for (String name : data.keySet()) {
if (data.get(name) == initialAnimationId) {
selectedCustomName = name;
showingBuiltIn = false;
break;
}
}
}
}
if (scrollAnimations != null) {
scrollAnimations.setList(getSearchList());
if (selectedName != null) {
scrollAnimations.setSelected(selectedName);
if (showingBuiltIn && !selectedBuiltInName.isEmpty()) {
scrollAnimations.setSelected(selectedBuiltInName);
} else if (!showingBuiltIn && selectedCustomName != null) {
scrollAnimations.setSelected(selectedCustomName);
}
}
}
@Override
public void setSelected(String selected) {
this.selectedName = selected;
if (scrollAnimations != null) {
scrollAnimations.setSelected(selected);
}
// Not used in this implementation
}
@Override
@@ -109,18 +168,22 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
if (search.equals(getTextField(55).getText()))
return;
search = getTextField(55).getText().toLowerCase();
scrollAnimations.resetScroll();
scrollAnimations.setList(getSearchList());
if (scrollAnimations != null) {
scrollAnimations.resetScroll();
scrollAnimations.setList(getSearchList());
}
}
}
}
private List<String> getSearchList() {
HashMap<String, Integer> sourceData = showingBuiltIn ? builtInData : customData;
if (search.isEmpty()) {
return new ArrayList<String>(animationData.keySet());
return new ArrayList<>(sourceData.keySet());
}
List<String> list = new ArrayList<String>();
for (String name : animationData.keySet()) {
List<String> list = new ArrayList<>();
for (String name : sourceData.keySet()) {
if (name.toLowerCase().contains(search))
list.add(name);
}
@@ -129,11 +192,20 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 0) {
String selected = scrollAnimations.getSelected();
if (selected != null && animationData.containsKey(selected)) {
selectedName = selected;
selectedAnimationId = animationData.get(selected);
String selected = scrollAnimations.getSelected();
if (selected == null) return;
if (showingBuiltIn) {
if (builtInData.containsKey(selected)) {
selectedBuiltInName = selected;
selectedAnimationId = -1;
selectedCustomName = null;
}
} else {
if (customData.containsKey(selected)) {
selectedCustomName = selected;
selectedAnimationId = customData.get(selected);
selectedBuiltInName = "";
}
}
initGui();
@@ -141,27 +213,40 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (selectedAnimationId < 0)
return;
close();
// Double-click to confirm selection
if (!selectedBuiltInName.isEmpty() || selectedAnimationId >= 0) {
close();
}
}
@Override
protected void actionPerformed(GuiButton guibutton) {
int id = guibutton.id;
if (id == 1) {
// Clear selection
selectedName = null;
// Toggle view button
if (id == 10) {
showingBuiltIn = !showingBuiltIn;
search = "";
if (scrollAnimations != null) {
scrollAnimations.resetScroll();
}
initGui();
}
// Clear
else if (id == 1) {
selectedBuiltInName = "";
selectedAnimationId = -1;
selectedCustomName = null;
close();
}
if (id == 2) {
// Done - keep selection
// Done
else if (id == 2) {
close();
}
if (id == 3) {
// Cancel - restore initial value
// Cancel
else if (id == 3) {
selectedAnimationId = initialAnimationId;
selectedBuiltInName = initialAnimationName;
close();
}
}
@@ -170,6 +255,16 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr
* Get the name of the selected animation (for display purposes).
*/
public String getSelectedName() {
return selectedName;
if (!selectedBuiltInName.isEmpty()) {
return selectedBuiltInName;
}
return selectedCustomName;
}
/**
* Check if a built-in animation was selected.
*/
public boolean isBuiltInSelected() {
return !selectedBuiltInName.isEmpty();
}
}
@@ -371,6 +371,7 @@ public class GuiTextureSelection extends SubGuiInterface implements ICustomScrol
selectedDomain = domain;
this.location = location;
}
static class TextureData {
String domain;
String absoluteName;
@@ -0,0 +1,368 @@
package noppes.npcs.client.gui.util;
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.AbilityPhase;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityDisc;
import kamkeel.npcs.entity.EntityAbilityLaser;
import kamkeel.npcs.entity.EntityAbilityOrb;
import kamkeel.npcs.entity.EntityAbilityProjectile;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.world.World;
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.
*
* Lifecycle:
* 1. WINDUP phase - plays windup animation, entities spawn and charge
* 2. ACTIVE phase - plays active animation, entities fire and move
* 3. EXTENDED phase - continues for +100 ticks after animations to see results
* 4. IDLE - preview complete
*
* Features:
* - Invisible fake target NPC placed in front of the preview NPC for targeting
* - NPC movement tracking for abilities that move the NPC (e.g. slam)
*/
@SideOnly(Side.CLIENT)
public class AbilityPreviewExecutor {
// ==================== PREVIEW STATE ====================
private Ability previewAbility;
private EntityNPCInterface previewNpc;
private AbilityPhase phase = AbilityPhase.IDLE;
private int currentTick = 0;
private boolean playing = false;
private boolean paused = false;
// ==================== TIMING ====================
private static final int EXTENDED_DURATION = 100;
private int activeDuration = 40;
// ==================== FAKE TARGET ====================
/** Invisible fake target NPC for ability targeting (placed 5 blocks in front of preview NPC) */
private EntityNPCInterface fakeTarget;
private static final double TARGET_DISTANCE = 5.0;
// ==================== NPC START POSITION ====================
/** Saved NPC position for restoring after movement abilities */
private double npcStartX, npcStartY, npcStartZ;
// ==================== PREVIEW CONTENT ====================
private TelegraphInstance previewTelegraph;
private List<Entity> previewEntities = new ArrayList<>();
// ==================== CALLBACKS ====================
private GuiAbilityInterface parentGui;
public AbilityPreviewExecutor() {
}
public void setParentGui(GuiAbilityInterface gui) {
this.parentGui = gui;
}
/**
* Start previewing an ability.
*/
public void startPreview(Ability ability, EntityNPCInterface npc) {
stop();
this.previewAbility = ability;
this.previewNpc = npc;
this.phase = AbilityPhase.WINDUP;
this.currentTick = 0;
this.playing = true;
this.paused = false;
this.activeDuration = ability.getPreviewActiveDuration();
// 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);
// Set preview target on the ability
ability.setPreviewTarget(fakeTarget);
// Start tracking NPC movement
if (parentGui != null) {
parentGui.startTrackingMovement();
}
// Create telegraph for preview
previewTelegraph = ability.createTelegraph(npc, fakeTarget);
// Start windup animation
Animation windUpAnim = ability.getWindUpAnimation();
if (windUpAnim != null) {
AnimationData data = npc.display.animationData;
data.setEnabled(true);
data.setAnimation(windUpAnim);
data.animation.paused = false;
}
// Spawn preview entity on first tick if ability spawns during windup
if (ability.spawnPreviewDuringWindup()) {
spawnPreviewEntity();
}
}
/**
* Create an invisible fake target NPC placed in front of the preview NPC.
* This entity is NOT rendered - it only exists for ability targeting logic.
*/
private void createFakeTarget(EntityNPCInterface npc) {
if (npc.worldObj == null) return;
try {
fakeTarget = new EntityCustomNpc(npc.worldObj);
// Position target in front of NPC based on its facing direction
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;
}
}
/**
* Get the fake target entity for abilities that need a target.
*/
public EntityLivingBase getFakeTarget() {
return fakeTarget;
}
public void play() {
if (previewAbility == null || phase == AbilityPhase.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;
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
if (data.animation != null) {
data.animation.paused = true;
}
}
}
public void stop() {
playing = false;
paused = false;
phase = AbilityPhase.IDLE;
currentTick = 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;
}
// Remove fake target
fakeTarget = null;
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(new Animation());
data.animation.paused = false;
}
}
/**
* Tick the preview forward.
*/
public void tick() {
if (!playing || paused || previewAbility == null || previewNpc == null) {
return;
}
currentTick++;
if (previewTelegraph != null) {
previewTelegraph.tick(null);
}
tickEntities();
switch (phase) {
case WINDUP:
tickWindup();
break;
case ACTIVE:
tickActive();
break;
case IDLE:
tickExtended();
break;
default:
break;
}
}
private void tickWindup() {
previewAbility.onPreviewWindUpTick(previewNpc, currentTick);
if (currentTick >= previewAbility.getWindUpTicks()) {
transitionToActive();
}
}
private void tickActive() {
previewAbility.onPreviewActiveTick(previewNpc, currentTick);
if (currentTick == 1 && !previewAbility.spawnPreviewDuringWindup()) {
spawnPreviewEntity();
fireEntities();
}
if (currentTick >= activeDuration) {
transitionToExtended();
}
}
private void tickExtended() {
if (currentTick >= EXTENDED_DURATION) {
playing = false;
}
}
private void transitionToActive() {
phase = AbilityPhase.ACTIVE;
currentTick = 0;
previewTelegraph = null;
// Notify ability of execution (for movement abilities like Slam/Charge/Dash)
previewAbility.onPreviewExecute(previewNpc);
fireEntities();
Animation activeAnim = previewAbility.getActiveAnimation();
if (activeAnim != null && previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(activeAnim);
data.animation.paused = false;
}
}
private void transitionToExtended() {
phase = AbilityPhase.IDLE;
currentTick = 0;
if (previewNpc != null) {
AnimationData data = previewNpc.display.animationData;
data.setAnimation(new Animation());
}
}
private void spawnPreviewEntity() {
Entity entity = previewAbility.createPreviewEntity(previewNpc);
if (entity != null) {
previewEntities.add(entity);
if (parentGui != null) {
parentGui.addPreviewEntity(entity);
}
}
}
private void fireEntities() {
for (Entity entity : previewEntities) {
if (entity instanceof EntityAbilityOrb) {
((EntityAbilityOrb) entity).startPreviewFiring();
} else if (entity instanceof EntityAbilityBeam) {
((EntityAbilityBeam) entity).startPreviewFiring();
} else if (entity instanceof EntityAbilityDisc) {
((EntityAbilityDisc) entity).startPreviewFiring();
}
}
}
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();
}
}
// ==================== GETTERS ====================
public boolean isPlaying() { return playing; }
public boolean isPaused() { return paused; }
public boolean isActive() { return playing || paused; }
public AbilityPhase getPhase() { return phase; }
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";
} else if (paused) {
return "Paused";
} else if (phase == AbilityPhase.WINDUP) {
return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0);
} else if (phase == AbilityPhase.ACTIVE) {
return "Active: " + currentTick + "/" + activeDuration;
} else if (phase == AbilityPhase.IDLE && playing) {
return "Extended: " + currentTick + "/" + EXTENDED_DURATION;
}
return "";
}
}
@@ -0,0 +1,391 @@
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.client.EntityUtil;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.entity.data.ModelData;
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.
*
* 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 ModelData playerdata;
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) {
super(npc);
this.npc = npc;
this.playerdata = ((EntityCustomNpc) npc).modelData;
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) {
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);
// Get the entity to render (could be transformed player model)
EntityLivingBase renderEntity = playerdata.getEntity(npc);
if (renderEntity == null) {
renderEntity = this.npc;
}
// Sync NPC properties to render entity
EntityUtil.Copy(npc, renderEntity);
// 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)
try {
RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks);
} catch (Exception e) {
playerdata.setEntityClass(null);
}
// 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) {
super.keyTyped(par1, par2);
if (par2 == 1) {
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();
}
}
}
@@ -0,0 +1,197 @@
package noppes.npcs.client.gui.util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.ArrayList;
import java.util.List;
/**
* Configurable textured button for auction GUI.
* Supports custom button sizes, icon sizes, and textures.
*/
public class GuiAuctionNavButton extends GuiNpcButton {
// Default auction button textures (18x18)
private static final ResourceLocation DEFAULT_NORMAL = new ResourceLocation("customnpcs", "textures/gui/auction/button.png");
private static final ResourceLocation DEFAULT_PRESSED = new ResourceLocation("customnpcs", "textures/gui/auction/button_press.png");
// Textures
private ResourceLocation textureNormal;
private ResourceLocation texturePressed;
private ResourceLocation iconTexture;
private ItemStack iconItem;
// Dimensions
private int buttonSize;
private int iconSize;
// State
private boolean selected;
private boolean isToggle; // Toggle buttons can be clicked when selected, nav buttons cannot
private final String tooltipKey;
private List<String> customTooltip;
/**
* Create a button with default 18x18 size and 16x16 icon using default textures.
*/
public GuiAuctionNavButton(int id, int x, int y, String tooltipKey, ResourceLocation iconTexture) {
this(id, x, y, 18, 16, tooltipKey, iconTexture, DEFAULT_NORMAL, DEFAULT_PRESSED);
}
/**
* Create a button with default 18x18 size and 16x16 icon with an item icon.
*/
public GuiAuctionNavButton(int id, int x, int y, String tooltipKey, ItemStack iconItem) {
super(id, x, y, 18, 18, "");
this.tooltipKey = tooltipKey;
this.iconTexture = null;
this.iconItem = iconItem;
this.buttonSize = 18;
this.iconSize = 16;
this.textureNormal = DEFAULT_NORMAL;
this.texturePressed = DEFAULT_PRESSED;
this.selected = false;
this.customTooltip = null;
}
/**
* Create a fully customizable button.
*
* @param id Button ID
* @param x X position
* @param y Y position
* @param buttonSize Size of the button background texture (e.g., 18 for 18x18, 10 for 10x10)
* @param iconSize Size of the icon texture (e.g., 16 for 16x16, 8 for 8x8)
* @param tooltipKey Lang key for tooltip
* @param iconTexture Icon texture to draw inside the button
* @param textureNormal Background texture for normal state
* @param texturePressed Background texture for pressed/hover state
*/
public GuiAuctionNavButton(int id, int x, int y, int buttonSize, int iconSize, String tooltipKey,
ResourceLocation iconTexture, ResourceLocation textureNormal, ResourceLocation texturePressed) {
super(id, x, y, buttonSize, buttonSize, "");
this.tooltipKey = tooltipKey;
this.iconTexture = iconTexture;
this.iconItem = null;
this.buttonSize = buttonSize;
this.iconSize = iconSize;
this.textureNormal = textureNormal;
this.texturePressed = texturePressed;
this.selected = false;
this.customTooltip = null;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isSelected() {
return selected;
}
/**
* Set whether this is a toggle button.
* Toggle buttons can be clicked when selected (to toggle off).
* Nav buttons cannot be clicked when selected.
*/
public GuiAuctionNavButton setToggle(boolean toggle) {
this.isToggle = toggle;
return this;
}
public boolean isHovered() {
return field_146123_n;
}
/**
* Set a custom multi-line tooltip. If null, uses the default tooltipKey translation.
*/
public void setCustomTooltip(List<String> tooltip) {
this.customTooltip = tooltip;
}
/**
* Get the tooltip lines for display.
*/
public List<String> getTooltipLines() {
if (customTooltip != null && !customTooltip.isEmpty()) {
return customTooltip;
}
List<String> lines = new ArrayList<>();
if (tooltipKey != null && !tooltipKey.isEmpty()) {
lines.add(StatCollector.translateToLocal(tooltipKey));
}
return lines;
}
public String getTooltipText() {
return tooltipKey != null ? StatCollector.translateToLocal(tooltipKey) : "";
}
@Override
public void drawButton(Minecraft mc, int mouseX, int mouseY) {
if (!this.visible) {
return;
}
// Check if mouse is hovering
boolean hovered = mouseX >= xPosition && mouseX < xPosition + width
&& mouseY >= yPosition && mouseY < yPosition + height;
field_146123_n = hovered;
// Draw button background
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if (selected || hovered) {
mc.getTextureManager().bindTexture(texturePressed);
} else {
mc.getTextureManager().bindTexture(textureNormal);
}
Gui.func_146110_a(xPosition, yPosition, 0, 0, buttonSize, buttonSize, buttonSize, buttonSize);
// Calculate icon offset to center it
int iconOffset = (buttonSize - iconSize) / 2;
int iconX = xPosition + iconOffset;
int iconY = yPosition + iconOffset;
if (iconItem != null) {
// Render item
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
RenderItem itemRenderer = RenderItem.getInstance();
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, iconItem, iconX, iconY);
GL11.glDisable(GL11.GL_LIGHTING);
RenderHelper.disableStandardItemLighting();
} else if (iconTexture != null) {
// Render texture icon
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(iconTexture);
Gui.func_146110_a(iconX, iconY, 0, 0, iconSize, iconSize, iconSize, iconSize);
}
}
@Override
public boolean mousePressed(Minecraft minecraft, int mouseX, int mouseY) {
// Don't allow clicking if selected (for nav buttons, not toggle buttons)
if (selected && !isToggle) {
return false;
}
return enabled && visible && mouseX >= xPosition && mouseX < xPosition + width
&& mouseY >= yPosition && mouseY < yPosition + height;
}
/**
* Check if this button contains the given mouse coordinates.
*/
public boolean isMouseOver(int mouseX, int mouseY) {
return mouseX >= xPosition && mouseX < xPosition + width
&& mouseY >= yPosition && mouseY < yPosition + height;
}
}
@@ -9,7 +9,7 @@ import noppes.npcs.constants.EnumDiagramLayout;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -18,11 +18,11 @@ import org.lwjgl.opengl.GL12;
public class GuiModelInterface2 extends GuiNPCInterface2 {
public ModelData playerdata;
private static float rotation = 0;
protected static float rotation = 0;
private GuiNpcButton left, right, zoom, unzoom;
private static float zoomed = 60;
protected static float zoomed = 60;
public int xOffset = 0;
public int yOffset = 0;
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
public abstract class GuiNPCInterface extends GuiScreen {
public EntityClientPlayerMP player;
@@ -48,6 +49,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
public String title;
private ResourceLocation background = null;
public boolean closeOnEsc = false;
public Supplier<Boolean> closeOnEscSupplier = null;
public int guiLeft, guiTop, xSize, ySize;
private SubGuiInterface subgui;
public int mouseX, mouseY, mouseScroll;
@@ -55,6 +57,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
public float bgScaleX = 1;
public float bgScaleY = 1;
public float bgScaleZ = 1;
public int bgTextureHeight = 256; // Actual content height in texture (for bottom border stitching)
public GuiNPCInterface(EntityNPCInterface npc) {
this.player = Minecraft.getMinecraft().thePlayer;
@@ -72,6 +75,11 @@ public abstract class GuiNPCInterface extends GuiScreen {
background = new ResourceLocation("customnpcs", "textures/gui/" + texture);
}
public void setBackground(String texture, int textureHeight) {
background = new ResourceLocation("customnpcs", "textures/gui/" + texture);
bgTextureHeight = textureHeight;
}
public ResourceLocation getResource(String texture) {
return new ResourceLocation("customnpcs", "textures/gui/" + texture);
}
@@ -104,6 +112,10 @@ public abstract class GuiNPCInterface extends GuiScreen {
rotateLeft = new GuiNpcButton(0, guiLeft + 44 + xOffsetNpc + xOffsetButton, guiTop + yOffsetNpc + yOffsetButton, 20, 20, "<");
rotateRight = new GuiNpcButton(0, guiLeft + 66 + xOffsetNpc + xOffsetButton, guiTop + yOffsetNpc + yOffsetButton, 20, 20, ">");
}
//Important for GuiScriptTextArea
for (GuiNpcTextField tf : textfields.values())
tf.initGui();
}
@Override
@@ -202,6 +214,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
}
}
}
@Override
public void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
if (subgui != null) {
@@ -237,6 +250,29 @@ public abstract class GuiNPCInterface extends GuiScreen {
@Override
public void keyTyped(char c, int i) {
/*
Fixes closing sub with escape closes all of its parents.
The outermost GUI (root of all subs) closes the deepest open sub on ESC.
*/
boolean isSub = this instanceof SubGuiInterface;
boolean shouldClose = closeOnEsc;
if (closeOnEscSupplier != null) {
try {
shouldClose = closeOnEscSupplier.get();
} catch (Exception ignored) {
}
}
if (shouldClose && !isSub && (i == 1 || (!GuiNpcTextField.isFieldActive() && isInventoryKey(i)))) {
SubGuiInterface sub = getSubGui();
if (sub != null)
sub.close();
else
close();
}
if (subgui != null)
subgui.keyTyped(c, i);
for (GuiNpcTextField tf : textfields.values())
@@ -246,27 +282,18 @@ public abstract class GuiNPCInterface extends GuiScreen {
guiScrollableComponent.keyTyped(c, i);
}
/*
Fixes closing sub with escape closes all of its parents.
The outermost GUI (root of all subs) closes the deepest open sub on ESC.
*/
boolean isSub = this instanceof SubGuiInterface;
if (closeOnEsc && !isSub && (i == 1 || !GuiNpcTextField.isFieldActive() && isInventoryKey(i))) {
SubGuiInterface sub = getSubGui();
if (sub != null)
sub.close();
else
close();
}
}
public void onGuiClosed() {
GuiNpcTextField.unfocus();
}
public void closeOnEsc(Supplier<Boolean> close) {
this.closeOnEscSupplier = close;
}
public void close() {
if(GuiNpcTextField.activeTextfield != null)
if (GuiNpcTextField.activeTextfield != null)
GuiNpcTextField.unfocus();
Keyboard.enableRepeatEvents(false);
@@ -382,6 +409,11 @@ public abstract class GuiNPCInterface extends GuiScreen {
button.drawHover(i, j, subGui);
}
}
for (GuiNpcTextField textField : textfields.values()) {
if (textField.hasHoverText()) {
textField.drawHover(i, j, subGui);
}
}
for (GuiScreen gui : extra.values())
gui.drawScreen(i, j, f);
@@ -400,23 +432,44 @@ public abstract class GuiNPCInterface extends GuiScreen {
GL11.glTranslatef(guiLeft, guiTop, 0);
GL11.glScalef(bgScale * bgScaleX, bgScale * bgScaleY, bgScale * bgScaleZ);
mc.renderEngine.bindTexture(background);
// Handle Y dimension: if ySize < texture content height, stitch bottom border
int topHeight = ySize;
int bottomHeight = 0;
int bottomTextureV = 0;
if (ySize < bgTextureHeight) {
// Keep bottom border from texture bottom (last 6 pixels of actual content)
bottomHeight = 6;
topHeight = ySize - bottomHeight;
bottomTextureV = bgTextureHeight - bottomHeight;
}
if (xSize > 256) {
// GUI wider than texture: draw left portion, then right portion from texture edge
drawTexturedModalRect(0, 0, 0, 0, 250, ySize);
drawTexturedModalRect(250, 0, 256 - (xSize - 250), 0, xSize - 250, ySize);
drawTexturedModalRect(0, 0, 0, 0, 250, topHeight);
drawTexturedModalRect(250, 0, 256 - (xSize - 250), 0, xSize - 250, topHeight);
if (bottomHeight > 0) {
drawTexturedModalRect(0, topHeight, 0, bottomTextureV, 250, bottomHeight);
drawTexturedModalRect(250, topHeight, 256 - (xSize - 250), bottomTextureV, xSize - 250, bottomHeight);
}
} else if (xSize < 256) {
// GUI narrower than texture: stitch left and right edges together
// Left portion (first half of GUI)
int leftWidth = xSize / 2;
// Right portion width (remaining)
int rightWidth = xSize - leftWidth;
// Draw left side from texture start
drawTexturedModalRect(0, 0, 0, 0, leftWidth, ySize);
// Draw right side from texture end (256 - rightWidth)
drawTexturedModalRect(leftWidth, 0, 256 - rightWidth, 0, rightWidth, ySize);
// Draw top portion
drawTexturedModalRect(0, 0, 0, 0, leftWidth, topHeight);
drawTexturedModalRect(leftWidth, 0, 256 - rightWidth, 0, rightWidth, topHeight);
// Draw bottom border strip
if (bottomHeight > 0) {
drawTexturedModalRect(0, topHeight, 0, bottomTextureV, leftWidth, bottomHeight);
drawTexturedModalRect(leftWidth, topHeight, 256 - rightWidth, bottomTextureV, rightWidth, bottomHeight);
}
} else {
// GUI exactly 256px: draw full texture
drawTexturedModalRect(0, 0, 0, 0, xSize, ySize);
// GUI exactly 256px wide
drawTexturedModalRect(0, 0, 0, 0, xSize, topHeight);
if (bottomHeight > 0) {
drawTexturedModalRect(0, topHeight, 0, bottomTextureV, xSize, bottomHeight);
}
}
GL11.glPopMatrix();
}
@@ -517,6 +570,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
public void drawNpcWithExtras(EntityLivingBase entity, int mouseX, int mouseY, float partialTicks) {
drawNpc(entity, mouseX, mouseY, partialTicks);
}
public void drawNpc(EntityLivingBase entity, int mouseX, int mouseY, float partialTicks) {
if (hasSubGui() && !drawNPConSub)
return;
Loaded 100 of 391 files, more files were not shown because too many files have changed in this diff. Show more