Merge branch 'dev' into janino-scripts

This commit is contained in:
bigguy345 committed 2026-01-22 19:53:18 +02:00
commit 3f8373d76f
48 files changed
+3333 -2035

No files matched your search

@@ -0,0 +1,214 @@
package noppes.npcs.controllers;
import foxz.utils.Market;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.roles.RoleTrader;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* Central registry for linked market synchronization.
* Tracks which RoleTrader instances use which markets,
* and which players are viewing each market.
*
* This enables immediate sync across all traders sharing
* the same market when a purchase occurs.
*/
public class MarketRegistry {
// marketName -> Set of traders using this market (WeakHashMap for auto-cleanup)
private static final Map<String, Set<RoleTrader>> marketTraders = new ConcurrentHashMap<>();
// marketName -> Set of players viewing this market (across all NPCs)
private static final Map<String, Set<EntityPlayerMP>> marketViewers = new ConcurrentHashMap<>();
// ==================== Trader Registration ====================
/**
* Register a trader as using a linked market.
* Should be called when NPC loads or marketName is set.
*/
public static void registerTrader(String marketName, RoleTrader trader) {
if (marketName == null || marketName.isEmpty() || trader == null) return;
Set<RoleTrader> traders = marketTraders.computeIfAbsent(marketName,
k -> Collections.newSetFromMap(new WeakHashMap<>()));
synchronized (traders) {
traders.add(trader);
}
}
/**
* Unregister a trader from a linked market.
* Should be called when NPC unloads or marketName changes.
*/
public static void unregisterTrader(String marketName, RoleTrader trader) {
if (marketName == null || marketName.isEmpty() || trader == null) return;
Set<RoleTrader> traders = marketTraders.get(marketName);
if (traders != null) {
synchronized (traders) {
traders.remove(trader);
if (traders.isEmpty()) {
marketTraders.remove(marketName);
}
}
}
}
/**
* Change a trader's market registration.
* Handles unregistering from old market and registering to new.
*/
public static void updateTraderMarket(String oldMarket, String newMarket, RoleTrader trader) {
if (trader == null) return;
if (oldMarket != null && !oldMarket.isEmpty()) {
unregisterTrader(oldMarket, trader);
}
if (newMarket != null && !newMarket.isEmpty()) {
registerTrader(newMarket, trader);
}
}
// ==================== Viewer Registration ====================
/**
* Register a player as viewing a market (via any NPC).
* Should be called when player opens trader GUI with linked market.
*/
public static void registerViewer(String marketName, EntityPlayerMP player) {
if (marketName == null || marketName.isEmpty() || player == null) return;
Set<EntityPlayerMP> viewers = marketViewers.computeIfAbsent(marketName,
k -> Collections.newSetFromMap(new WeakHashMap<>()));
synchronized (viewers) {
viewers.add(player);
}
}
/**
* Unregister a player from viewing a market.
* Should be called when player closes trader GUI.
*/
public static void unregisterViewer(String marketName, EntityPlayerMP player) {
if (marketName == null || marketName.isEmpty() || player == null) return;
Set<EntityPlayerMP> viewers = marketViewers.get(marketName);
if (viewers != null) {
synchronized (viewers) {
viewers.remove(player);
if (viewers.isEmpty()) {
marketViewers.remove(marketName);
}
}
}
}
// ==================== Synchronization ====================
/**
* Sync stock data to all traders and viewers of a market.
* Called after a purchase to update all linked traders and their viewers.
*
* @param marketName The market to sync
*/
public static void syncMarket(String marketName) {
if (marketName == null || marketName.isEmpty()) return;
// Get latest data from cache
NBTTagCompound marketData = Market.getMarketCache(marketName);
if (marketData == null) return;
// Update all traders' internal stock data
Set<RoleTrader> traders = marketTraders.get(marketName);
if (traders != null) {
NBTTagCompound stockData = marketData.getCompoundTag("Stock");
synchronized (traders) {
// Clean up any null references (WeakHashMap cleanup)
traders.removeIf(t -> t == null || t.npc == null);
for (RoleTrader trader : traders) {
// Update stock data from cache
if (stockData != null && stockData.hasKey("EnableStock")) {
trader.stock.readFromNBT(stockData);
}
}
}
}
// Sync all viewers (across all NPCs for this market)
syncMarketViewers(marketName);
}
/**
* Sync stock data to all players viewing a specific market.
* Each viewer gets data relative to their own player (for per-player stock display).
*/
public static void syncMarketViewers(String marketName) {
if (marketName == null || marketName.isEmpty()) return;
Set<EntityPlayerMP> viewers = marketViewers.get(marketName);
if (viewers == null || viewers.isEmpty()) return;
// Find any trader with this market to use for sync (they all have same data now)
Set<RoleTrader> traders = marketTraders.get(marketName);
if (traders == null || traders.isEmpty()) return;
RoleTrader syncSource = null;
synchronized (traders) {
for (RoleTrader trader : traders) {
if (trader != null && trader.npc != null) {
syncSource = trader;
break;
}
}
}
if (syncSource == null) return;
// Sync to all viewers
synchronized (viewers) {
// Remove disconnected players
viewers.removeIf(p -> p == null || p.playerNetServerHandler == null);
for (EntityPlayerMP viewer : viewers) {
syncSource.syncToPlayer(viewer);
}
}
}
// ==================== Utility ====================
/**
* Get count of traders registered to a market (for debugging/info).
*/
public static int getTraderCount(String marketName) {
Set<RoleTrader> traders = marketTraders.get(marketName);
return traders != null ? traders.size() : 0;
}
/**
* Get count of viewers for a market (for debugging/info).
*/
public static int getViewerCount(String marketName) {
Set<EntityPlayerMP> viewers = marketViewers.get(marketName);
return viewers != null ? viewers.size() : 0;
}
/**
* Clear all registrations (for server shutdown/reload).
*/
public static void clear() {
marketTraders.clear();
marketViewers.clear();
}
}
@@ -0,0 +1,230 @@
package noppes.npcs.controllers.data;
import kamkeel.npcs.util.VaultUtil;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.handler.IPlayerCurrencyData;
import noppes.npcs.config.ConfigMarket;
/**
* Stores player currency balance.
* This data is NOT profile slot bound - all profile slots share the same currency pool.
* When Vault API is available and UseVault config is enabled, operations delegate to Vault.
* The built-in CNPC+ currency data is always preserved in NBT, but unused when Vault is active.
*/
public class PlayerCurrencyData implements IPlayerCurrencyData {
private final PlayerData playerData;
// Built-in CNPC+ currency (always saved, used as fallback)
private long balance;
private long lifetimeEarned;
private long lifetimeSpent;
public PlayerCurrencyData(PlayerData playerData) {
this.playerData = playerData;
this.balance = ConfigMarket.StartingBalance;
this.lifetimeEarned = 0;
this.lifetimeSpent = 0;
}
/**
* Check if Vault should be used for currency operations.
* Requires both config enabled AND Vault actually available.
*/
private boolean shouldUseVault() {
return ConfigMarket.UseVault && VaultUtil.isEnabled();
}
/**
* Get player name for Vault operations
*/
private String getPlayerName() {
if (playerData != null && playerData.player != null) {
return playerData.player.getCommandSenderName();
}
return playerData != null ? playerData.playername : null;
}
public void readFromNBT(NBTTagCompound compound) {
if (compound.hasKey("CurrencyBalance")) {
this.balance = compound.getLong("CurrencyBalance");
} else {
this.balance = ConfigMarket.StartingBalance;
}
this.lifetimeEarned = compound.getLong("CurrencyLifetimeEarned");
this.lifetimeSpent = compound.getLong("CurrencyLifetimeSpent");
}
public void writeToNBT(NBTTagCompound compound) {
// Always save built-in currency data (preserved even when using Vault)
compound.setLong("CurrencyBalance", this.balance);
compound.setLong("CurrencyLifetimeEarned", this.lifetimeEarned);
compound.setLong("CurrencyLifetimeSpent", this.lifetimeSpent);
}
/**
* Get the current balance
*/
@Override
public long getBalance() {
if (shouldUseVault()) {
String playerName = getPlayerName();
if (playerName != null) {
return (long) VaultUtil.getBalance(playerName);
}
}
return balance;
}
/**
* Set the balance directly (use with caution)
*/
@Override
public void setBalance(long balance) {
if (balance < 0) {
balance = 0;
}
if (balance > ConfigMarket.MaxBalance) {
balance = ConfigMarket.MaxBalance;
}
if (shouldUseVault()) {
String playerName = getPlayerName();
if (playerName != null) {
VaultUtil.setBalance(playerName, balance);
return;
}
}
this.balance = balance;
}
/**
* Add currency to balance (deposit)
* @param amount Amount to add
* @return true if successful, false if would exceed max balance
*/
@Override
public boolean deposit(long amount) {
if (amount <= 0) {
return false;
}
if (shouldUseVault()) {
String playerName = getPlayerName();
if (playerName != null) {
boolean success = VaultUtil.addMoney(playerName, amount);
if (success) {
this.lifetimeEarned += amount;
}
return success;
}
}
// Built-in currency
long newBalance = this.balance + amount;
if (newBalance > ConfigMarket.MaxBalance) {
return false;
}
if (newBalance < this.balance) {
// Overflow protection
return false;
}
this.balance = newBalance;
this.lifetimeEarned += amount;
return true;
}
/**
* Remove currency from balance (withdraw)
* @param amount Amount to remove
* @return true if successful, false if insufficient funds
*/
@Override
public boolean withdraw(long amount) {
if (amount <= 0) {
return false;
}
if (shouldUseVault()) {
String playerName = getPlayerName();
if (playerName != null) {
boolean success = VaultUtil.withdrawMoney(playerName, amount);
if (success) {
this.lifetimeSpent += amount;
}
return success;
}
}
// Built-in currency
if (this.balance < amount) {
return false;
}
this.balance -= amount;
this.lifetimeSpent += amount;
return true;
}
/**
* Check if player can afford an amount
*/
@Override
public boolean canAfford(long amount) {
if (shouldUseVault()) {
String playerName = getPlayerName();
if (playerName != null) {
return VaultUtil.has(playerName, amount);
}
}
return this.balance >= amount;
}
/**
* Get lifetime earned currency
*/
@Override
public long getLifetimeEarned() {
return lifetimeEarned;
}
/**
* Get lifetime spent currency
*/
@Override
public long getLifetimeSpent() {
return lifetimeSpent;
}
/**
* Format the balance for display
*/
@Override
public String formatBalance() {
if (shouldUseVault()) {
return VaultUtil.format(getBalance());
}
return formatAmount(this.balance);
}
/**
* Format an amount for display
*/
public static String formatAmount(long amount) {
return String.format("%,d %s", amount, ConfigMarket.CurrencyName);
}
/**
* Check if Vault is being used for currency operations.
* Returns true only if config is enabled AND Vault is actually available.
*/
@Override
public boolean isUsingVault() {
return shouldUseVault();
}
/**
* Check if Vault is configured (regardless of availability)
*/
public boolean isVaultConfigured() {
return ConfigMarket.UseVault;
}
}
@@ -17,6 +17,7 @@ import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import noppes.npcs.api.entity.ICustomNpc;
import noppes.npcs.api.handler.IPlayerBankData;
import noppes.npcs.api.handler.IPlayerCurrencyData;
import noppes.npcs.api.handler.IPlayerData;
import noppes.npcs.api.handler.IPlayerDialogData;
import noppes.npcs.api.handler.IPlayerFactionData;
@@ -59,6 +60,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
public DataSkinOverlays skinOverlays = new DataSkinOverlays(this);
public MagicData magicData = new MagicData();
// Currency data - NOT slot-bound, shared across all profile slots
public PlayerCurrencyData currencyData = new PlayerCurrencyData(this);
public ActionManager actionManager = new ActionManager();
public PlayerDataScript scriptData;
@@ -397,6 +401,10 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
return mailData;
}
public IPlayerCurrencyData getCurrencyData() {
return currencyData;
}
public synchronized void save() {
// Don't Save this is a Modification of a Profile's PlayerData
Profile profile = ProfileController.Instance.getProfile(UUID.fromString(uuid));
@@ -406,6 +414,9 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
}
final NBTTagCompound compound = getNBT();
// Currency data is saved at player level, NOT per profile slot
currencyData.writeToNBT(compound);
final String filename;
if (ConfigMain.DatFormat) {
filename = uuid + ".dat";
@@ -442,6 +453,10 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData {
if (data.hasNoTags()) {
data = getNBT();
}
// Load currency BEFORE setNBT - currency is player-level, NOT per profile slot
currencyData.readFromNBT(data);
setNBT(data);
}
@@ -0,0 +1,353 @@
package noppes.npcs.controllers.data;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.constants.EnumStockReset;
import java.util.HashMap;
import java.util.Map;
/**
* Manages trader stock system including:
* - Per-slot stock limits
* - Per-player vs per-server stock tracking
* - Automatic stock reset timers
*/
public class TraderStock {
// Stock configuration
public boolean enableStock = false;
public boolean perPlayer = false; // false = per-server, true = per-player
// Reset configuration (mirrors Quest cooldown system)
public EnumStockReset resetType = EnumStockReset.NONE;
public long customResetTime = 0; // For MCCUSTOM/RLCUSTOM types (in ticks or ms)
// Stock quantities per slot (max stock, -1 = unlimited)
public int[] maxStock = new int[18];
// Current stock (per-server mode)
public int[] currentStock = new int[18];
public long lastResetTime = 0;
// Per-player stock tracking
public HashMap<String, PlayerTraderStock> playerStock = new HashMap<>();
public TraderStock() {
for (int i = 0; i < 18; i++) {
maxStock[i] = -1; // -1 = unlimited
currentStock[i] = -1;
}
}
/**
* Get available stock for a slot
* @param slot The slot index
* @param playerName The player name (for per-player mode)
* @return Available stock count, or Integer.MAX_VALUE if unlimited
*/
public synchronized int getAvailableStock(int slot, String playerName) {
if (!enableStock || slot < 0 || slot >= 18 || maxStock[slot] < 0) {
return Integer.MAX_VALUE; // Unlimited
}
if (perPlayer) {
PlayerTraderStock pStock = playerStock.get(playerName);
if (pStock == null) {
return maxStock[slot]; // Not purchased yet
}
return pStock.getStock(slot, maxStock[slot]);
}
if (currentStock[slot] < 0) {
return maxStock[slot];
}
return Math.max(0, currentStock[slot]);
}
/**
* Check if stock is available for purchase
*/
public boolean hasStock(int slot, String playerName, int amount) {
return getAvailableStock(slot, playerName) >= amount;
}
/**
* Consume stock when purchase is made
* @return true if successful, false if insufficient stock
*/
public synchronized boolean consumeStock(int slot, String playerName, int amount) {
if (!enableStock || slot < 0 || slot >= 18 || maxStock[slot] < 0) {
return true; // Unlimited, always succeeds
}
if (perPlayer) {
PlayerTraderStock pStock = playerStock.computeIfAbsent(
playerName, k -> new PlayerTraderStock());
return pStock.consumeStock(slot, maxStock[slot], amount);
}
if (currentStock[slot] < 0) {
currentStock[slot] = maxStock[slot];
}
if (currentStock[slot] >= amount) {
currentStock[slot] -= amount;
return true;
}
return false;
}
/**
* Check if stock should reset based on current time
* @param currentTime Current MC world time (ticks) or real time (ms) depending on reset type
*/
public boolean shouldReset(long currentTime) {
if (resetType == EnumStockReset.NONE) {
return false;
}
long elapsed = currentTime - lastResetTime;
long resetInterval = getResetInterval();
return elapsed >= resetInterval;
}
/**
* Reset all stock to max values
* @param currentTime Current time to record as reset time
*/
public synchronized void resetStock(long currentTime) {
lastResetTime = currentTime;
// Reset per-server stock
for (int i = 0; i < 18; i++) {
currentStock[i] = maxStock[i];
}
// Clear per-player stock (cleanup per-player data on reset)
playerStock.clear();
}
/**
* Get reset interval based on reset type
* @return Interval in ticks (MC time) or milliseconds (real time)
*/
public long getResetInterval() {
switch (resetType) {
case MCDAILY:
return 24000; // 1 MC day in ticks
case MCWEEKLY:
return 168000; // 7 MC days in ticks
case MCCUSTOM:
return customResetTime; // Custom ticks
case RLDAILY:
return 86400000L; // 24 hours in ms
case RLWEEKLY:
return 604800000L; // 7 days in ms
case RLCUSTOM:
return customResetTime; // Custom ms
default:
return Long.MAX_VALUE;
}
}
/**
* Get time until next reset
* @param currentTime Current time
* @return Time remaining until reset, or -1 if no reset scheduled
*/
public long getTimeUntilReset(long currentTime) {
if (resetType == EnumStockReset.NONE) {
return -1;
}
long elapsed = currentTime - lastResetTime;
long interval = getResetInterval();
return Math.max(0, interval - elapsed);
}
/**
* Format time until reset for display
* @param currentTime Current time
* @return Formatted string like "2 hours" or "1 day, 5 hours"
*/
public String getTimeUntilResetFormatted(long currentTime) {
long remaining = getTimeUntilReset(currentTime);
if (remaining < 0) {
return "";
}
if (resetType.isRealTime()) {
// Convert ms to readable format
long hours = remaining / 3600000L;
long days = hours / 24;
hours = hours % 24;
if (days > 0) {
return days + " day" + (days != 1 ? "s" : "") +
(hours > 0 ? ", " + hours + " hour" + (hours != 1 ? "s" : "") : "");
} else if (hours > 0) {
return hours + " hour" + (hours != 1 ? "s" : "");
} else {
long minutes = remaining / 60000L;
return minutes + " minute" + (minutes != 1 ? "s" : "");
}
} else {
// Convert ticks to MC time format
long mcHours = remaining / 1000; // 1000 ticks = 1 MC hour
long mcDays = mcHours / 24;
mcHours = mcHours % 24;
if (mcDays > 0) {
return mcDays + " MC day" + (mcDays != 1 ? "s" : "") +
(mcHours > 0 ? ", " + mcHours + " MC hour" + (mcHours != 1 ? "s" : "") : "");
} else {
return mcHours + " MC hour" + (mcHours != 1 ? "s" : "");
}
}
}
/**
* Set stock for a specific slot
*/
public void setMaxStock(int slot, int amount) {
if (slot >= 0 && slot < 18) {
maxStock[slot] = amount;
if (currentStock[slot] < 0 || currentStock[slot] > amount) {
currentStock[slot] = amount;
}
}
}
/**
* Validate and clamp all current stock values to not exceed max stock.
* Should be called when trader GUI opens to ensure consistency.
* @return true if any stock was clamped
*/
public boolean validateStock() {
boolean changed = false;
for (int i = 0; i < 18; i++) {
if (maxStock[i] >= 0) {
// Has a max limit
if (currentStock[i] < 0) {
// Not initialized, set to max
currentStock[i] = maxStock[i];
changed = true;
} else if (currentStock[i] > maxStock[i]) {
// Exceeds max, clamp down
currentStock[i] = maxStock[i];
changed = true;
}
}
}
// Also validate per-player stock
for (PlayerTraderStock pStock : playerStock.values()) {
for (int i = 0; i < 18; i++) {
if (maxStock[i] >= 0) {
int available = pStock.getStock(i, maxStock[i]);
if (available < 0) {
// Over-purchased somehow, reset
pStock.purchasedAmounts[i] = maxStock[i];
changed = true;
}
}
}
}
return changed;
}
// ==================== NBT Serialization ====================
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setBoolean("EnableStock", enableStock);
compound.setBoolean("PerPlayer", perPlayer);
compound.setInteger("ResetType", resetType.ordinal());
compound.setLong("CustomResetTime", customResetTime);
compound.setIntArray("MaxStock", maxStock);
compound.setIntArray("CurrentStock", currentStock);
compound.setLong("LastResetTime", lastResetTime);
// Save per-player stock
NBTTagList playerList = new NBTTagList();
for (Map.Entry<String, PlayerTraderStock> entry : playerStock.entrySet()) {
NBTTagCompound playerTag = new NBTTagCompound();
playerTag.setString("Player", entry.getKey());
entry.getValue().writeToNBT(playerTag);
playerList.appendTag(playerTag);
}
compound.setTag("PlayerStock", playerList);
return compound;
}
public void readFromNBT(NBTTagCompound compound) {
enableStock = compound.getBoolean("EnableStock");
perPlayer = compound.getBoolean("PerPlayer");
int resetOrdinal = compound.getInteger("ResetType");
if (resetOrdinal >= 0 && resetOrdinal < EnumStockReset.values().length) {
resetType = EnumStockReset.values()[resetOrdinal];
}
customResetTime = compound.getLong("CustomResetTime");
int[] loadedMax = compound.getIntArray("MaxStock");
int[] loadedCurrent = compound.getIntArray("CurrentStock");
if (loadedMax != null && loadedMax.length == 18) {
maxStock = loadedMax;
}
if (loadedCurrent != null && loadedCurrent.length == 18) {
currentStock = loadedCurrent;
}
lastResetTime = compound.getLong("LastResetTime");
// Load per-player stock
playerStock.clear();
NBTTagList playerList = compound.getTagList("PlayerStock", 10);
for (int i = 0; i < playerList.tagCount(); i++) {
NBTTagCompound playerTag = playerList.getCompoundTagAt(i);
String playerName = playerTag.getString("Player");
PlayerTraderStock pStock = new PlayerTraderStock();
pStock.readFromNBT(playerTag);
playerStock.put(playerName, pStock);
}
}
// ==================== Inner Class for Per-Player Stock ====================
public static class PlayerTraderStock {
public int[] purchasedAmounts = new int[18];
public PlayerTraderStock() {
for (int i = 0; i < 18; i++) {
purchasedAmounts[i] = 0;
}
}
public int getStock(int slot, int maxStock) {
if (slot < 0 || slot >= 18) return 0;
return Math.max(0, maxStock - purchasedAmounts[slot]);
}
public boolean consumeStock(int slot, int maxStock, int amount) {
if (slot < 0 || slot >= 18) return false;
if (getStock(slot, maxStock) >= amount) {
purchasedAmounts[slot] += amount;
return true;
}
return false;
}
public void writeToNBT(NBTTagCompound compound) {
compound.setIntArray("Purchased", purchasedAmounts);
}
public void readFromNBT(NBTTagCompound compound) {
int[] loaded = compound.getIntArray("Purchased");
if (loaded != null && loaded.length == 18) {
purchasedAmounts = loaded;
}
}
}
}